chrome 扩展程序如何访问网页中的js函数?
微wx笑
2025-05-11【前端开发】
0
0关键字:
Chrome 扩展程序
chrome 扩展程序如何访问网页中的js函数?在"content_scripts" 中的脚本是无法直接访问网页中的js函数的,下面是一个脚本注入程序:// content.jsfunction injectScript(code) {
chrome 扩展程序如何访问网页中的js函数?
在"content_scripts" 中的脚本是无法直接访问网页中的js函数的,
下面是一个脚本注入程序:
// content.jsfunction injectScript(code) { const script = document.createElement('script'); script.textContent = code; document.documentElement.appendChild(script); script.remove(); // 执行后移除脚本}
但是这种将js代码做为内联、行内脚本的方式注入是不行的,
会遇到类似下面的错误:
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.
由于 Chrome 扩展程序的内容安全政策(CSP)限制导致的。Chrome 扩展默认禁止执行内联脚本(如通过textContent
注入的代码)
解决方法
就是把要注入的代码写到一个单独的文件中,然后注入脚本文件
比如存放到 "external-script.js"
// 注入脚本到网页环境 function injectScript() { const script = document.createElement('script'); script.src = chrome.runtime.getURL('external-script.js'); document.documentElement.appendChild(script); script.remove(); }
在"content_scripts" 中调用 injectScript()
manifest.json 中需要添加对应的代码:
"web_accessible_resources": [ { "resources": ["external-script.js"], "matches": ["<all_urls>"] } ],
本文由 微wx笑 创作,采用 署名-非商业性使用-相同方式共享 4.0 许可协议,转载请附上原文出处链接及本声明。
原文链接:https://www.ivu4e.cn/blog/front/2025-05-11/2069.html
下一篇:返回列表