Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Message passing: Background script to closing tab

I'm a javascript novice writing my first Chrome extension and I'm stuck on message passing. My extension includes a background script, a browser action icon, and a content script. The content script (a timer that measures the number of second spent in tab) needs to update the background script and change the icon when the tab is closed, but since the content script cannot access the tab onRemove event, it needs to listen for a message from the background script.

Here's how I've set up the background script listener to listen for closed tabs:

// Listen for closed tabs.
chrome.tabs.onRemoved.addListener(function(tab) {
    send_closed_message();
}); 

function send_closed_message () {
    chrome.tabs.getSelected(null, function(tab) {
        console.log("sending tab_closed to tab " + tab.id);
        chrome.tabs.sendRequest(tab.id, {close: true}, 
                                        function(response) {
            console.log(response.timer_stop); }); 
    });
}  

And here's the function in the content script that listens for this message.

function main () {
    console.log("main()");
    timer = new Timer();
    timer.start();

    // Listen for window focus
    window.addEventListener('focus', function() { timer.start(); } );

    // Listen for window blur
    window.addEventListener('blur', function() { timer.stop(); } );

    // Listen for tab close
    chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
        console.log(sender.tab ? 
                    "from a content script:" + sender.tab.url:
                    "from the extension");

        if (request.close === true) {
           sendResponse({timer_stop: "stopped"});
           timer.stop();
        }
    });
}

I do not see a response from the content script in the background script console. Since I'm closing the tab, I can't view the content script console. Where is the message going wrong? Is there a better way to debug this? Is there another way the content script could listen for when its tab closes?

like image 683
ecmendenhall Avatar asked Mar 09 '26 09:03

ecmendenhall


1 Answers

I believe the onRemoved on background happens when the tab is already being closed, so probably there is no enough time for the context to receive your message and replay back to the background script.

Maybe is a good idea for the context to keep sending messagens to background every second with its count value. And when the background receives the onRemoved event it simply uses the last received value as the live time of that page.

like image 80
Gustavo Vargas Avatar answered Mar 11 '26 21:03

Gustavo Vargas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!