[英]window.getSelection returning undefined or null
这可能是一个非常初学者的问题,但是我要拔掉头发,因为我无法弄清楚自己在做什么错。 此时,我要做的就是将选定的文本打印在警报或控制台中(用于测试)。 我确定.toString()
方法已添加到window.getSelection().
返回的对象中window.getSelection().
不管我做什么,控制台和警报都显示为空白。 谁能解释为什么?
我正在本地Chrome扩展程序中执行此操作。
的manifest.json
{
"manifest_version": 2,
"name":"Testing",
"version": "0.1",
"icons": {
"48":"48.png"
},
"background": {
"scripts": [ "background.js" ]
},
"permissions":[ "tabs" ],
"browser_action": {
"default_icon": { "19":"img19.png" }
}
}
JavaScript的
chrome.browserAction.onClicked.addListener(function(tab) {
var selObj = window.getSelection();
var selectionText = selObj.toString();
alert(selectionText); // displays a blank alert
console.log(selectionText); // adds a blank line in the console
});
我在学。 提前致谢。
经过最近24小时的反复研究之后,我终于有了一个可行的解决方案。 因为我正在访问DOM元素,所以需要注入内容脚本并从后台脚本来回传递信息。 我还向清单中添加了activeTab
权限。
的manifest.json
{
"manifest_version": 2,
"name":"Simple Highlighter",
"version": "1.0",
"icons": {
"19":"img19.png",
"48":"48.png"
},
"content_scripts": [{
// "matches": ["<all_urls>"], only used for testing
"js":["contentscript.js"]
}],
"background": {
"scripts": [ "background.js" ]
},
"permissions":[ "tabs", "activeTab" ],
"description": "Highlight web text and send it to a new Google Doc",
"browser_action": {
"default_icon": { "19":"img19.png" },
"default_title":"Simple Highlighter"
}
}
background.js
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.query({active: true, windowId: chrome.windows.WINDOW_ID_CURRENT}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].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});
}
contentscript.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({});
}
)
显然,这并没有实现我最初打算做的事情。 但是,我有它传递数据,因此接下来我将研究突出显示功能。
参考链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.