简体   繁体   中英

XMLHttpRequest not sending in Firefox (addon)

I'm developing an addon that needs to do a POST request to my server.

I'm using XMLHttpRequest for this. It's working great on Chrome, but the POST request is never sent on Firefox. Nothing is showing in the dev tools (console /.network / addon inspect console), and nothing is received on my server. I've disabled any other addons and any kind of security on my whole PC (yes, I'm this desperate).

manifest.json

{
    ...
    "manifest_version": 2,
    "content_scripts": [{
        "matches": ["*://myurl.com/*"],
        "js": ["content.js"],
        "run_at": "document_end"
    }],
    "permissions": ["activeTab", "webRequest"]
}

The post request in my content script

const post = () => {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://myserver.com/test', false);
    xhr.setRequestHeader('Content-Type', 'application/json');
    console.log('Before sending request');
    xhr.send(JSON.stringify({id: myId}));
    console.log('Request sent');
    return xhr.responseText;
};

Only the "Before sending request" is logged. Anything after the xhr.send() is never executed (this includes code after the post() call in the rest of my code).

My server accepts all origins. It's also correctly configured to received and process POST requests

const cors = require('cors')
app.use(cors());

What's wrong with this? It's perfectly working on Chrome and I have no idea why it's never being sent without leaving any kind of error...

Per the post on firefox XHR working differently based on calling context consider moving the call to a background script to see if you get different behaviour.

You should consider adding your URL (eg "*://myurl.com/*" ) as a host permission to the permission array to have privilege for XMLHttpRequest. Please see official doc here in MDN and Chrome docs .

You can see this issue was also covered in this SO answer as well

BTW, I would consider migrating to manifest V3 following this Chrome suggestion:

The Chrome Web Store no longer accepts Manifest V2 extensions. Please use Manifest V3 when building new extensions.

As @Cadmium suggested in the question comments (and even though I didn't want to handle this request there), I've moved my post() function to a background script.

It's now working on both Chrome and Firefox. I still don't understand why it's behaving this way on Firefox, but it's a good enough workaround for me for now !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM