XMLHttpRequest from Firefox WebExtension
Asked Answered
U

1

7

I've seen loads of examples of creating xhr requests from Firefox Add-ons, but I am trying to use the new WebExtensions stuff (where require and Components are undefined) and can't seem to see why I can't send a simple XmlHttpRequest from within the extension?

It's worth noting that the ajax request is going to a completely different URL, but the host has CORs set to allow all origins.

As soon as .send() is fired I get the error:

[Exception... "Failure" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: resource://gre/modules/ExtensionContent.jsm -> moz-extension://9ca18411-9a95-4fda-8184-9dcd3448a41a/myapp.js :: GM_xmlhttpRequest :: line 162" data: no]"1 whatsapp.js:166:9

The code looks like this:

function GM_xmlhttpRequest(orders) {
  try {
    var oReq = new XMLHttpRequest();
    oReq.addEventListener("load", function(a1, a2, a3) {
      console.log('xhr.load: %s, %s, %s', a1, a2, a3);
    });

    // open synchronously
    oReq.open(orders.method, orders.url, false);

    // headers
    for (var key in orders.headers) {
      oReq.setRequestHeader(key, orders.headers[key]);
    }

    // send
    var res = oReq.send(orders.data);
    console.log('xhr result: %s', res);
  } catch(e) {
    debugger;
    console.warn('could not send ajax request %s to %s, reason %s', orders.method, orders.url, e.toString());
  }
}

I've added webRequest permissions to my manifest.json, I realise that is not what it means, but am struggling to understand what is stopping the ajax request? Any ideas?

{
  "manifest_version": 2,
  "name": "MyApp",
  "version": "1.0",
  "description": "TestXHR",
  "icons": {
       "48": "icons/myapp-48.png"
  },
  "applications": {
      "gecko": {
      "id": "[email protected]",
      "strict_min_version": "45.0"
  }
  },
  "content_scripts": [
    {
      "matches": ["*://web.myapp.com/*"],
      "js": ["myapp.js"]
    }
  ],  
  "permissions": [
    "https://thehost.all-xhr-sent-here.net/*",
    "webRequest"
    ]
  }
Ulund answered 21/6, 2016 at 12:10 Comment(3)
You could try fetch.Falgoust
Thats interesting. XHR should work as it does from any webpage, as long as you do it from background.js or popup.js I would think.Aboveground
Works from inside the web extension too, it was something to do with the permissions URL itselfUlund
U
5

The problem was the permissions URL specified. I changed the sub domain to an asterisk and the protocol to an asterisk and it seemed to work after that.

Ulund answered 23/6, 2016 at 5:54 Comment(2)
Might be worth installing Live HTTP Headers add-on, enable all checkboxes, and see what is actually being loaded. Is it switching protocol from http to https? Switching sub-domains sub1.dom.tld sub2.dom.tld sub3.dom.tld?Snowber
user314159 is right. My case is 302 redirect. Discovered by using fiddler.Impoverished

© 2022 - 2024 — McMap. All rights reserved.