chrome消息传递实例

不管我本人多么平庸,我总觉得对你的爱很美。

manifest.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"name": "消息传递",
"version": "1.0",
"manifest_version": 2,
"description": "各个页面JS之间事件的触发和消息的传递",
"browser_action": {
"default_icon": "images/icon38.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["js/background.js","js/jquery.min.js"],
"persistent": false
},
"permissions": ["tabs", "<all_urls>"]
}
1
2
3
4
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/content.js"></script>

<button id="newtab" >new tab</button>

content.js

1
2
3
4
5
$(document).ready(function () {
$("#newtab").click(function () {
chrome.runtime.sendMessage({action:"new_tab"});
});
});

background.js

1
2
3
4
5
6
7
8
9
10
11
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

if(request.action != 'new_tab'){
var newURL = "http://stackoverflow.com/";
chrome.tabs.create({ url: newURL });
}else {
var newURL = "http://www.baidu.com/";
chrome.tabs.create({ url: newURL });
}

});