views:

37

answers:

2

I want to trigger some code when page action or browser action popup gets closed. I tried listening to onunload and onbeforeunload events on <body> or window but they never fire.

+1  A: 

As looks like there is no straight forward solution, this is what I ended up doing if anyone interested.

Periodically ping background page from the popup, and if background page is not received ping within some time period, it triggers required action. Works like a time bomb :)

In background page:

var timeoutId = 0;
function popupPing() {
    if(timeoutId != 0) {
        clearTimeout(timeoutId);
    }

    timeoutId = setTimeout(function() {
        popupClosed();
        timeoutId = 0;
    }, 1000);
}

function popupClosed() {
    //...
}

In popup:

ping();
function ping() {
    chrome.extension.getBackgroundPage().popupPing();
    setTimeout(ping, 500);
}

(note that popup pings 2 times faster than "trigger" time in background page)

serg
Although I really hope there is a better answer (and if there isn't, we should file a bug), this is a pretty cool hack. A sort of dead man's switch: http://en.wikipedia.org/wiki/Dead_man's_switch
npdoty
+1  A: 

It's a bug, but a chromium developer posted a workaround.

http://crbug.com/31262#c13

pdknsk