Search code examples
httpsfirefox-addon

Sending Data to a Server using JavaScript (Firefox Addon)


I would like to send some data to an external server within an Firefox extension.

I tried this code snippet but it doesn’t work, due to Same-Origin-Policy.

$.ajax({
  type: "POST",
  url: 'https://127.0.0.1:54321',
  data: ({foo: "bar"}),
  crossDomain: true,
  dataType: 'json'
}).done(function () {
    alert("done");
}).fail(function(xhr, status, error) {
//  var err = eval("(" + xhr.responseText + ")");
  alert((xhr.responseText));
});

Since this does not work, I tried this tutorial:

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

That got me this piece of code:

var invocation = new XMLHttpRequest(); var url = 'https://127.0.0.1:54321'; 
invocation.open('POST', url, true);
invocation.setRequestHeader('X-PINGOTHER', 'pingpong');
invocation.setRequestHeader('Content-Type', 'application/xml'); 
invocation.onreadystatechange = handler;
invocation.send(document.body);

This code also doesn't work and Firefox prompts that I should use CORS.

The weird thing is that it works if I don't use HTTPS (on non-HTTPS sites).

Note: On https://127.0.0.1:54321 runs a Java SSLServerSocket.


Solution

  • Copy paste this:

    var {Cu, Cc, Ci} = require('chrome'); //addon-sdk way
    //var {Cu: utils, Cc: classes, Ci: instances} = Components; //non addon-sdk
    Cu.import('resource://gre/modules/Services.jsm');
    function xhr(url, cb) {
        let xhr = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
    
        let handler = ev => {
            evf(m => xhr.removeEventListener(m, handler, !1));
            switch (ev.type) {
                case 'load':
                    if (xhr.status == 200) {
                        cb(xhr.response);
                        break;
                    }
                default:
                    Services.prompt.alert(null, 'XHR Error', 'Error Fetching Package: ' + xhr.statusText + ' [' + ev.type + ':' + xhr.status + ']');
                    break;
            }
        };
    
        let evf = f => ['load', 'error', 'abort'].forEach(f);
        evf(m => xhr.addEventListener(m, handler, false));
    
        xhr.mozBackgroundRequest = true;
        xhr.open('GET', url, true);
        xhr.channel.loadFlags |= Ci.nsIRequest.LOAD_ANONYMOUS | Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_PERSISTENT_CACHING;
        //xhr.responseType = "arraybuffer"; //dont set it, so it returns string, you dont want arraybuffer. you only want this if your url is to a zip file or some file you want to download and make a nsIArrayBufferInputStream out of it or something
        xhr.send(null);
    }
    
    xhr('https://www.gravatar.com/avatar/eb9895ade1bd6627e054429d1e18b576?s=24&d=identicon&r=PG&f=1', data => {
        Services.prompt.alert(null, 'XHR Success', data);
        var file = OS.Path.join(OS.Constants.Path.desktopDir, "test.png");
        var promised = OS.File.writeAtomic(file, data);
        promised.then(
            function() {
                alert('succesfully saved image to desktop')
            },
            function(ex) {
                 alert('FAILED in saving image to desktop')
            }
        );
    });