前端开发您现在的位置是:首页 > 博客日志 > 前端开发

chrome 扩展程序如何访问网页中的js函数?

<a href='mailto:'>微wx笑</a>的头像微wx笑 2025-05-11前端开发7 0 0关键字: Chrome 扩展程序  

chrome 扩展程序如何访问网页中的js函数?在"content_scripts" 中的脚本是无法直接访问网页中的js函数的,下面是一个脚本注入程序:// content.jsfunction injectScript(code) {

无知人生,ivu4e.com,ivu4e.cn

chrome 扩展程序如何访问网页中的js函数?5Qu无知

在"content_scripts" 中的脚本是无法直接访问网页中的js函数的,5Qu无知

下面是一个脚本注入程序:
5Qu无知

1
2
3
4
5
// content.jsfunction injectScript(code) {
  const script = document.createElement('script');
  script.textContent = code;
  document.documentElement.appendChild(script);
  script.remove(); // 执行后移除脚本}

但是这种将js代码做为内联、行内脚本的方式注入是不行的,5Qu无知

会遇到类似下面的错误:5Qu无知

inject_zsxq.js:8 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-jGCkTlRBYIkCuAVFsB45CjzUzmq3mHYQQbl3CeJ402Y='), or a nonce ('nonce-...') is required to enable inline execution.5Qu无知


5Qu无知

由于 Chrome 扩展程序的内容安全政策(CSP)限制导致的。Chrome 扩展默认禁止执行内联脚本(如通过textContent注入的代码)5Qu无知

解决方法5Qu无知

就是把要注入的代码写到一个单独的文件中,然后注入脚本文件5Qu无知

比如存放到 "external-script.js"5Qu无知

1
2
3
4
5
6
7
// 注入脚本到网页环境
function injectScript() {
  const script = document.createElement('script');
  script.src = chrome.runtime.getURL('external-script.js');
  document.documentElement.appendChild(script);
  script.remove();
}

在"content_scripts" 中调用 injectScript()5Qu无知

manifest.json 中需要添加对应的代码:5Qu无知

1
2
3
4
5
6
"web_accessible_resources": [
        {
            "resources": ["external-script.js"],
            "matches": ["<all_urls>"]
        }
    ],


5Qu无知


5Qu无知

无知人生,ivu4e.com,ivu4e.cn

本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0 许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/blog/front/2025-05-11/2069.html

很赞哦! (2) 有话说 (0)

文章评论