如果您曾经为Chrome开发扩展程序,则可能表明它已停止工作。原因是从去年开始,Chrome浏览器中阻止了来自内容脚本的跨域请求。这意味着,如果您的扩展程序直接从内容脚本访问某些第三方API,则由于跨域读取阻止(CORB),此类请求将被阻止解决阻塞问题的推荐方法是将请求从内容脚本传输到后台脚本。文档中的示例:旧内容脚本:var itemId = 12345;
var url = "https://another-site.com/price-query?itemId=" +
encodeURIComponent(request.itemId);
fetch(url)
.then(response => response.text())
.then(text => parsePrice(text))
.then(price => ...)
.catch(error => ...)
新的内容脚本:chrome.runtime.sendMessage(
{contentScriptQuery: "queryPrice", itemId: 12345},
price => ...);
新的背景脚本:chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.contentScriptQuery == "queryPrice") {
var url = "https://another-site.com/price-query?itemId=" +
encodeURIComponent(request.itemId);
fetch(url)
.then(response => response.text())
.then(text => parsePrice(text))
.then(price => sendResponse(price))
.catch(error => ...)
return true;
}
});
还请注意以下事实:您不应该通过后台脚本(即 您不应将内容脚本中的消息发送到后台脚本,以使URL接收数据,而应根据消息中的数据确定后台脚本中的URL。因此,在上面的示例中,请求的URL由contentScriptQuery和itemId参数确定。摘自文档的“不良”消息示例:{
contentScriptQuery: "fetchUrl",
url: "https://example.com/any/path/or/site/allowed/here"
}
PS:我正在开发Firefox和Chrome的扩展程序,但是主要的浏览器是Firefox,下载新版本的扩展程序时,我会检查Chrome的性能。前几天,我发现我的一个扩展程序停止工作了,这是由于CORB所致。检查您的扩展名,以免使您感到惊讶。