background是作为背景页来使用,content.js是注入到页面中。两者通过通信来实现内容的传输。整个过程学习到了chrome的插件的制作方式,通过阅读chrome.360.cn提供的文档,基本上知道了chrome提供了哪些接口。以后再做chrome插件的时候就胸有成竹了。:-)
background.js
[code lang=”js”]
var searchInfo;
var zy = {
toEtao: function() {
if(searchInfo){
var url = ‘http://s.etao.com/search?q=’ + searchInfo;
} else {
var url = ‘http://www.etao.com’;
}
chrome.tabs.create({
url: url
});
}
};
chrome.contextMenus.create({
"title": "一淘搜索",
"type": "normal",
"contexts": ["all"],
"onclick": zy.toEtao
});
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if (request.info){
searchInfo = request.info;
sendResponse({
farewell: "success"
});
};
});
[/code]
content.js
[code lang=”js”]
function sendMsg(msg) {
chrome.extension.sendRequest({info : msg}, function(response){
console.log(response.farewell);
});
}
document.addEvent(‘mouseup’, function(){
var userSelection = window.getSelection();
sendMsg(userSelection.toString());
console.log(‘发送成功’);
});
[/code]