

chrome扩展中如何绕开CSP限制运行javascript:func()形式的js代码日期:2026-6-9
我在运行自己前两年编写的chrome扩展时,发现模拟点击超链接时无法跳转页面并且报错:Running the JavaScript URL violates the following Content Security Policy directive 'script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost:* http://127.0.0.1:* chrome-extension://1f137fc2-e688-42f1-a42e-8628d4c034fd/'. 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. The action has been blocked.。网上查解决方案,发现问题原因是最新的chrome扩展V3完全禁止了unsafe-eval、unsafe-inline,而我运行扩展模拟点击的网页超链接是用href="javascript:urlpage('next')"的形式调用函数跳转页面的,被CSP规则禁止了。
manifest.json的方法解决问题最新的chrome扩展V3版本完全禁止了unsafe-eval、unsafe-inline,因此修改manifest.json增加unsafe-eval、unsafe-inline权限将导致扩展无法加载,不可用。
我的解决方法是在background.js中调用chrome.scripting.executeScript运行从content.js中发送过来的javascript代码。具体做法是在background.js中加入监听器执行接收到的代码,在content.js中发送需要执行的javascript代码。
下面是监听器实例(如果你还有其他监听器,就把if (...){...}那段加进去):
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse){
if (request.action === 'exec_script') {
console.log(request.action+": "+request.js);
var jscode = String( request.js );
chrome.scripting.executeScript({
target: { tabId: sender.tab.id },
func: (code) => {
eval( code );
},
args:[ jscode ],
world: 'MAIN' // 确保在页面主上下文执行
});
}
return true; // 保留消息通道打开,以便异步发送响应
}
下面是在content.js中发送代码的函数示例:
function tryExecJs(code) {
// 如果 code 以 "javascript:" 开头,就执行代码,返回 true,否则返回 false
if( code.length<13 ) {
return false;
}
if(code.substr(0,11)==="javascript:"){
let jscode = code.substr(11, code.length);
chrome.runtime.sendMessage( { action: "exec_script", js: jscode } );
return true;
}
return false;
}
下面是manifest.json中需要添加的内容:
"permissions": [
...
"scripting"
],
"host_permissions": [
"<all_urls>"
]