ACEnglish
ACEnglish

Reputation: 115

chrome extension content script before tab-close or page change

I have a content-script that's initiated in my background.js with:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    var url = (new String(tab.url)).valueOf();
    if(url.indexOf("chrome") == 0 || url == undefined || url == 'undefined')
        return;
    if(changeInfo.status == 'complete') {            
        chrome.tabs.executeScript(tabId,
        {file: "js/control.js", runAt:"document_end"},
        function() { console.log("Control sent to page");
    });
    console.log("ChangeInfo " + changeInfo.status);
});

I need to execute a function before the page changes or the window closes. I've looked around and can't figure out how to do this. The closest thing I could find was:

chrome.runtime.onSuspend.addListener(function () {
    someObjectDefinedInScript.afunction("stopping");
});

Because I got chrome.runtime.sendMessage to work in the content-script.

But this returns an error:

Uncaught TypeError: Cannot call method 'addListener' of undefined

Upvotes: 2

Views: 3708

Answers (2)

AlbertoFdzM
AlbertoFdzM

Reputation: 1053

You may use chrome.tabs.onRemoved event to listen to Tab close (You should declare this listener on your background script).

More info: https://developer.chrome.com/extensions/tabs#event-onRemoved

Upvotes: 1

Xan
Xan

Reputation: 77523

Good old window.onunload will work from a content script.

Upvotes: 2

Related Questions