我在 Google Chrome 扩展的 background_script 中有以下代码:
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);
我的问题如下:每当我加载扩展程序时,它都会显示“错误”,但我如何找出究竟是什么触发了错误?
最佳答案
The specification仅定义了触发“错误”事件的几种可能情况,它们是:
Access-Control-Allow-Origin
未设置或与原始 URL 不匹配。 withCredentials:true
(通过 EventSource
的第二个参数),但服务器没有回复 Access-Control-Allow-Credentials: true
. Content-Type
响应的 header 不是 `text/event-stream. 当发生 CORS 错误时,Chrome 通常会将以下消息记录到控制台:
EventSource cannot load http://example.com/eventsource. Origin http://origin.example.com is not allowed by Access-Control-Allow-Origin.
出于某种原因,当发生重定向时,Chrome 不会显示此错误。
您可能添加了
"http://www.janywer.freetzi.com/*"
对 list 文件的权限,导致初始请求通过。此页面重定向到不同的域(没有 www 前缀)。您可能尚未将此域添加到 list 文件中,因此 Chrome 会尝试启用 CORS 的请求。未收到预期的 header ,因此 Chrome 中止了请求。这可以通过两种方式解决:
"permissions": [
"http://www.janywer.freetzi.com/*",
"http://janywer.freetzi.com/*"
]
(参见 Chrome 扩展文档中的 match patterns)
header("Access-Control-Allow-Origin: *");
这允许任何页面访问您的 URL。要仅限制对您的扩展程序的访问,请使用:
header("Access-Control-Allow-Origin: chrome-extension://EXTENSION ID HERE");
关于javascript - 是什么导致 EventSource 在我的 Chrome 扩展程序中触发错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17262833/