I'm currently working on a project involving a google chrome extension where the content.js script sends a message to popup.js. I'm also attempting to take some text from content.js and display it in popup.js. Here is my entire code:
Here's my manifest file, manifest.json:
{
"name": "Hoko's Extension",
"description": "My Extension",
"version": "1.0",
"manifest_version": 3,
"action": {
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["https://*/*", "http://*/*"],
"js": ["content-script.js"]
}
],
"background": {
"service_worker": "background.js"
},
"permissions": [
"tabs",
"activeTab"
]
}
This is the popup displayed when you click the icon in the toolbar, popup.html:
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>This is the Popup</h1>
<p id="extensionpopupcontent"></p>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>
Below is my content script named content-script.js:
function injectScript(file_path, tag) {
var node = document.getElementsByTagName(tag)[0];
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', file_path);
node.appendChild(script);
}
injectScript(chrome.runtime.getURL('inject.js'), 'body');
chrome.runtime.sendMessage(document.getElementsByTagName('title')[0].innerText);
In background.js, I am receiving messages from content-script.js.
chrome.runtime.onMessage.addListener(function(response, sender, sendResponse) {
function onMessage(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello") {
sendResponse({farewell: "goodbye"});
}
}
})
In popup.js, I receive messages from background.js and output the code from content-script.js.
window.addEventListener('DOMContentLoaded', () => {
let bg = chrome.extension.getBackgroundPage();
chrome.tabs.query({active: true, currentWindow: true}, tabs => {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
document.getElementById('extensionpopupcontent').innerHTML = response;
});
});
});
I believe I need to include this script inject.js:
function click() {
return document.getElementsByTagName('title')[0].innerText;
}
click();