問題:
重新載入時,孤立的內容腳本可能會保留,從而導致錯誤以及與擴展其他部分的通訊問題。如果原始內容腳本具有 DOM 事件偵聽器,從而阻止其自動刪除,則會出現此問題。
解決方案:
要刪除孤立腳本:
程式碼範例:
background.js:
<code class="javascript">// Re-inject content scripts on reloading/installing the extension // (See example in link provided in QA)</code>
<code class="javascript">// Generate a unique message ID for the orphan check const orphanMessageId = chrome.runtime.id + 'orphanCheck'; // Register a listener for the orphan check message window.addEventListener(orphanMessageId, unregisterOrphan); // ... (Continue with original content script code) ... // Function to unregister the orphaned script function unregisterOrphan() { // Check if the extension is uninstalled if (!chrome.runtime.id) { // The script is not orphaned return; } // Remove the orphan message listener window.removeEventListener(orphanMessageId, unregisterOrphan); // Remove DOM event listeners document.removeEventListener('mousemove', onMouseMove); // Remove runtime message listener (try-catch required in some cases) try { chrome.runtime.onMessage.removeListener(onMessage); } catch (e) {} }</code>
<code class="javascript">// Function to send a message and ensure a content script is injected before doing so 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); } } // Function to check if a content script is running and re-inject it if not async function ensureContentScript(tabId) { try { // Check if the content script is running const [{ result }] = await chrome.scripting.executeScript({ target: { tabId }, func: () => window.running === true, }); // If not, inject the content script if (!result) { await chrome.scripting.executeScript({ target: { tabId }, files: ['content.js'], }); } return true; } catch (e) {} }</code>
popup.js:
與透過這種方法,孤立的腳本將被清理,並且可以恢復與擴展的其餘部分的通信。以上是Chrome 擴充功能更新後如何刪除孤立腳本?的詳細內容。更多資訊請關注PHP中文網其他相關文章!