首页 > 解决方案 > Firefox 插件:同源策略不允许读取远程资源(原因:无法添加 CORS 标头 'Origin')

问题描述

我有一个为Chrome开发的扩展程序,并且还上传到Firefox的附加商店。我最近添加了一个功能,扩展程序向https://tf2metrics.azurewebsites.net发出跨域请求以下载一些 json 数据。

来自扩展的示例调用:

https://tf2metrics.azurewebsites.net/api/users/76561198142328193,76561198200094518,76561198090551717

相同的源代码在 Chrome 上运行良好,但不适用于 Firefox 用户。

在 Firefox 浏览器控制台中,此调用会导致:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://tf2metrics.azurewebsites.net/api/users/76561198142328193,76561198200094518,76561198090551717. (Reason: CORS header ‘Origin’ cannot be added).

我的内容脚本在https://tf2center.com/lobbies/ * 上运行,带有一行简单的 jQuery:

$.get(url, function (data) {
    // do stuff
});

我尝试添加一个Origin标题,因为错误说它“无法添加”:

$.ajaxSetup({
    headers: {
        'Origin': "https://tf2center.com"
    }
});

此扩展程序仍然无法在 Firefox 上运行,并且通过此调用在 Chrome 上也失败。错误是:

Refused to set unsafe header "Origin"

所以我删除了那个。我浏览了一下,看到添加

"permissions": [
  "*://*.tf2center.com/*",
  ...
],

manifest.json可能会解决这个问题,但这也不起作用。

这里的参考是我最初添加的 ASP.NET Core 3.1Startup.cs代码来处理 COR,当时我第一次需要支持 Chrome 的功能:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    ...
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    ...
    app.UseCors(_ => _.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    ...
}

为什么我的 Chrome 扩展程序允许通话而 Firefox 不允许?我还能尝试修复 Firefox 特定的错误吗?

标签: asp.net-corecorsfirefox-addoncross-domainfirefox-addon-webextensions

解决方案


我误解了需要添加到manifest.json'permissions部分的内容。我需要包含我希望调用的 URL 匹配模式,而不是源的 URL。

"permissions": [
  "https://tf2metrics.azurewebsites.net/*",
  ...
],

我更新为仅https在我的站点(而不是调用站点)上调用,它现在可以在 Firefox 上运行。


推荐阅读