Messaging: Background script to close tabs

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

Here's how I set up a 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 is the function in the content of the 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();
        }
    });
}

script script. , script. ? ? , script , ?

+3
1

, onRemoved , , , , , script.

, , . onRemoved, .

+1

All Articles