好的,所以我有一个内容脚本,后台脚本和我的主脚本,所有消息都互相发送。虽然内容脚本可以很好地说明后台脚本,但后台不会对扩展中的主脚本说话。
脚本:
内容脚本
var port = chrome.runtime.connect({name:'appName'});
port.postMessage({'bookmark':{
userName:el.getAttribute('data-name'),
userImage:el.getAttribute('data-image'),
post:el.parentNode.querySelector('.content div').innerHTML,
postLink:"http://"+location.hostname + location.pathname + "#"+el.parentNode.id.replace('p','')
}
});
后台脚本 *持久性
chrome.runtime.onConnect.addListener(function(port) {
port.onMessage.addListener(function(msg) {
if(msg.bookmark){
chrome.runtime.sendMessage({'newBookmark':msg.bookmark});
var notify = window.webkitNotifications.createNotification(
'http://i57.servimg.com/u/f57/18/65/52/70/128-lo11.png',
'Bookmarks Updated',
msg.bookmark.userName+"'s post has been saved in your bookmarks for later use");
notify.show();
setTimeout(function(){
notify.cancel();
},9000);
}
port.postMessage({'bookmarklet':true});
});
});
扩展主JS
chrome.runtime.onMessage.addListener(function(msg,sender){
_userdata.bookmarks[msg.bookmarks[msg.bookmarks.postLink]=msg.bookmarks;
chrome.storage.sync.set({'system_settings':_userdata});
});
清单
{
"name": "AvacWeb Chrome Tools",
"short_name":"AWCT",
"version": "0.5.5",
"description": "This extension is for AvacWeb members. Giving our users an awesome Google Chrome tool for our website is the first of many awesome things to come. We are proud of our members so we took the liberty of giving you the avacweb experience anywhere you go!",
"browser_action": {
"default_icon":{
"19": "images/19-logo.png",
"38":"images/38-logo.png",
"128":"images/128-logo.png"
},
"default_title": "AvacWeb Chrome Tools",
"default_popup": "main.html"
},
"icons":{
"16": "images/19-logo.png",
"48":"images/48-logo.png",
"128":"images/128-logo.png"
},
"content_scripts": [
{
"matches": ["*://www.avacweb.com/t*"],
"js": ["injection.js"],
"css":["bookmark.css"]
}
],
"manifest_version": 2,
"permissions":["storage","background","notifications"],
"background": {
"scripts": ["background.js"],
"persistant":true
},
"content_security_policy": "script-src 'self' https://www.google.com; object-src 'self'"
}
基本上我要做的是当用户点击网页上的一个元素时,它会向后台发送一条消息,然后轮流将消息发送到扩展的html内的main.js,因此我将我的数据存储在chrome.storage.sync
我已经遵循了所有文档,我相信背景和扩展应该能够进行通信。是否有一些我遗漏的东西很小或很傻。
任何人都有一个建议吗?