无意中重新加载 Chrome 扩展程序,尤其是处于开发者模式的扩展程序,可能会创建孤立内容脚本。这些脚本仍然在后台运行,但与扩展的其余部分失去了通信,从而导致诸如“扩展上下文无效”和“未检查的runtime.lastError”之类的错误。
孤立的内容脚本仍然可以接收 DOM 消息。删除它:
1.从新内容脚本发送消息:
2。在孤立脚本中注销监听器:
3.后台脚本:
4.内容脚本:
5.弹出脚本:
示例代码:
background.js:
<code class="javascript">// Re-inject content script chrome.runtime.onInstalled.addListener(() => { chrome.tabs.query({ active: true, currentWindow: true }, tabs => { chrome.tabs.executeScript(tabs[0].id, { file: 'content.js' }); }); });</code>
content.js:
<code class="javascript">// Orphaned script detection and cleanup var orphanMessageId = chrome.runtime.id + 'orphanCheck'; window.dispatchEvent(new Event(orphanMessageId)); window.addEventListener(orphanMessageId, unregisterOrphan); // Register named listeners chrome.runtime.onMessage.addListener(onMessage); document.addEventListener('mousemove', onMouseMove); // Orphan flag and cleanup function window.running = true; function unregisterOrphan() { if (chrome.runtime.id) { // Not orphaned return; } window.removeEventListener(orphanMessageId, unregisterOrphan); document.removeEventListener('mousemove', onMouseMove); try { chrome.runtime.onMessage.removeListener(onMessage); } catch (e) {} return true; }</code>
popup.js:
<code class="javascript">async function sendMessage(data) { const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); if (await ensureContentScript(tab.id)) { return await chrome.tabs.sendMessage(tab.id, data); } } async function ensureContentScript(tabId) { try { const [{ result }] = await chrome.scripting.executeScript({ target: { tabId }, func: () => window.running === true, }); if (!result) { await chrome.scripting.executeScript({ target: { tabId }, files: ['content.js'], }); } return true; } catch (e) {} }</code>
以上是如何修复 Chrome 扩展程序中孤立内容脚本导致的“扩展程序上下文无效”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!