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

In my addon I have to submit data as urlencoded POST, for now I used a js script to do that (inject a form in the current page and submit it) but I wonder if there is a solution to do that with the Firefox Addon SDK?

I haven't found a clue in the high-level API but I am less familiar with the low-level, is it possible with the 'window/utils' openDialog method? There is some args parameter but I don't know how to use it.

Thanks.

EDIT

To be specific I need to mimic the behavior of an html form in a new tab.

Upvotes: 3

Views: 1301

Answers (3)

Just to add code to my comment, I did this:

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

Upvotes: 1

Noitidart
Noitidart

Reputation: 37238

Check out these two topics: (1) Replication of Form method with loadOneTab and (2) Use Blob on firefox add-on

An interesting thing you can do is, XHR request it and with the returned source make it a blob and load load blob in tab:

var {Blob, File} = Cu.import("resource://gre/modules/Services.jsm", {});
var oFileBody = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
var oBlob = Blob([oFileBody], { type: "text/html"});
var blobUrl = URL.createObjectURL(oBlob); //returns a string like blob:null/bbe1b94e-0800-4af2-9d9e-df09c0b9cab3 so paste that into your url bar

OR just see how @nmaier is posting data to new tab.

OR the messy way, make a data url out of the source code like `data:text/html,rawr' and put that in your url bar. i prefer @nmaiers methods

OR again just see how @nmaier is posting data to new tab. (i love his way)

Upvotes: 2

EpokK
EpokK

Reputation: 38092

Use can use Request to send your data.

var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
  url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
  onComplete: function (response) {
    var tweet = response.json[0];
    console.log("User: " + tweet.user.screen_name);
    console.log("Tweet: " + tweet.text);
  }
});

Upvotes: 0

Related Questions