Skip to content Skip to sidebar Skip to footer

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 t

Solution 1:

Do you actually need to post to a tab or just display the response? This will post and get a response you can do something with. Make sure your CORS header is set correctly too.

<meta http-equiv="Content-Security-Policy" content="default-src 'self' www.demo.com; script-src 'self'; img-src http: https: data:; style-src 'self' 'unsafe-inline'">

functionajax(url) {
    returnnewPromise(function(resolve, reject) {
        var xhr = newXMLHttpRequest();
        xhr.onload = function() {
            resolve(this.responseText);
        };
        xhr.onerror = reject;
        xhr.open('POST', url);
        xhr.send();
    });
}

ajax("www.demo.com/test.php?q=" + params).then(function(result) {
    //Do something with result
}).catch(function(err) {
      console.log("Error: " + err.message);
});

Solution 2:

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:

functionsubmitForm(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);

Post a Comment for "Open A Tab And Make A Post Request To It In A Firefox Webextension"