Chrome扩展调用scripting.executeScript报签名不匹配错误求助
解决Chrome扩展Manifest V3中scripting.executeScript签名错误及功能修正
核心错误原因
你调用chrome.scripting.executeScript时传了两个独立参数,而Manifest V3要求这个方法只接受一个包含所有配置的对象参数,这就是触发签名不匹配报错的直接原因。
完整修正方案
1. 修正executeScript调用格式
把target和code/func合并到同一个对象参数中,同时调整逻辑:让内容脚本直接在页面内提取并处理目标内容,再将结果返回给popup执行保存操作,避免在popup中解析整个HTML的冗余步骤。
2. 移除未引入的jQuery依赖
你的代码里使用了$但未在popup.html中引入jQuery库,这里直接替换为原生JS实现,避免额外依赖。
修正后的代码
manifest.json(无需修改)
{ "name": "AOPS Saver", "version": "1.1", "manifest_version": 3, "description": "Saves current AOPS problem to file", "action": { "default_title": "???", "default_popup": "popup.html" }, "permissions": [ "scripting", "activeTab" ] }
popup.html(调整脚本加载时机)
<!DOCTYPE html> <html> <head> <title>My Extension</title> </head> <body> <button id="execute">Execute</button> <script src="popup.js"></script> </body> </html>
popup.js(核心逻辑修正)
function saveToFile(text, filename) { const blob = new Blob([text], {type: 'text/plain'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; a.click(); URL.revokeObjectURL(url); // 释放URL资源,避免内存泄漏 } // 等待DOM加载完成后绑定按钮事件 document.addEventListener('DOMContentLoaded', () => { document.getElementById('execute').addEventListener('click', () => { chrome.tabs.query({active: true, currentWindow: true}, (tabs) => { const tab = tabs[0]; // 用startsWith匹配URL,兼容带参数的页面 if (tab.url.startsWith('https://artofproblemsolving.com/alcumus/problem')) { // 修正executeScript参数格式:单个对象包含所有配置 chrome.scripting.executeScript({ target: {tabId: tab.id}, func: () => { // 用func传递函数,比code字符串更易维护 const element = document.querySelector('.alc-solution-text'); if (!element) return ''; // 复制元素避免修改原页面DOM const container = element.cloneNode(true); // 替换图片为alt文本 container.querySelectorAll('img').forEach(img => { const textNode = document.createTextNode(img.alt); img.replaceWith(textNode); }); return container.textContent.trim(); } }, (results) => { // 添加错误捕获 if (chrome.runtime.lastError) { console.error(chrome.runtime.lastError); return; } const content = results[0].result; if (content) { saveToFile(content, 'problems.txt'); } else { alert('未找到目标内容'); } }); } else { alert('请打开AOPS的Alcumus问题页面'); } }); }); });
关键改进点
- 修复了
executeScript的参数格式,完全符合Manifest V3的API要求 - 用
func替代code字符串,代码可读性更强且避免字符串转义问题 - 在内容脚本中直接处理DOM,减少popup与页面间的数据传递量
- 添加了错误处理逻辑,避免静默失败
- 替换jQuery为原生JS,消除未声明的依赖问题
- 改用
startsWith匹配URL,兼容带查询参数的目标页面
内容的提问来源于stack exchange,提问作者433MEA
相关产品推荐
相关产品推荐

