I have the following code in a background_script in a 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 the following: Whenever I load the extension, it's saying 'error', but how do I find out what exactly triggered the error?
The onerror event occurs when an error occurs with the event source. An error usually occurs when a connection is disrupted. If this happens, the EventSource object will automatically attempt to reconnect to the server.
The EventSource interface is web content's interface to server-sent events. An EventSource instance opens a persistent connection to an HTTP server, which sends events in text/event-stream format. The connection remains open until closed by calling EventSource.
close() The close() method of the EventSource interface closes the connection, if one is made, and sets the EventSource. readyState attribute to 2 (closed). Note: If the connection is already closed, the method does nothing.
The specification defines only a few possible cases for the "error" event to be triggered, which are:
Access-Control-Allow-Origin
is not set or does not match the origin URL.withCredentials:true
(via the second parameter of EventSource
), but the server did not reply with Access-Control-Allow-Credentials: true
.Content-Type
header of the response is not `text/event-stream.When a CORS error occurs, Chrome will usually log the following message to the console:
EventSource cannot load http://example.com/eventsource. Origin http://origin.example.com is not allowed by Access-Control-Allow-Origin.
For some reason, Chrome does not show this error when a redirect has taken place.
You have probably added the "http://www.janywer.freetzi.com/*"
permission to your manifest file, causing the initial request to pass. This page redirects to a different domain (without www-prefix). You have probably not added this domain to your manifest file, so Chrome attempts a CORS-enabled request. The expected headers are not received, so Chrome aborts the request.
This can be solved in two ways:
Add all involved domains to your file, e.g.
"permissions": [
"http://www.janywer.freetzi.com/*",
"http://janywer.freetzi.com/*"
]
(see match patterns in the Chrome extension documentation)
or let the server reply with the expected CORS headers. In PHP:
header("Access-Control-Allow-Origin: *");
This allows any page to access your URL. To restrict access to your extension only, use:
header("Access-Control-Allow-Origin: chrome-extension://EXTENSION ID HERE");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With