【问题标题】:chrome.windows.create creates new popups when execute multiple timeschrome.windows.create 在多次执行时创建新的弹出窗口
【发布时间】:2021-12-04 19:42:53
【问题描述】:

我有这个带有 browser_action 按钮的 chrome 扩展。单击此浏览器操作时,后台脚本会打开一个弹出窗口,如下所示

const popup = window.open('popup.html', tab.id, 'menubar=0,innerWidth=900,innerHeight=800');

当用户多次单击浏览器动作时,每次都会重新创建弹出窗口(我没有得到多个弹出窗口)

但是,现在我想用browser.windows.create 替换这段代码,据我所知,这更像是一种扩展方式。所以我创建了

browser.windows.create({url: 'popup.html', height: 800, width: 900, type: 'popup'});

这几乎相同,除了当用户多次单击浏览器操作按钮时,我得到多个弹出窗口,这不是我想要的。有没有办法获得与 `window.open 相同的行为?

【问题讨论】:

    标签: javascript google-chrome-extension popup


    【解决方案1】:

    这是我的建议(打字稿):

    function findTab(tab: chrome.tabs.Tab) {
        return tab.url == "popup.html";
    }
    
    // first get all open chrome windows
    let windows = await chrome.windows.getAll({populate: true, windowTypes: ["popup"]});
    
    // find a window that has a tab with the url "popup.html"
    let myWindow = windows.find(window => window.tabs.some(tab => findTab(tab)));
    
    // find a tab that has the url "popup.html"
    let myTab = myWindow?.tabs.find(tab => findTab(tab));
    
    if (myWindow && myTab) {
        // if such tab exists, focus the parent window and the tab
        await chrome.windows.update(myWindow.id, {focused: true});
        await chrome.tabs.update(myTab.id, {active: true});
    }
    else {
        // open the window and the tab
        await chrome.windows.create({url: "popup.html", type: "popup"});
    }
    

    【讨论】:

    • 是的,这行得通。非常感谢!
    猜你喜欢
    • 2023-03-18
    • 2011-06-17
    • 2017-08-28
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    相关资源
    最近更新 更多