如何在特定选项卡上保留选项卡?

How to Keep Tabs on a Particular Tab?

在我的 firefox sdk 插件中,我想使用我的数据目录中的自定义网页作为我的 settings/about 页面。

但是我无法在选项卡上保持关注!

所以我有一个按钮调用 OptionsPanel() 函数在新选项卡中打开我的网页。现在,我想这样做,如果用户忘记该选项卡已打开并再次按下按钮,它会激活已经打开的设置选项卡。这意味着我需要知道该选项卡已打开,并且我需要能够切换到它(如果它已打开)或打开它(如果它尚未打开)。

这是我到目前为止想出的方法,但没有用;它只是总是打开一个新标签。我什至不知道我是否在咆哮正确的树。

const tabs = require("sdk/tabs");
var optionsTab;
function OptionsPanel(){
    var opsTab = GetTabByID(optionsTab.id);
    if(opsTab == null){
        tabs.open( data.url("OptionsPanel.html") );
        optionsTab.id = tabs.tab.id;  <======errors out as undefined
    }else{
        opsTab.activate();
    }
}

//return a handle to the tab that matches specified tab id
function GetTabByID(whatid){
    for(let thistab of tabs){
        if(thistab.id = whatid){
            return thistab;
        }
    }
    return null;
}

所以,这是我的目标:

  1. 如果我的页面尚未打开,请在新选项卡中打开它。
  2. 如果该选项卡已经打开,则切换到该选项卡。
  3. 如果页面在浏览器加载时打开,则准备好在用户按下选项按钮时切换到该选项卡。

为什么您认为 tabs 模块有 tab 属性?

通常您会使用 activeTab 属性。但是它不会在调用 tabs.open 后立即更新。必须改用 tabs[tabs.length - 1]

const tabs = require("sdk/tabs");
var optionsTabId;
function OptionsPanel(){
    var opsTab = GetTabByID(optionsTabId);
    if (opsTab == null) {
        tabs.open( data.url("OptionsPanel.html") );
        optionsTabId = tabs[tabs.length - 1].id;
    } else {
        opsTab.activate();
    }
}

此外,您在 GetTabByID 中犯了一个错误。

//return a handle to the tab that matches specified tab id
function GetTabByID(whatid){
    for(let thistab of tabs){
        if(thistab.id == whatid){ // use == to compare 
            return thistab;
        }
    }
    return null;
}

请记住,这是假设无法离开您的选项标签。我会检查 optsTab.url 以防万一。


或者您可以使用选项卡事件界面

const tabs = require("sdk/tabs");
const OPTIONS_URL = data.url("OptionsPanel.html");
var optionsTab = null;

function OptionsPanel(){
    if (optionsTab == null) {
        tabs.open(OPTIONS_URL);
        tabs.once('ready', function(tab) {
            optionsTab = tab;
            optionsTab.on('ready', function readyListener(tab) {
                if (tab.url !== OPTIONS_URL) {
                    optionsTab.off('ready', readyListener);
                    optionsTab = null;
                }
            })
            optionsTab.once('close', function(tab) {
                optionsTab = null;
            })
        });
    } else {
        optionsTab.activate();
    }
}