無意中重新載入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中文網其他相關文章!