I created an extension, where I placed a script into a page markup and performs some actions according to the following article:
var s = document.createElement('script');
s.src = chrome.runtime.getURL('code.js');
s.onload = function() {
this.remove();
};
(document.head || document.documentElement).appendChild(s);
I also displayed a checkbox in "default_popup" which should indicate whether to execute a part of methods in script from "code.js" (web_accessible_resources) or not.
However, I have no idea how to interact between the script from "content_scripts" (which has access to "default_popup") and the script from "web_accessible_resources".
Could you suggest something?
I understand that I can completely replace the "web_accessible_resources" script, but this does not seem to be the best practice.
Thank you.
This is a sample of communication between popup and tab.
manifest.json
{
"name": "content_scripts + popup",
"version": "1.0",
"manifest_version": 3,
"content_scripts": [
{
"js": [
"matches.js"
],
"matches": [
"<all_urls>"
]
}
],
"host_permissions": [
"<all_urls>"
],
"action": {
"default_popup": "popup.html"
}
}
popup.js
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
console.log("Send");
chrome.tabs.sendMessage(tabs[0].id, "message", (response) => {
console.log("Recv response = " + response.title);
document.getElementById("title").innerText = response.title;
});
});
matches.js
console.log("matches.js");
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
console.log("Recv. Send response = " + document.title);
sendResponse({ title: document.title });
return true;
});
popup.html
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
* {
font-size: x-large;
}
</style>
</head>
<body style="min-width:300px">
<div id="title"></div><br>
<script src="popup.js"></script>
</body>
</html>