带有弹出窗口的chrome.browserAction.onClicked.addListener()

时间:2014-08-10 19:40:50

标签: javascript google-chrome google-chrome-extension

我想在每次点击浏览器图标时将Listener添加到触发的事件中。我还有一个弹出窗口,单击此图标即可出现。

我试过chrome.browserAction.onClicked.addListener()但是没有把它解雇,后来我看到文档说:

Fired when a browser action icon is clicked. 
This event will not fire if the browser action has a popup. 

所以,我有弹出窗口,所以这个监听器不起作用。在我的案例中,我可以采用哪种解决方法将Listener附加到图标?

2 个答案:

答案 0 :(得分:6)

没有解决方法将侦听器附加到该事件,但您可以使用消息传递让您的后台页面知道弹出窗口已打开。

在你的弹出窗口中,尽快:

chrome.runtime.sendMessage({popupOpen: true});

在您的背景页面中:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
  if(message.popupOpen) { /* do your stuff */ }
});

答案 1 :(得分:1)

对于@ Xan的回答,我需要更明确的一些内容,所以这就是我所做的:

这是我的index.html

<!DOCTYPE html>
<html>
<head>
  <title>Ahead of time compilation</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="styles.css">
  <script src="node_modules/core-js/client/shim.min.js"></script>
  <script src="node_modules/zone.js/dist/zone.js"></script>
  <script src="loader.js"></script>
  <script src="popup.js"></script>


</head>
<body>
<my-app>Loading...</my-app>
</body>
<script src="dist/build.js"></script>
</html>

以下是popup.js

chrome.runtime.sendMessage({popupOpen: true});

以下是manifest.json

{
  "manifest_version": 2,
  "name"            : "Test ang 2",
  "description"     : "jons test",
  "short_name"      : "test",
  "version"         : "1.0",
  "browser_action": {
    "default_icon" : "app/assets/icon.png",
    "default_title": "hi jon",
    "default_popup": "index.html"
  },
  "permissions": [
    "debugger",
    "activeTab",
    "tabs",
    "alarms",
    "clipboardWrite",
    "notifications",
    "background",
    "storage",
    "cookies",
    "https://*/",
    "http://*/"
  ],
  "web_accessible_resources": [
    "assets/*",
    "bower_components/*",
    "components/*",
    "app.module.js",
    "app.routes.js",
    "index.html",
    "app/*"
  ],
  "externally_connectable": {
    "matches": [
      "*://*.capitalone.com/*"
    ]
  },
  "background": {
    "scripts":["background.js"]
  },
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": ["content-scripts.js"]
    }
  ],
  "content_security_policy": "script-src 'self' ; object-src 'self'"
}

以下是background.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
  console.log(message);
  alert('hello world');
  if(message.popupOpen) {
    console.log('popup is open');
  }
});