I am writing a Chrome extension for which I need to read the selected text from the webpage. Here are the relevant pieces of my code:
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)
});
});
This works perfectly on simple pages like Wikipedia; however it does not work on pages with lot of dynamic content like say cnn.com
The console log below shows messages generated on one click of extension. They seem to indicate that message is sent to multiple elements in the page or its received multiple times (though in popup.js its only sent once). Some return " whereas some return the correct selection.
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
I am trying to figure out:
- What's going on here?
- What's the right way to get selected text?