Jérémie Bertrand Jérémie Bertrand - 5 months ago 46
Javascript Question

Open a tab and make a POST request to it in a firefox webextension

I try to migrate my firefox addon wich use low level SDK API to WebExtension and at some point I want to POST data url-encoded to a new tab.

With the low level API it is possible through the following code:

const querystring = require('sdk/querystring');
let stringStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
stringStream.data = querystring.stringify(params); // params is a json data

let postData = Cc["@mozilla.org/network/mime-input-stream;1"].createInstance(Ci.nsIMIMEInputStream);
postData.addHeader("Content-Type", "application/x-www-form-urlencoded");
postData.addContentLength = true;
postData.setData(stringStream);

var tabBrowser = Cc["@mozilla.org/appshell/window-mediator;1"].getService(Ci.nsIWindowMediator).getMostRecentWindow("navigator:browser").gBrowser;
var selectedTabIndex = tabBrowser.tabContainer.selectedIndex;
var newTab = tabBrowser.loadOneTab("https://myurl.com/", {
inBackground: false,
postData: postData
});
tabBrowser.moveTabTo(newTab, selectedTabIndex + 1);


But I haven't found a WebExtension equivalent.

Is it possible or the only solution is to create a form and submit it in js?

Answer

Right now the only solution is to create a form in the new tab and submit it. In the background script:

// tab creation
browser.tabs.create({ index: tab.index + 1, url: "https://myurl.com/" }, function (tab) {
    // load content script submitForm.js
    browser.tabs.executeScript(tab.id, { file: "submitForm.js" }, function () {
        // send message to submitForl.js with parameters
        chrome.tabs.sendMessage(tab.id, {url: tab.url, message: 'hello world'});
    });
});

submitForm content:

function submitForm(request, sender, sendResponse)
{
    var f = document.createElement('form');
    f.setAttribute('method','post');
    f.setAttribute('action','https://myurl.com/form');

    var f1 = document.createElement('input');
    f1.setAttribute('type','hidden');
    f1.setAttribute('name','url]');
    f1.setAttribute('value', request.url);
    f.appendChild(f1);

    var f2 = document.createElement('input');
    f2.setAttribute('type','hidden');
    f2.setAttribute('name','content');
    f2.setAttribute('value', request.message);
    f.appendChild(f2);

    document.getElementsByTagName('body')[0].appendChild(f);
    f.submit();
}

// listen for messages and execute submitForm
chrome.runtime.onMessage.addListener(submitForm);
Comments