开发者

on tab switch event

I was开发者_如何学运维 looking for an event that is able to run some code after clicking (changing) tab in browser, but I haven't found it.

Is it possible to achieve this event somehow?

I'm already listening to DOMContentLoaded event, I'm displaying some information about the current page on the status bar. When I changed tab, the information in the status bar is not correct (I have to reload the page).

thank you


There are two possible ways to do this.

Detecting location change

The nsIWebProgressListener interface is used to detect when the window's location has changed. Place something like this in your window's onLoad handler:

// implements nsIWebProgressListener
var listener = {
    onLocationChange: function(aProgress, aRequest, aURI) {
        // fires on tab change; update status here;
        // get the currently selected tab
        var currDoc = gBrowser.contentDocument; 
    },
    onStateChange: function(a, b, c, d) {},
    onProgressChange: function(a, b, c, d, e, f) {},
    onStatusChange: function(a, b, c, d) {},
    onSecurityChange: function(a, b, c) {}
}

gBrowser.addProgressListener(
    listener, 
    Components.interfaces.nsIWebProgress.NOTIFY_LOCATION);

Note that onLocationChange fires every time the window's location changes. This means that it fires when the browser is started, when a new URL is loaded in the current tab, when the tab changes, etc. This is probably what you want if your goal is to update the status bar based on the currenty-loaded URL.

Detecting tab change

To detect only the case when a new tab has been selected, use the TabSelect event. Full example copied from here:

function exampleTabSelected(event) {
  var browser = gBrowser.selectedBrowser;
  // browser is the XUL element of the browser that's just been selected
}

// During initialisation
var container = gBrowser.tabContainer;
container.addEventListener("TabSelect", exampleTabSelected, false);

// When no longer needed
container.removeEventListener("TabSelect", exampleTabSelected, false);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜