我是个chrome扩展的新手,在这个问题上花了几个小时之后,我决定问:
我的后台脚本只有在我重新加载扩展并快速切换到选项卡后才会向内容脚本发送消息。否则什么都不会发生。
{
"name": "Fixes",
"version": "2",
"manifest_version": 2,
"description": "SomeFixes",
"permissions": ["tabs", "http://*/*", "https://*/*", "storage"],
"options_page": "options.html",
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["<all my urls>"],
"js": ["jquery1.7.js", "helper.js"]
}
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "options.html"
}
}Background.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {type:"test"}, function(response) {});
});helper.js
jQuery(document).ready(function() {
//Get allowed functions
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if(msg.type == "test"){
alert("test received");
});警告框仅在重新加载扩展后触发,并快速切换到应显示警告框的选项卡。
所以我认为background.js应该在我每次重新加载标签的时候加载。但现在它只加载一次,如果我不在那个选项卡上,它会在helper.js准备发送响应之前加载。这是我的理论。但正如我所说的,我是新手,我正在努力理解它是如何工作的。
最终,我试图完成的是让用户保存一些选项,这些选项将在每次页面加载时默认加载。保存选项页面中的选项工作正常。弹出页面也可以正常工作。我无法加载默认选项,因为我无法将消息发送到内容脚本页面。
发布于 2013-03-23 00:22:01
后台页面将在每次加载扩展时运行,并且由于它是一个事件页面,它将被卸载,并且它的任何事件都将再次执行您的代码。试着像这样做
helper.js
chrome.extension.sendMessage({text:"getStuff"},function(reponse){
//This is where the stuff you want from the background page will be
if(reponse.type == "test")
alert("Test received");
});background.js
chrome.extension.onMessage.addListener(function(message,sender,sendResponse){
if(message.text == "getStuff")
sendResponse({type:"test"});
});这样,内容脚本就会启动信息流,这样您就可以确定它已经准备好接收信息了。
https://stackoverflow.com/questions/15575030
复制相似问题