如何有后台脚本和类似的默认弹出窗口? [英] How to have background script and something similar to a default popup?
问题描述
这里是manifest.json
browser_action:{
default_title:
default_icon:icon.png
},
background:{
scripts:[background.js] ,
persistent:false
},
content_scripts:[
{
matches:[
http:// * / *,
https:// * / *
,
js:[content.js]
}
],
你完全可以同时拥有一个弹出窗口(即 default_popup
set)和一个背景页面。后台页面将拥有自己的生命周期(persistent:false
它是一个活动页面),弹出窗口会一直存在。
我想你的困惑源于你不能拥有的事实一个弹出窗口和一个 chrome.browserAction.onClicked
监听器。
这是真的,但有其他方式告诉你的背景页面,弹出窗口已打开。
您可以从弹出窗口中向背景页面发送消息:
// popup.js应包含在弹出窗口
中chrome.runtime.sendMessage({popupOpen:true},function(response){
/ *过程响应* /
});
// background.js
chrome.runtime.onMessage.addListener(函数(message,sender,sendResponse){
if(message.popupOpen){
/ * do stuff * /
sendResponse(response);
}
});
如果您将上面的弹出式代码放在顶层,那么后台会尽快通知弹出窗口打开。
虽然您可以从后台直接访问弹出窗口(请参阅 chrome.extension.getViews
),建议您将UI逻辑移动到弹出窗口本身并与背景使用信息,并共享 chrome.storage
。
So, I understand that you cannot have background scripts and a default popup together. If this is so, how can I have something similar to a default popup (where there is some simple HTML that appears when you clicked the extension's icon) and have the background script modify the contents of that popup?
Here's the 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"]
}
],
You absolutely can have both a popup (i.e. default_popup
set) and a background page. The background page will have its own lifecycle (with "persistent": false
it's an Event page) and the popup will exist as long as it's open.
I guess your confusion stems from the fact that you cannot have a popup and a chrome.browserAction.onClicked
listener at the same time.
This is true, but there are other ways to tell your background page that the popup has opened.
You can message the background page from the popup:
// 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);
}
});
If you put the above popup code on the top level, then the background will be informed as soon as the popup opens.
While you can directly access the popup's window from the background (see chrome.extension.getViews
), it's recommended that you move the UI logic into the popup itself and communicate with the background using Messaging as above and shared chrome.storage
.
这篇关于如何有后台脚本和类似的默认弹出窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!