问题:
重新加载 Chrome 扩展程序时,孤立的内容脚本可能会保留,从而导致错误以及与扩展其他部分的通信问题。如果原始内容脚本具有 DOM 事件侦听器,从而阻止其自动删除,则会出现此问题。
解决方案:
要删除孤立脚本:
代码示例:
background.js:
<code class="javascript">// Re-inject content scripts on reloading/installing the extension // (See example in link provided in QA)</code>
content.js:
<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>
popup.js:
<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>
通过这种方法,孤立的脚本将被清理并可以恢复与扩展程序其余部分的通信。
以上是Chrome 扩展更新后如何删除孤立脚本?的详细内容。更多信息请关注PHP中文网其他相关文章!