Detecting tab closed (after closed) from Firefox extension

时光毁灭记忆、已成空白 提交于 2020-01-05 10:32:02

问题


I'm trying to get my Firefox extension to create a url list from all tabs in the browser. To keep the list updated I need to know when a tab has been closed.

I've tried using:

window.addEventListener("TabClose", tabRemoved, false);

However, this gets called BEFORE the tab is actually closed, which results in my updated tablist still containing the closed tabs url.

I update the tab list by iterating all browsers, like so:

function ()
{
    gBrowser = window.getBrowser();
    tabs = gBrowser.browsers;
    urls = [];

    for (var i = 0; i < tabs.length; i++)
    {
        if (typeof(tabs[i]) != "undefined") {
            urls.push(tabs[i].webNavigation.currentURI.spec);
        }
    }

    return urls;
}

So what I'm looking for is an event that gets called AFTER a tab has been closed, or a way to get the index of the tab that was closed so that I can skip it while iterating browsers.

Anyone know of any such event or other solutions to my problem?


回答1:


There is no special event for that - you simply catch the regular event and update the tab list delayed. Something along these lines:

var tabRemoveTimeout = null;
window.addEventListener("TabClose", tabRemoved, false);

function tabRemoved(event)
{
  // If we already scheduled an async action - cancel it
  if (tabRemoveTimeout)
    window.clearTimeout(tabRemoveTimeout);

  tabRemoveTimeout = window.setTimeout(function()
  {
    tabRemoveTimeout = null;
    updateTabList();
  }, 0);
}

A less generic approach would be updating the list immediately but excluding the tab that is being closed.




回答2:


Here is what I did to solve the problem:

tabRemoved = function (ev)
{
    logTabs([ev.target._tPos]); /* ev.target._tPos = index of tab that was closed */
}

logTabs = function (excludelist)
{
    ...
    urls = getTabURLs();
    for(var i = 0; i < urls.length; i++)
    {
        if(typeof(excludelist) != "undefined" && excludelist.indexOf(i) != -1)
            continue;

        doStuff(urls[i]);
    ...


来源:https://stackoverflow.com/questions/9572466/detecting-tab-closed-after-closed-from-firefox-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!