Pono Pono - 1 year ago 103
Javascript Question

Chrome Extension Development - POST to new tab

Is there an easy solution to POST dynamically aggregated data into a new tab?

does not have a 'POST' option. Normally I would use

chrome.browserAction.onClicked.addListener(function (t) {
"url" : "http://super.url",
"method" : "POST" // oops.. no option.

Answer Source

You can simply combine these two techniques:

  1. You may execute JavaScript commands by adding javascript: prefix at your address bar or in href values of <a> tags.
  2. Only with JavaScript, you can create a form element and fill it with your data then POST it.


function fakePost() {   
    var form = document.createElement("form");
    form.setAttribute("method", "post");
    form.setAttribute("action", "http://cvsguimaraes.altervista.org/fiddles/postcheck.php");
    var params = {userId: 2, action: "delete"};
    for(var key in params) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);
    document.body.appendChild(form); // Not sure if this step is necessary
//minify function
fakePostCode = fakePost.toString().replace(/(\n|\t)/gm,'');

chrome.browserAction.onClicked.addListener(function (t) {
  chrome.tabs.create({"url" : "javascript:"+fakePostCode+"; fakePost();"});

Of course, that's just a dirty hack. If you need something better you can use a XHR Object or elaborate something more like @Xan's answer below.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download