10

我正在寫一個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返回空字符串...

有人知道該怎麼做嗎?

+0

感謝你爲這個!我將刪除executeScript。 –

+0

對於google-docs,這裏有一個帶有「kix-selection-overlay」類的HTML元素。這個類是創建選擇外觀的實際div(即深青色背景)。但它沒有連接反正包含文本的DIV ... –

+0

關於PDF:https://stackoverflow.com/questions/15527095/how-extension-get-the-text-selected-in-chrome-pdf-查看器 –

回答

5

谷歌文檔文件並沒有真正遵循如何對從擴展訪問文本的正常方式。 我爲此創建了谷歌文檔,其中可以發現here

這將使你的工作的工具:

//contentScript.js 
var googleDocument = googleDocsUtil.getGoogleDocument(); 
console.log("The selected text is: " + googleDocument.selectedText); 
+0

你可以請分享精確的代碼剪 - 僅用於獲取選定的文本? –

1

您可以從上下文菜單中得到這個。我敢打賭,無論如何你都會添加一個上下文菜單項。

chrome.contextMenus.create({ 
    id:"g-search", 
    title:"Search %s", 
    contexts:["selection"] 
}); 

chrome.contextMenus.onClicked.addListener(function(sel){ 
    console.log(sel.selectionText); 
}); 
+1

謝謝,但Google Docs阻止了此方法 - 而不是瀏覽器用戶的上下文菜單,請參閱Google文檔的上下文菜單。 –

+0

如果您希望添加禁用Google文檔菜單的Google文檔菜單項,即禁用此菜單並允許本機。 –