Search code examples
javascriptfirefox-addon

how to deal with "CORS error" when writing firefox plugin?


I am trying to write a plugin for Firefox that keeps track of changes of several websites. To do this, I would need to maintain a list of websites and do "HTTP GET" to get their latest contents using following code:

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.withCredentials = true;
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.setRequestHeader('Access-Control-Allow-Origin', '*');
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

However, I constantly have following error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMissingAllowOrigin. (Reason: CORS request did not succeed). Status code: (null)

Does anyone know how I should fix this issue? Any suggestion would be much appreciated, thanks!


Solution

  • To allow Cross-Origin requests for an extension you are developing, you need to request the permission in your manifest.json. The documentation can be found here: permissions and host_permissions. This, I quote, grants the permission for:

    XMLHttpRequest and fetch access to those origins without cross-origin restrictions (even for requests made from content scripts).

    You need to add the websites you want to use fetch requests on, as match patterns, for example: *://*.google.com/* will grant you fetch request permissions for google.com and its subdomains (such as maps.google.com), on HTTP and HTTPS. If you want to request permissions for all websites, you can use the special pattern <all_urls>.