我正在撰写Chrome扩展程序,我需要从网页上阅读所选文字。以下是我的代码的相关部分:
的manifest.json :
{
"name": "XXX",
"version": "1.0",
"manifest_version": 2,
"description": "XXX",
"icons": {
"128": "images/icon.png"
},
"browser_action": {
"default_icon": "images/icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"tabs"
],
"content_scripts": [{
"matches": ["<all_urls>"],
"js": [ "content_script.js" ],
"run_at": "document_start",
"all_frames": true
}],
}
content_script.js :
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection") {
var sel = window.getSelection();
var selectedText = sel.toString();
console.log("getSelection requested, sending \""+selectedText+"\"")
sendResponse({data: selectedText})
}
});
popup.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
</body>
</html>
popup.js :
chrome.tabs.query( {active:true, windowId: chrome.windows.WINDOW_ID_CURRENT},
function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {method: "getSelection"},
function(response){
console.log("getSelection method returned - " + response.data)
});
});
这适用于像维基百科这样的简单页面;但它不适用于具有大量动态内容的网页,例如cnn.com
下面的控制台日志显示了一次点击扩展程序时生成的消息。它们似乎表明消息被发送到页面中的多个元素或多次被接收(尽管在popup.js中它只被发送一次)。一些回归&#34;有些人会返回正确的选择。
getSelection requested, sending "" selection.js:26
getSelection requested, sending "" selection.js:26
getSelection requested, sending "" selection.js:26
getSelection requested, sending "" selection.js:26
getSelection requested, sending "" selection.js:26
getSelection requested, sending "" selection.js:26
getSelection requested, sending "Trump" selection.js:26
getSelection requested, sending "" selection.js:26
我想弄明白: