开发了一个简单的谷歌浏览器小插件 --- 百度精简搜索
先来看下插件效果图:
"default_title": "\u6253\u5F00\u767E\u5EA6"
},
"content_scripts": [ {
"js": [ "detector.js" ],
"matches": [ "http://*/*", "https://*/*" ]
} ],
"content_security_policy": "script-src 'self' 'unsafe-eval' https://ssl.google-analytics.com; object-src 'self'",
"description": "Quick access to Baidu \u7CBE\u7B80\u7248\uFF0C\u5212\u8BCD\u53F3\u952E\u83DC\u5355\u5FEB\u901F\u641C\u7D22",
"icons": {
"128": "logo128.png",
"48": "logo48.png",
"16": "logo16.png"
},
"manifest_version": 2,
"name": "\u767E\u5EA6\u7CBE\u7B80\u641C\u7D22",
"permissions": [ "contextMenus", "tabs", "http://*/*", "https://*/*", "notifications", "webRequest", "webRequestBlocking" ],
"update_url": "https://clients2.google.com/service/update2/crx",
"version": "1.0"
}
background.js:
var win = null,
text = '',
search_text = null;
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendMessage(tab.id, {selected: true}, function(response) {
if (!response) return;
var search_text = response.data;
if(search_text.length == 0 && win) {
chrome.windows.update(win.id, { focused: true });
} else if(search_text.length > 1) {
toSearch(search_text);
} else {
toSearch();
}
});
if (tab.url.indexOf('chrome://') == 0) toSearch();
});
});
var toSearch = function(_text) {
text = _text;
var url = 'http://www.baidu.com';
if(text && !text.status && text != ''){
url = 'http://www.baidu.com/s?wd=' + text;
}
chrome.tabs.query( {'active' : true}, function(tabs){
chrome.tabs.create({url:url,index: tabs[0].index + 1});
})
};
chrome.windows.onRemoved.addListener(function(windowId) {
if(!win) return;
if(windowId = win.id)
win = null;
});
chrome.contextMenus.onClicked.addListener(function clickMenuToSearch(info, tab){
selectedText = info.selectionText;
if(selectedText.length == 0 && win) {
chrome.windows.update(win.id, { focused: true });
} else if(selectedText.length > 0) {
toSearch(selectedText);
} else {
toSearch();
}
});
chrome.contextMenus.create({"title": "用 Baidu 搜索 '%s'", "contexts": ["selection"], "id": "用 Baidu 搜索 '%s'"});
detector.js:
var detector = {
addListen: function() {
chrome.extension.onMessage.addListener(
function(request, sender, sendResponse) {
var selected = detector.getSelectedText();
if (request.selected) {
sendResponse({data: selected});
}
});
},
getSelectedText: function() {
var txt = 'nothing';
if (window.getSelection){
txt = window.getSelection().toString();
} else if (document.getSelection) {
txt = document.getSelection().toString();
} else if (document.selection) {
txt = document.selection.createRange().text;
}
return txt;
}
};
detector.addListen();
开发好代码后就可以到Chrome浏览器的扩展程序页面,开启开发者模式来进行调试以及打包生成crx文件进行安装。
点击下载打包好的baidu.crx文件