Home >Web Front-end >JS Tutorial >How to Prevent \'Unchecked runtime.lastError: The Message Port Closed...\' Errors in Chrome Extensions?

How to Prevent \'Unchecked runtime.lastError: The Message Port Closed...\' Errors in Chrome Extensions?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 14:37:02751browse

How to Prevent

Unveiling the Culprit: Orphaned Scripts and Extension Updates

After accidentally reloading a Chrome extension, you might encounter a pesky error: "Unchecked runtime.lastError: The message port closed before a response was received." This error stems from the creation of orphaned scripts, which breaks communication between the popup and content pages.

Grasping the Orphaned Script Concept

An orphaned script is a ghostly remnant of a previously loaded extension that continues to linger even after the extension has been updated or reloaded. This ghost script intercepts messages intended for the new content script, leading to communication disruptions.

Eradicating Orphaned Scripts

To banish this spectral script, we must first ascertain whether it's still responsive. If it is, we can dispatch a message from the new content script via the window object. Upon receiving this message, the orphaned script should deregister all event listeners and prepare for garbage collection.

Replenishing Content Scripts on Reloading

To prevent this issue from recurring, we can check for the presence of a usable content script before sending messages from the popup page. If none exists, we can inject the content script again.

Sample Code for Content Script

To implement the aforementioned solution, incorporate this amended content.js script:

<code class="javascript">var orphanMessageId = chrome.runtime.id + 'orphanCheck';
window.dispatchEvent(new Event(orphanMessageId));
window.addEventListener(orphanMessageId, unregisterOrphan);

// ... (register named functions for event listeners)

window.running = true;

function unregisterOrphan() {
  // ... (deregister listeners and nullify variables)
}

function onMessage(msg, sender, sendResponse) {
  // ... (handle message)
}

function onMouseMove(event) {
  // ... (DOM event handler)
}</code>

Popup Page Verification

To ensure a content script is injected before message transmission, enhance the popup.js script with this snippet:

<code class="javascript">async function sendMessage(data) {
  // ... (fetch active tab)
  if (await ensureContentScript(tab.id)) {
    return await chrome.tabs.sendMessage(tab.id, data);
  }
}

async function ensureContentScript(tabId) {
  // ... (check for existing content script)
  if (!result) {
    await chrome.scripting.executeScript({
      // ... (inject content script)
    });
  }
  return true;
}</code>

By implementing these measures, you can exorcise orphaned scripts and maintain seamless communication between your extension's popup and content pages.

The above is the detailed content of How to Prevent \'Unchecked runtime.lastError: The Message Port Closed...\' Errors in Chrome Extensions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn