4 jquery google-chrome-extension
我是初学者,在这个问题上花了好几个小时后,我决定问:
我的后台脚本只在我重新加载扩展并快速更改为选项卡后才向我的内容脚本发送消息.其他明智的事情都没有发生.
{
"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"
}
}
Run Code Online (Sandbox Code Playgroud)
Background.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {type:"test"}, function(response) {});
});
Run Code Online (Sandbox Code Playgroud)
helper.js
jQuery(document).ready(function() {
//Get allowed functions
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
if(msg.type == "test"){
alert("test received");
});
Run Code Online (Sandbox Code Playgroud)
警报框仅在重新加载扩展程序后触发,并快速切换到警告框应显示的选项卡.
所以我认为每次重新加载标签时都应该加载background.js.但是现在它只加载一次,如果我不在那个标签上,它会在helper.js准备发送响应之前加载.这是我的理论.但正如我所说,我是新手,我很难理解它是如何运作的.
最终我要完成的是让用户保存一些选项,每次加载页面时默认加载这些选项.保存选项页面中的选项工作得很好.弹出页面也正常工作.我只是无法获取要加载的默认选项,因为我无法将消息传递到内容脚本页面.
每次加载扩展时都会运行后台页面,因为它是一个事件页面,它将卸载,任何事件都将再次执行您的代码.尝试这样做
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");
});
Run Code Online (Sandbox Code Playgroud)
background.js
chrome.extension.onMessage.addListener(function(message,sender,sendResponse){
if(message.text == "getStuff")
sendResponse({type:"test"});
});
Run Code Online (Sandbox Code Playgroud)
这样,内容脚本就会启动信息流,因此您可以确定它已准备好接收它.