Chrome扩展程序弹出窗口按条件显示

Chrome扩展程序弹出窗口按条件显示

问题描述:

我想通过单击显示弹出窗口,但前提是条件为假. 单击扩展程序图标后,背景js搜索带有当前名称的标签.如果找到选项卡,则后台js继续工作.如果未找到-我想显示带有说明的弹出窗口.无法理解在这种情况下如何仅显示弹出窗口. 我可以通过browserAction.setPopup()设置弹出窗口,但是仅在下次单击后才会显示弹出窗口. 我只想显示一次弹出窗口. 绝对有可能,我已经在其他扩展程序上看到了这种行为.

I want to show popup by click, but only if condition is false. After click to extension icon background js searchig for tab with current name. If tab found background js continues working. If not found - i want to show popup with instructions. Can`t understand how to just show popup in this case. I can set popup by browserAction.setPopup(), but popup will be displayed only after next clicks. I just want to show my popup one time. It is definitely posible, I've seen this behavior on other extension.

var pcTabs; // tabs array

chrome.browserAction.onClicked.addListener(buttonClick);

function buttonClick() {
 // getting tabs...
 if(pcTabs.length != 0){
    // working with finded tabs
 } else{ // tabs not found
    // show popup.html here. this is the question
 }
}

更新. 这是我的 background.js .所有代码也都在存储库中. 如何将警报替换为弹出窗口?

upd. This is my background.js. All code also in repository. How to replace alerts to popups?

简而言之:您无法按照描述的方式进行操作.

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

设置了弹出页面后,chrome.browserAction.onClicked将不会触发,并且将显示弹出窗口.

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.

那么,怎么办呢?

1)您可以进行Edwin的答案中描述的丑陋的骇客行为.始终显示弹出窗口,尽快检查条件,向后台发送消息,并在满足条件时执行window.close().

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.

当然,这很丑.

2)执行此操作的正确方法是在条件可能发生变化时更新弹出窗口.也就是说,每当您从pcTabs添加/删除数据时,都应该使用

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)做到这一点的 方法是使用实​​验性JavaScript方法

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'});  
    }
  });
});