打开新页面时保持弹出窗口打开状态

Keep Popup Open when Opening a new Page

本文关键字:状态 窗口 新页面      更新时间:2023-09-26

我有以下代码来介绍我的Chrome扩展程序。

// detect if this is the first time running
var first_run = false;
if (!localStorage['ran_before']) {
    first_run = true;
    localStorage['ran_before'] = '1';
}
// if not, start the intro() script
if (first_run) intro();
// intro script
function intro() {
    window.open("intro/index.html", '_blank');
}

但遗憾的是,当我单击扩展程序时,它不会打开popup.html,而只是打开介绍页面......它需要保持popup.html打开状态,我相信有一种方法可以做到这一点。我想同时打开它们。

最好的方法是什么?

您使用的方法有效并且应该有效,但您可能应该只需使用 onInstalled 事件即可保持一致性:

chrome.runtime.onInstalled.addListener(function(info){
    if(info.reason == "install"){
        console.log("Installed!");
    }else if(info.reason == "update"){
        console.log("Updated!");
    }
});

它不需要新的权限,并且会使安装代码与其余代码明确分开。

虽然Marc Guiselin的回答非常好,但知道如何在不关闭弹出窗口的情况下打开选项卡可能会很有用。

您可以在后台打开该选项卡,这样它就不会关闭弹出窗口。

chrome.tabs.create({
  url: chrome.runtime.getURL("intro/index.html"),
  active: false
});

通常,应避免在扩展中使用window.open,而应改用chrome.tabschrome.windows API。