如何有背景脚本和类似于默认弹出的东西

How to have background script and something similar to a default popup?

本文关键字:默认 类似于 背景 脚本      更新时间:2023-09-26

所以,我明白你不能有后台脚本和默认弹出在一起。如果是这样的话,我怎么能有类似的默认弹出(那里有一些简单的HTML,出现当你点击扩展的图标),并有后台脚本修改该弹出的内容?

manifest.json

"browser_action": {
    "default_title": "Mark this position!",
    "default_icon": "icon.png"
},
"background": {
    "scripts": ["background.js"],
    "persistent": false
},
"content_scripts": [
    {
        "matches": [
            "http://*/*",
            "https://*/*"
        ],
        "js": ["content.js"]
    }
],

你绝对可以同时拥有一个弹出窗口(即default_popup集)和背景页面。背景页面将有自己的生命周期(与"persistent": false它是一个事件页面),弹出窗口将存在,只要它打开。

我猜你的困惑源于这样一个事实,你不能有一个弹出窗口和chrome.browserAction.onClicked监听器在同一时间。

这是真的,但是还有其他方法可以告诉你的背景页面弹出窗口已经打开。

你可以从弹出窗口发送消息给后台页面:

// popup.js, should be included in the popup
chrome.runtime.sendMessage({popupOpen: true}, function(response) {
  /* process response */
});
// background.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  if(message.popupOpen) {
    /* do stuff */
    sendResponse(response);
  }
});

如果你把上面的弹出代码放在顶层,那么一旦弹出窗口打开,背景就会被通知。

虽然您可以直接从后台访问弹出窗口(参见chrome.extension.getViews),但建议您将UI逻辑移动到弹出窗口本身,并使用上述消息传递与后台通信,并共享chrome.storage