建立一个插件popup页面到chrome tab子页面的通信连接
注意要在插件启动后,刷新页面,才会执行contentscript.js, 注册监听request
manifeset.json
{
"name": "MyTaskList",
"version": "0.9.0",
"manifest_version": 2,
"description": "Management my everyday's task lists.",
"browser_action": {
"default_icon": "icon.png" ,
"default_title": "My Task List",
"default_popup": "popup.html"
} ,
"permissions": [ "tabs"],
"content_scripts": [{
"js": [
"jquery.js",
"contentscript.js"
],
"matches": [ "http://*/*", "https://*/*" ],"run_at": "document_end"
}]
}
popup.html
<!doctype html>
<html>
<head>
<title>test</title>
<script src="jquery.js"></script>
<script src="popup.js"></script>
</head>
<body>
<input type="text" id="filter" size="24">
<input type="button" id="try" name="try" value="try">
<div id="show">init</div>
</body>
</html>
$(function(){init();});
function init(){
$('#show').html('ready');
$('#filter').val(readVal('myFilter','#cnt'));
$('#try').bind("click",function(){
chrome.tabs.getSelected(null, function(tab) {
alert(tab.id)
chrome.tabs.sendRequest(tab.id, {filter: $('#filter').val()}, function(response){
$('#show').html(response.flag);
});
});
});
}
///数据存储
function readVal(val, defa){
if(typeof(localStorage.getItem(val)) == 'undefined') {
re = defa;
localStorage.val = defa;
}
else
re = localStorage.val;
return re;
}
function saveVal(val, content) {
localStorage.setItem(val) = content;
}
contentscript.js
alert("dsds13")
console.log("from a content script:");
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
$(request.filter).css('background-color', '#EE4444');
sendResponse({flag: "ok"});
});