改进 ahnquan 的答案,因此chrome.contextMenus.create
不会在每个后台脚本调用中调用,并且还将其编码highlighted text
为 URI,因此当它包含特殊字符时不会中断,例如;,/?:@&=+$
.
您的 background.js 将如下所示:
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({
"title": 'Search Google for "%s"',
"contexts": ["selection"],
"id": "myContextMenuId"
});
});
chrome.contextMenus.onClicked.addListener(function(info, tab) {
chrome.tabs.create({
url: "http://www.google.com/search?q=" + encodeURIComponent(info.selectionText)
});
})
和 manifest.json:
{
"manifest_version": 2,
"name": "App name",
"version": "1.0",
"permissions": ["contextMenus"],
"background": {
"scripts": ["background.js"],
"persistent": false
}
}