chrome.browserAction.onClicked.addListener() with popup

chrome.browserAction.onClicked.addListener() with popup

本文关键字:with popup addListener browserAction onClicked chrome      更新时间:2023-09-26

我想在每次点击浏览器图标时触发的事件中添加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不起作用。在我的情况下,我可以做些什么来附加侦听器图标?

没有办法给这个事件附加一个监听器,但是你可以使用消息传递让后台页面知道弹出窗口已经打开。

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

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

背景页:

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

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