What makes EventSource fire an error in my Chrome extension?

I have the following code in background_script in the google chrome extension:

var source = new EventSource("http://www.janywer.freetzi.com/events/groupshout.php"); source.addEventListener('message', function (e) { console.log('message', e.data); }, false); source.addEventListener('open', function (e) { console.log('open'); }, false); source.addEventListener('error', function (e) { console.log('error') }, false); 

My problem is this: whenever I download the extension, it says β€œerror”, but how do I know what exactly caused the error?

+6
source share
1 answer

The specification defines only a few possible cases for triggering the error event, which are:

  • A cross-out request was initiated, but the expected CORS headers were not received. This includes:
    • Access-Control-Allow-Origin not installed or does not match the original URL.
    • You set withCredentials:true (via the second EventSource parameter), but the server did not respond with Access-Control-Allow-Credentials: true .
  • A network error has occurred.
  • The http status is not 200, 305, 401, 407, 301, 302, 303 or 307.
  • The user agent (browser) is trying to reconnect.
  • The http status is 200, but the response Content-Type header is not a text / event stream.
  • A redirect occurred that led to one of the previous conditions.

When a CORS error occurs, Chrome usually writes the following message to the console:

EventSource cannot load http://example.com/eventsource . The origin of http://origin.example.com is not allowed by Access-Control-Allow-Origin.

For some reason, Chrome does not show this redirect error.


You may have added the permission "http://www.janywer.freetzi.com/*" to the manifest file, as a result of which the initial request has passed. This page is redirected to another domain (without www-prefix). You probably did not add this domain to your manifest file, so Chrome is trying to execute a request with CORS support. Expected headers are not accepted, so Chrome cancels the request.

This can be solved in two ways:

  • Add all involved domains to e.g.

     "permissions": [ "http://www.janywer.freetzi.com/*", "http://janywer.freetzi.com/*" ] 

    (see compliance templates in the Chrome extension documentation)

  • or respond to the server with the expected CORS headers. In PHP:

     header("Access-Control-Allow-Origin: *"); 

    This allows any page to access your URL. To restrict access only to your extension, use:

     header("Access-Control-Allow-Origin: chrome-extension://EXTENSION ID HERE"); 
+6
source

Source: https://habr.com/ru/post/947946/


All Articles