使用JavaScript将数据发送到服务器(Firefox Addon)

时间:2014-12-01 13:28:05

标签: https firefox-addon cors

我想将一些数据发送到Firefox扩展程序中的外部服务器。

我尝试了这段代码片段但由于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));
});

由于这不起作用,我尝试了这个教程:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS 这让我得到了这段代码:

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

此代码也不起作用,Firefox提示我应该使用CORS。

有线的事情是,如果我不使用HTTPS(在非HTTPS网站上)

注意:在'https://127.0.0.1:54321'上运行Java SSLServerSocket。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

复制粘贴:

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