我正在寫一個Chrome擴展程序捕獲用戶文本選擇,並將所選文本,谷歌搜索。捕獲文本選擇在谷歌文檔
manifest.json的
{
"manifest_version": 2,
"name": "Selection Extension",
"description": "Search your selected text",
"version": "1.0",
"permissions": [
"tabs",
"http://*/*",
"https://*/*"
],
"background": {
"scripts": [
"background.js"
],
"persistent": false
},
"browser_action": {
"default_icon": "icon.png",
"default_title": "Mark it!!"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content_script.js"]
}
]
content_script.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection") {
sendResponse({data: window.getSelection().toString()});
} else {
sendResponse({});
}
});
background.js
function initBackground() {
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.sendMessage(tab.id, {method: "getSelection"}, function(response){
sendServiceRequest(response.data);
});
});
}
function sendServiceRequest(selectedText) {
var serviceCall = 'http://www.google.com/search?q=' + selectedText;
chrome.tabs.create({url: serviceCall});
}
initBackground();
這種鱈魚e可在網頁(如Gmail,Facebook和新聞。) 我也希望能夠獲得在PDF的選擇,和谷歌文件(在瀏覽器中查看)的選擇。 在這些情況下:window.getSelection
返回空字符串...
有人知道該怎麼做嗎?
感謝你爲這個!我將刪除executeScript。 –
對於google-docs,這裏有一個帶有「kix-selection-overlay」類的HTML元素。這個類是創建選擇外觀的實際div(即深青色背景)。但它沒有連接反正包含文本的DIV ... –
關於PDF:https://stackoverflow.com/questions/15527095/how-extension-get-the-text-selected-in-chrome-pdf-查看器 –