在Tab切换事件上

时间:2011-05-15 13:53:49

标签: events firefox-addon

我正在寻找能够在浏览器中点击(更改)标签后运行一些代码的event,但我还没找到。

是否有可能以某种方式实现此事件?

我已经在监听DOMContentLoaded事件,我正在状态栏上显示有关当前页面的一些信息。当我更改选项卡时,状态栏中的信息不正确(我必须重新加载页面)。

谢谢

1 个答案:

答案 0 :(得分:5)

有两种方法可以做到这一点。

检测位置变化

nsIWebProgressListener界面用于检测窗口位置何时发生变化。在窗口的onLoad处理程序中放置这样的内容:

// 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);

请注意,每次窗口位置发生变化时,onLocationChange都会触发。这意味着它会在浏览器启动,当前选项卡中加载新URL,选项卡更改等时触发。如果您的目标是根据当前加载状态更新状态栏,这可能就是您想要的。 URL。

检测标签更改

要仅检测选择新标签的情况,请使用TabSelect事件。完整示例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);
相关问题