Here is a full working solution for you.
---manifest.json---
{
"name": "Popup to Content",
"version": "1.0.0",
"manifest_version": 3,
"content_scripts": [{
"matches": ["https://*/*"],
"js": ["content_script.js"]
}],
"permissions": [],
"action": {
"default_popup": "popup.html"
}
}
---popup.html---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="example"></button>
<script src="popup.js"></script>
</body>
</html>
---popup.js---
const exampleButton = document.querySelector("#example")
exampleButton.addEventListener("click", function(){
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
const activeTabId = tabs[0].id;
chrome.tabs.sendMessage(activeTabId, {"message": "This worked!"});
});
});
---content_script.js---
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
// receive message here...
console.log(request.message)
});
This will get the message to log in the console of the page instead of the popup window.
It works by querying the active tab (i.e. the one the user has open) and sends a message to that tab. The content script has a message listener that receives the message and once the message is received, logs it to the console of the active tab.
Please make sure you refresh the page after refreshing the extension or the page will not have the content script inserted and will therefore not log the message.