Chrome扩展混淆含chrome.scripting.executeScript的代码报错问题
Chrome扩展后台脚本混淆后executeScript失效的解决方案
问题原因
你遇到的错误是因为混淆工具将后台脚本里的myfunction重命名为了_0xb06ad0,但chrome.scripting.executeScript注入函数时,会序列化后台的函数引用,注入到目标页面的代码里会引用这个混淆后的变量名——而目标页面的全局作用域不存在这个变量,所以抛出ReferenceError。
解决办法
1. 改用字符串代码注入
不要直接传递函数引用,而是将函数转换为完整的代码字符串注入,确保目标页面能拿到独立可执行的代码:
function myfunction(){ console.log("hey if i work this should be on the console ") } chrome.tabs.create({ active: true, url: "https://example.com" }, function(tab) { // 将函数转为字符串,包裹成自执行形式注入 chrome.scripting.executeScript({ target: { tabId: tab.id }, code: `(${myfunction.toString()})()` }); })
或者直接编写完整的代码字符串(避免依赖后台函数引用):
chrome.tabs.create({ active: true, url: "https://example.com" }, function(tab) { chrome.scripting.executeScript({ target: { tabId: tab.id }, code: `function myfunction(){console.log("hey if i work this should be on the console ")} myfunction();` }); })
2. 配置混淆工具保留函数名
如果坚持使用函数引用注入,可以调整混淆工具的配置,让它不重命名myfunction这类需要跨作用域引用的函数:
- 比如用Terser混淆时,添加参数:
--keep-fnames myfunction - 或者在代码中给函数添加保留注释(不同工具规则不同):
/*@keep*/ function myfunction(){ console.log("hey if i work this should be on the console ") }
3. 改用静态内容脚本
把要注入的逻辑单独写成内容脚本文件,在manifest.json中声明,代替动态注入:
{ "content_scripts": [ { "matches": ["https://example.com/*"], "js": ["content.js"] } ] }
content.js里放原函数逻辑,这样后台脚本和内容脚本可以单独混淆,不会出现跨作用域变量名的问题。
内容的提问来源于stack exchange,提问作者xone-a
相关产品推荐
相关产品推荐

