Reputation: 97
I am trying to make the selected text change into the p element of id 'ext' in popup.html and popup.js when I click the buy button but I seem to get undefined.
This is my manifest.json
{
"name": "hoko's ext",
"description": "my ext",
"version": "1.0",
"manifest_version": 3,
"action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
],
"background": {
"service-worker": "background.js"
},
"content_scripts": [
{
"matches": ["https://*/*"],
"js": ["content.js"]
}
]
}
This is my popup.html
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>I am the popup</h1>
<button id="btn">Buy</button>
<p id="ext">Hello</p>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
This is my background.js service worker
chrome.runtime.onMessage.addListener(receiver);
window.word = 'Hello';
function receiver(request, sender, sendResponse) {
if (request.text === 'Hello') {
sendResponse(request);
}}
This is my content script. The error is at content.js:13 (anonymous function)
console.log('yo');
window.addEventListener('mouseup', word);
function word() {
console.log('word selected');
let select = window.getSelection().toString();
console.log(select);
if (select.length > 0) {
let message = {
text: select
};
chrome.runtime.sendMessage(message);
}
}
And lastly this is my popup.js script
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
chrome.runtime.sendMessage({text: "Hello"}, function(response) {
document.getElementById('ext').innerHTML = response;
}
);
})
Upvotes: 3
Views: 9503
Reputation: 1
service_worker instead of service-worker in the manifest.js was the problem
Upvotes: 0
Reputation: 97
Okay, I just had to replace - with _ in service-worker in manifest.json and everything worked perfectly! I edited my code however in background.js, content.js and popup.js.
manifest.json
{
"name": "hoko's ext",
"description": "my ext",
"version": "1.0",
"manifest_version": 3,
"action": {
"default_popup": "popup.html"
},
"permissions": [
"activeTab"
],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["https://*/*"],
"js": ["content.js"]
}
]
}
Upvotes: 1
Reputation: 21
Your backgroundScript receiver isn't doing anything when it gets the message (selected word) from the contentScript.
//backgroundScript.js
var selectedWord;
chrome.runtime.onMessage.addListener(
function(request,sender,sendResponse){
if(request.text === 'Hello'){
//send saveWord variable to popup
sendResponse({word:selectedWord});
} else {
//save request.text
selectedWord = request.text
}
return true; //for async reasons i dont get either
}
);
//popupScript.js
... document.getElementById('ext').innerHTML = response.word;
I hope this helps?
Upvotes: 1