How do you emulate Form's 'POST'
action with target="_blank"
in XMLHttpRequest
? (ie post data and open target page in a new tab)
Asked
Active
Viewed 2,341 times
3

erosman
- 7,094
- 7
- 27
- 46
1 Answers
2
gBrowser
offers this functionality right out of the box.
var dataStream = Cc["@mozilla.org/io/string-input-stream;1"].createInstance(Ci.nsIStringInputStream);
dataStream.data = "foo=bar&alpha=beta"; // make sure the values are properly encoded with encodeURIComponent
var postStream = Cc["@mozilla.org/network/mime-input-stream;1"].createInstance(Ci.nsIMIMEInputStream);
postStream.addHeader("Content-Type", "application/x-www-form-urlencoded");
postStream.addContentLength = true;
postStream.setData(dataStream);
gBrowser.loadOneTab("http://www.example.com/", {inBackground: false, postData: postStream});

paa
- 5,048
- 1
- 18
- 22
-
Great :) .... I am going to try it. Regarding `dataStream.data`, how can I pass a local file ie `'file:///C:/.../root.png'`? – erosman Jul 16 '14 at 18:15
-
Very useful stuff thanks man. Submitting files with this method would be nice too! By `values` being properly encoded you mean like: `dataStream.data = encodeURIComponent("foo") + "=" + encodeURIComponent("ba-%r") + "&" + encodeURIComponent("@find") + "=" + encodeURIComponent("ba+$@r");` right? – Noitidart Jul 16 '14 at 19:40
-
1@erosman try to [use FormData](http://stackoverflow.com/questions/13900527/how-to-upload-binary-content-with-firefox-extension) and pass that as postStream, though I don't know if that will work with `loadOneTab`. – paa Jul 18 '14 at 09:04