I have a simple Chrome Extension, code below. When a button in my popup is clicked I want to copy the selected text from the users browser tab.
Problem: all the responses back from my Content Script selection.js are undefinied
Any help would be greatly appreciated :)
manifest.json
{
"manifest_version": 2,
"name": "Selected Text",
"description": "copying your highlighted text",
"version": "0.1",
"browser_action": {
"default_title": "Selected Text",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"<all_urls>"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["selection.js"],
"run_at": "document_start",
"all_frames": true
}
]
}
popup.html
<!doctype html>
<html>
<head>
<title>Selected Text</title>
<script src="popup.js"></script>
</head>
<body>
<h1>Selected Text</h1>
<p id="text">Not Selected</p>
<button id="checkPage">Copy Highlighted Text!</button>
</body>
</html>
popup.js
function getSelectedText() {
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.sendRequest(tab.id, {method: "getSelection"}, function(response) {
// PROBLEM: response is always undefined
var text = response.data;
document.getElementById("text").innerHTML = text;
});
});
};
document.addEventListener('DOMContentLoaded', function() {
var checkPageButton = document.getElementById('checkPage');
checkPageButton.addEventListener('click', function() {
getSelectedText();
}, false);
}, false);
selection.js
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse({}); // snub them.
});
sendRequest
andgetSelected
methods with the modernsendMessage
andquery({active: true, currentWindow: true}, ...
(see chrome.tabs API). You may also want to use the recommendedchrome.runtime
instead ofchrome.extension
– wOxxOm