Chrome extension popup showing by condition

别说谁变了你拦得住时间么 提交于 2019-12-04 11:35:22
Xan

In short: you can't do it the way you describe.

When a popup page is set, chrome.browserAction.onClicked won't fire, and the popup will show.

When a popup page is not set, your event listener will execute, but you cannot show a popup programmatically. The most you can do is to set a popup for the next click.

So, what to do with it?

1) You can do an ugly hack (kind of) described in Edwin's answer. Always show the popup, check the condition as soon as possible, message the background and execute window.close() if the condition is met.

Of course, it is ugly.

2) The proper way to do this would be updating the popup whenever the condition can potentially change. That is, whenever you add/remove data from pcTabs, you should set/unset the popup with chrome.browserAction.setPopup

// ... somewhere ...
pcTabs.push(/*...*/);
chrome.browserAction.setPopup({popup: ''});

// ... somewhere else ...
pcTabs.pop(/*...*/);
if(!pcTabs.length) chrome.browserAction.setPopup({popup: 'popup.html'});    

chrome.browserAction.onClicked.addListener(function() {
  // Assume condition is met, popup didn't show
});

3) The fancy way to do it is to use experimental JavaScript method, Array.observe, that is only supported in Chrome.

var pcTabs = [];
Array.observe(pcTabs, function(changes) {
  changes.forEach(function(change) {
    if(change.object.length) {
      chrome.browserAction.setPopup({popup: ''});
    }   else {
      chrome.browserAction.setPopup({popup: 'popup.html'});  
    }
  });
});

Alright this is my code:

chrome.tabs.query({currentWindow: true, active: true}, function(tabs) {
    if (!tabs[0].url.includes('google.com')) { //check if current tab is not google: if false show popup, you can just put an else at the end and do w.e with your popup
        chrome.tabs.query({currentWindow: true, url: 'https://*.google.com/*'}, function(tabs) { //since current tab is not google query tabs with google
            if (tabs.length) { //check if there are any pages with google
                chrome.tabs.highlight({tabs: tabs[0].index}, function(w) {}); //this is what I chose to do idk what you want to do but you can write w.e here
            } else { 
                chrome.tabs.create({url: 'https://google.com'}); //other wise no pages with google open one
            }
        });
    };
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!