检查窗口是否已从非父窗口(chrome 扩展程序)打开

Check if window is already open from a non-parent window (chrome extension)

本文关键字:窗口 扩展 chrome 程序 打开 是否 检查      更新时间:2023-09-26

我正在制作Chrome扩展程序。单击popup.html中的按钮将打开一个新窗口并加载feedback-panel.html

这有效,但是,在单击时,我想检查窗口是否已经打开,如果是这样,请专注于它而不是创建一个新窗口。

JavaScript window.open 仅在窗口不存在时才看起来很有前途,但它依赖于打开的窗口在打开窗口时作为变量存储在父页面上,并在打开新窗口之前检查这些窗口。这对我不起作用,因为父窗口(popup.html)通常会关闭并重新打开,我会丢失变量。

我试图实现同样的想法,但将窗口变量存储在chrome.storage中,因为它允许您存储对象。好吧,它确实允许您存储对象,但它首先序列化它们,因此窗口变量会丢失其所有功能,我最终得到

result.feedbackPanel.focus() 不是一个函数

这是我的尝试:

function openFeedbackPanel(){
    chrome.storage.local.get('feedbackPanel', function (result) {
        console.log( result.feedbackPanel); // logs window object sans all functions
        if(result.feedbackPanel && ! result.feedbackPanel.closed){
            try{
                result.feedbackPanel.focus();
            }
            catch(error){
                chrome.storage.local.remove('feedbackPanel', function () {
                });
                createFeedbackPanel();
            }
        }
        else{
            createFeedbackPanel();
        }
    });
}
function createFeedbackPanel(){
    var win =  window.open('feedback-panel.html', 'Feedback', 'width=935, height=675');
    console.log(win); // logs full object as expected 
    chrome.storage.local.set({"feedbackPanel": win});
}

$('#some-button').click(openFeedbackPanel());

因此,由于这不起作用:

如何检查弹出窗口是否已从非父窗口(未打开弹出窗口的窗口)打开?

无需跟踪窗口并存储它们。
如果您知道扩展程序 ID,最简单的方法是测试所有选项卡的 URL,看看它是否已打开

chrome.tabs.query({}, function(tabs) {
  var doFlag = true;
  for (var i=tabs.length-1; i>=0; i--) {
    if (tabs[i].url === "chrome-extension://EXTENSION_ID/feedback-panel.html") {
      //your popup is alive
      doFlag = false;
      chrome.tabs.update(tabs[i].id, {active: true}); //focus it
      break;
    }
  }
  if (doFlag) { //it didn't found anything, so create it
    window.open('feedback-panel.html', 'Feedback', 'width=935, height=675');
  }
});

这里已经回答了如何获取扩展ID,

您还可以使用邮件系统。这是我用于扩展选项的示例。在 onClick 中调用这样的函数以获取按钮:

    // send message to the option tab to focus it.
    // if not found, create it
    showOptionsTab: function() {
        chrome.runtime.sendMessage({window: 'highlight'}, null, function(response) {
            if (!response) {
                // no one listening
                chrome.tabs.create({url: '../html/options.html'});
            }
        });
    },

在您的窗口/选项卡中收听这样的消息

// listen for request to make ourselves highlighted
chrome.runtime.onMessage.addListener(t.onMessage);
...
// message: highlight ourselves and tell the sender we are here
t.onMessage = function(request, sender, response) {
    if (request.window === 'highlight') {
        chrome.tabs.getCurrent(function(t) {
            chrome.tabs.update(t.id, {'highlighted': true});
        });
        response(JSON.stringify({message: 'OK'}));
    }
};

此方法的一个优点是它不需要选项卡权限。