Chrome扩展程序*后台*脚本访问XMLHttpRequest已被CORS策略阻止。

4
我发布了一个Chrome扩展程序,幸运地拥有一个相当大的用户群(数千名用户)。背景页面连接到我的服务器以验证他们的订阅。对于约95%的用户,这按预期工作,在我测试的每台机器上都按预期工作。根据https://developer.chrome.com/extensions/xhr,“在扩展的背景页面或前台选项卡中执行的脚本可以与其来源之外的远程服务器通信,只要扩展请求跨源权限。”我的manifest.json在权限中指定了我的服务器域,而且似乎对于绝大多数用户来说都没有问题。偶尔我会收到来自被阻止的用户的支持请求,并最终提供显示错误的背景页面开发控制台截图:Access to XMLHttpRequest at 'https://www.mydomainname.com/check_subscription.php?guid=example-example-example-example' from origin 'chrome-extension://abcexampleexampleexample' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

有什么可能导致一些用户的计算机出现此问题而另一些用户没有?我对任何可能导致此问题的原因都很感兴趣,无论是我可以在我的代码中修复的问题,还是用户可以在他们的计算机上修复的问题,或者任何其他解决方案。


我猜是防火墙或其他问题。你是否在响应中添加了“Access-Control-Allow-Origin”头来检查订阅? - Nadia Chibrikova
1
@NadiaChibrikova 我尝试添加了那个头部,但是对于受影响的客户并没有产生任何奇怪的变化。 - r14n
3个回答

1
你只需要使用CORS代理绕过CORS策略,只需在URL前加上'https://cors-anywhere.herokuapp.com/'

例如,如果你要请求: https://www.mydomainname.com/check_subscription.php? ,那么

你需要请求: 'https://cors-anywhere.herokuapp.com/https://www.mydomainname.com/check_subscription.php?'

这个URL是CORS策略的代理,它能像魔术一样工作。


有趣,但最终我认为这并不能帮助,因为请求的URL在我的控制之下,并且已经具有宽松的CORS头。 - r14n

1
这可以帮助你。

Explanation As of Chrome 73, cross site requests are blocked. (Even if you have the hosts in your permissions property.) Some sites seem to get through unblocked but I'm sure eventually most won't.

You have to make the request in a background page...

Setup Add a section to your manifest.json to point to the background page.

"background": { "scripts": ["bg_page.js"], "persistent": false } Create the background page: bg_page.js

chrome.runtime.onMessage.addListener( function(url, sender, onSuccess) { fetch(url) .then(response => response.text()) .then(responseText => onSuccess(responseText))

    return true;  // Will respond asynchronously.
} ); Then use it in main.js

chrome.runtime.sendMessage( //goes to bg_page.js url, data => dataProcessFunction(data) ); Additional Tips If you do anything like console.log() from the bg page, click the "inspect views background page" link in your extension's square in chrome's extensions manager and you'll get a separate dev tools window for everything that happens with your background page.

If you want to see the docs for yourself, check out step 2 of the Recommended Developer Actions section here: https://www.chromium.org/Home/chromium-security/extension-content-script-fetches#TOC-2.-Avoid-Cross-Origin-Fetches-in-Content-Scripts

来自这里


1
这个问题特别关注的是为什么它已经(零星地)不能在后台页面工作,而不是如何创建一个后台页面。 - r14n

-1

你尝试过添加:

Access-Control-Allow-Origin: * 

你的脚本需要返回什么?'*'字符是通配符,允许请求来自任何域。

如果你想更深入地了解,是否考虑使用预检请求呢?一些信息可以通过MDN获得:

与“简单请求”(上文已讨论)不同,“预检请求”会首先使用OPTIONS方法向其他来源的资源发送HTTP请求,以确定实际请求是否安全。跨站点请求像这样进行预检,因为它们可能对用户数据产生影响。

最后,只是因为你是Chrome扩展程序开发人员,CNET提供了一篇详细介绍2021年1月中旬即将到来的Manifest v3问题的文章。 这可能是一个很好的资源,可以让你看看在新的一年里是否会有任何问题影响你的用户群体。


嗨。是的。那个在服务器上,但是出于某些原因一些人仍然被阻止了。 - r14n

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接