javascript - 向浏览器扩展中的任何 url 发出网络请求

标签 javascript html browser-extension

我目前正在开发浏览器扩展程序,但我遇到了网络请求问题。

扩展程序需要向自托管实例发出请求。这意味着每个人的网址都不同。

我在发出网络请求时遇到了两个问题(在 javascript 中):

  1. 只是发出任何网络请求都失败了。见:
fetch(`${base_url}/api/auth/status`)
.then(response => {
    // catch errors
    if (!response.ok) {
        return Promise.reject(response.status);
    };

    return;
});
.catch(e => {
    console.log(e);
})

导致以下两个错误:

Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.
Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution. Note that hashes do not apply to event handlers, style attributes and javascript: navigations unless the 'unsafe-hashes' keyword is present.
  1. 阅读文章,看来我需要将确切的 url 添加到将向其发出请求的 manifest.json 文件中。但是,向任何 url 发出请求,因为服务器是自托管的。那我该如何解决呢?

我看过这些文章和 SO 帖子,但似乎没有帮助:Dev , Medium , SO 1 , CSPlite , Csper , SO 2

在此先感谢您的帮助:)

最佳答案

我已经解决了这两个问题。

第一个问题,即 JavaScript 无法运行,是由表单的 action 属性引起的。我的 html 中有一个表单,使用 JavaScript,我将 action 属性设置为 javascript:login();。这会内联运行登录功能,这是不允许的。我通过将表单更改为 div 并将事件监听器添加到提交按钮以运行登录来修复它。

通过将以下内容添加到 manifest.json 文件中解决了第二个问题:

"host_permissions": [
    "http://*/",
    "http://*/*",
    "https://*/",
    "https://*/*"
]

关于javascript - 向浏览器扩展中的任何 url 发出网络请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73717897/

相关文章:

google-chrome - Chrome 扩展程序 : Execute background page only once when chrome starts

javascript - 使用 Knockout-Validation 插件进行独特值验证

javascript - 我在对象实例化到显示 "Uncaught RangeError: Maximum call stack size exceeded"错误时做错了什么以及如何避免它?

jquery - IE7 Jquery UI Sortable问题

javascript - imagemap onMouseOver解决方案

google-chrome - 如何在浏览器扩展程序的第一个选项卡/新窗口上加载页面

javascript - 将数据推送到 JavaScript 对象中

javascript - 使用 JQuery post+get 数据使用react

Javascript 变量 - 设置为百分比

javascript - 将下载链接从网络浏览器传递到第三方应用程序