Chrome扩展Manifest V3中scripting.executeScript未定义错误求助
问题解决:TypeError: Cannot read properties of undefined (reading 'executeScript')
核心问题分析
- 函数参数传递错误:你在
executeScript中传入func: getHightLightedText(),这会立即执行函数并将返回值(undefined)传给func,而非传递函数本身,导致API调用异常。 - API调用环境错误:
chrome.scripting属于扩展特权API,仅能在background service worker、popup页面、选项页面等扩展自有上下文使用,无法在content script中调用。
分步解决
1. 修正func参数传递
将func: getHightLightedText()改为func: getHightLightedText,传递函数引用而非执行结果:
await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: getHightLightedText, // 去掉括号 });
2. 确保代码运行在正确上下文
- 如果当前代码写在content script中:必须将调用
chrome.scripting.executeScript的逻辑迁移到popup或background service worker中,content script无法访问该API。 - 如果代码在popup中:建议将执行逻辑绑定到按钮点击事件(而非页面加载时自动执行),避免popup关闭后逻辑中断。
3. 优化事件监听逻辑(避免重复绑定)
原函数每次注入都会添加新的mouseup监听器,多次执行会导致重复触发,优化后:
const getHightLightedText = () => { // 先移除已有监听器,防止重复绑定 document.removeEventListener('mouseup', handleMouseUp); document.addEventListener('mouseup', handleMouseUp); function handleMouseUp(event) { const selectedText = window.getSelection().toString().trim(); if (selectedText) { console.log(selectedText); } } };
完整可运行示例
以popup触发为例:
popup.html
<button id="startListener">开启选中文本监听</button> <script src="./popup.js"></script>
popup.js
document.getElementById('startListener').addEventListener('click', async () => { const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); await chrome.scripting.executeScript({ target: { tabId: tab.id }, func: getHightLightedText, }); }); function getHightLightedText() { document.removeEventListener('mouseup', handleMouseUp); document.addEventListener('mouseup', handleMouseUp); function handleMouseUp(event) { const selectedText = window.getSelection().toString().trim(); if (selectedText) { console.log(selectedText); } } }
你的manifest配置权限部分无问题,无需修改。
内容的提问来源于stack exchange,提问作者Angel
相关产品推荐
相关产品推荐

