我正在编写一个 Chrome 扩展程序,用于捕获用户文本选择并将所选文本发送到 Google 搜索。
list .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();
此代码适用于网页中的选择(例如 Gmail、Facebook、新闻。)
我还希望能够获得 PDF 和 Google 文档(在浏览器中查看)的选择。
在这些情况下:window.getSelection
返回空字符串...
有人知道怎么做吗?
最佳答案
Google Docs 文档并没有真正遵循从扩展访问文本的正常方式。 出于这个原因,我创建了一个工具来使用 Google 文档,可以在 here 中找到它。
这应该使您能够:
//contentScript.js
var googleDocument = googleDocsUtil.getGoogleDocument();
console.log("The selected text is: " + googleDocument.selectedText);
关于javascript - 在 Google 文档中捕获文本选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41419141/