Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Chrome Extension Development - POST to new tab


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

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

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

Solution

  • 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");
        
        // Create a POST dump at ptsv2.com and change the code
        form.setAttribute("action", "http://ptsv2.com/t/dcgex-1614815819/post");
        form.setAttribute("method", "post");
    
        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]);
            form.appendChild(hiddenField);
        }
    
        // Appending the form might not be necessary
        document.body.appendChild(form);
    
        form.submit();
    };
    
    const 
        source = fakePost.toString().replace(/(\n|\t)/gm,'').replace(/\s\s/gm,' '),
        url = `javascript:${source}; fakePost();`;
    
    chrome.browserAction.onClicked.addListener(() => chrome.tabs.create({ url }));
    

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