0

I've written a small extension for firefox, where I inject a content script into some websites. That content script shall do XMLHttpRequests, but when I try to run my code:

function call(url, data1, data2) {
    var request = new XMLHttpRequest();
    request.open('PUT', url, false);
    request.setRequestHeader("content-type", "application/json");
    request.send("{data1: " + data1 + ", data2: " + String(data2) + "}");
    if (request.status === 200) {
        console.log("Success");
    }
}
call("https://example.com/", "DATA1", true);

I end up getting this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/. (Reason: CORS request did not succeed).
Uncaught DOMException: A network error occurred.

Anyone any idea on how to fix this? I know, that background scripts can with the right permissions run these, but how to do this in a content script? I know, there are similar questions, but everything the answers mentioned was how to fix it server-side. Since the servers aren't mine, that's not possible for me obviously.

  • 1
    The only way is to do in the background script and use messaging to pass results back, [example](https://stackoverflow.com/a/55292071). As an alternative you can probably just add Access-Control-Allow-Origin header via `webRequest` API. – wOxxOm Jun 13 '21 at 03:09

0 Answers0