I'm building a chrome extension that takes some text the user selects in a web page and then displays it in a popup when a button is clicked. I'm using chrome.runtime API to do this.
But when chrome.runtime.sendMessage
executes I get an undefined response which results in the following error: TypeError: Cannot read property 'data' of undefined
.
The code:
function pasteSelection() {
chrome.runtime.sendMessage( {"method": "getSelection"}, function(response) {
var text = document.getElementById('text');
text.innerHTML = response.data;
});
}
window.onload = function() {
document.getElementById("myButton").addEventListener("click", pasteSelection);
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getSelection")
sendResponse({"data": window.getSelection().toString()});
else
sendResponse({});
});
I was trying to follow the instructions of this answer. Some of the methods the author uses here are deprecated.
UPDATE:
I've separated the code in two files and made some minor changes, and I'm showing my manifest.json file as well.
popup.js
function pasteSelection() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var currTab = tabs[0];
var tab_id = currTab.id;
chrome.tabs.sendMessage(tab_id, {method: "getSelection"}, function(response) {
var text = document.getElementById('text');
text.innerHTML = response.data;
});
});
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById("myButton").addEventListener("click", pasteSelection);
});
selection.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message.method == "getSelection")
sendResponse({data: window.getSelection().toString()});
else
sendResponse( {} );
return true;
});
manifest.json
{
"manifest_version": 2,
"name": "Code snippets",
"description": "Extension that enables users to save and tag code snippets and easily navigate through them",
"version": "1.0",
"browser_action": {
"default_title": "Code Snippets",
"default_popup": "interface.html"
},
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["selection.js"]
}
],
"permissions": [
"tabs"
]
}