Skip to content
The Chat Archive
minimax-m1 LMArena Human Preference 140K

I am developing a chrome extension, which injects two separate content scripts…

  1. User

    I am developing a chrome extension, which injects two separate content scripts (topFrame.js and aboutBlank.js) into the same targeted page. The two content scripts work together to hide/show certain UI elements on the page, depending on certain conditions.

    My extension is mostly working the way I want it to.

    However, there is one thing that I am trying to address: In the event that a user of the extension decides to disable or uninstall the extension, with the targeted page still open, I want aboutBlanks.js to send a message to topFrame.js (or vice versa).

    In aboutBlank.js, I am detecting a likely uninstall event by explicitly catching and handling an error message that includes the string "Extension context invalidated". In this catch block, I tear down the still-active functionality in aboutBlank.js (namely, a keydown event listener). However, in this same catch block, I would also like to send a message to my topFrame.js script, indicating the "Extension context invalidated" event and thus signaling to the topFrame.js script to tear down its own functionality (namely, a click event listener).

    I am considering a few different approaches: Custom DOM Events, BroadcastChannel API, window.postMessage. For my scenario, which of these approaches would you recommend? Or would you recommend a different, unmnentioned approach?

    In the latest version of my extension, I am actually already dispatching (and listening for) a custom event, in order to make my content scripts indempotent.

    If you recommend that I should pursue the Custom DOM Events approach, here are some additional questions...

    For dispatching a custom event related to an uninstall event, should I set up discrete listeners for this custom event? Or, should I use the same event listener for both scenarios and then just handle each accordingly in the event listener's callback?

    Here is the relevant code related to ensuring my aboutBlank.js content script is indempotent (and I have similar code within topFrame.js)...

    (function () { console.log(aboutBlank.js. (ts: ${ts()}));

    if (window[chrome.runtime.id + "initializedAboutBlank"]) { console.log(Content script already initialized, so we will halt any further execution of this particular script. (ts: ${ts()})); return; }

    window[chrome.runtime.id + "initializedAboutBlank"] = true;

    // Check for orphaned aboutBlank.js content script. let orphanMessageIdAbout = chrome.runtime.id + "orphanCheckAbout"; window.dispatchEvent(new Event(orphanMessageIdAbout)); window.addEventListener(orphanMessageIdAbout, unregisterOrphanAbout);

    // If nec, deactivate orphaned script. function unregisterOrphanAbout() { try { console.log(unregisterOrphanAbout(). (ts: ${ts()}));

      if (chrome.runtime.id) {
        console.log(`chrome.runtime.id is true, so exiting unregisterOrphanAbout() function. (ts: ${ts()})`);
        return;
      }
    
      // Tear down script
      // Code not included
    
    } catch (error) {
      console.log("unregisterOrphan()", error);
    
    }
    

    }

    // More Code... // Code not included.

    })();

  2. Assistant

    For your scenario where two content scripts (aboutBlank.js and topFrame.js) need to communicate during an extension uninstall/disable event, Custom DOM Events are the most straightforward and reliable approach. Here's why:


    Recommendation: Use Custom DOM Events

    1. Same Context: Both content scripts run in the same document, so DOM events work natively without cross-origin issues.
    2. Simplicity: You already use custom events for idempotency—extending this pattern keeps your code consistent.
    3. Synchronous Cleanup: Events are dispatched synchronously, which is critical since the extension context invalidates quickly.

    Implementation Steps

    1. Dispatch Event on Uninstall Detection

    In aboutBlank.js, modify your error handler to dispatch a custom event when the extension is unloaded:

    try {
      // Code that might throw "Extension context invalidated"
    } catch (error) {
      if (error.message.includes("Extension context invalidated")) {
        // Dispatch a dedicated event for cleanup
        window.dispatchEvent(new CustomEvent("extensionUnloaded"));
        
        // Existing cleanup logic for aboutBlank.js
        // ...
      }
    }
    

    2. Listen for the Event in topFrame.js

    In topFrame.js, add a listener to handle the cleanup:

    window.addEventListener("extensionUnloaded", () => {
      // Tear down click event listeners and other logic
      // ...
    });
    

    Key Considerations

    • Discrete Listeners: Use a dedicated event (extensionUnloaded) instead of reusing existing events. This avoids ambiguity and keeps logic separate.
    • Timing: Ensure the event is dispatched synchronously in the catch block. The extension context may invalidate immediately after the error, so delayed events (e.g., setTimeout) might not work.
    • Idempotency Check: Your existing initializedAboutBlank check prevents redundant initialization. The new event handler for extensionUnloaded should similarly check if cleanup is needed (though it’s likely harmless to run idempotently).

    Why Not Other Approaches?

    • BroadcastChannel API: Requires explicit channel setup and may not work reliably in content script contexts.
    • window.postMessage: Less direct than DOM events for same-document communication.
    • Custom Events Are Already Working: Leverage your existing pattern for consistency.

    By using a dedicated custom event, you ensure clean, maintainable communication between your content scripts during extension teardown.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.