so I am building a function that will change the background color of a website I am browsing, but when I click on the change color button, it only changes the background color of the popup.html, not the website I am browsing.
Here is the Manifest File
{
"manifest_version": 3,
"name": "Change Body Color",
"version": "1.0",
"description": "Change the background color of the body tag.",
"permissions": ["activeTab"],
"action": { "default_popup": "popup.html" },
"content_scripts": [
{ "matches": ["<all_urls>"],
"js": ["content.js"] } ] }
content.js
window.addEventListener('load', function() { let myBtn = document.getElementById('changeColorBtn'); if (myBtn) { // Check if button exists (optional) function red() { document.body.style.backgroundColor = "red"; } myBtn.addEventListener('click', red); } else { console.error("Button element not found!"); } });
popup.html
<!DOCTYPE html>
<html>
<head>
<title>Change Color</title>
<script src="content.js"></script>
</head>
<body>
<button id="changeColorBtn">Change Color</button>
</body>
</html>
I tried everything. I changed the content.js to background.js and followed many tutorials, but nothing helped. I came here to see if anyone could help me.
2
Answers
You have a confusion about the difference between
Popup Scripts
, these are the scripts run in the context of your extension’s popup which In your case,popup.html
has its own context, separate from the webpage you are browsing.Content Scripts
, these are scripts injected in the page you are browser, which can interact with page DOM.Background Scripts
, these are scripts where you maintain the long-running logic and communication betweenPopup Scrupts
andContent Scripts
Here the issue is tring to use
content.js
for both the popup and as a content script, so you need to seperate the concern between thepopup
andcontent
script.First you need to modify
popup.html
to create apopup
script, which will send message to thecontent
script with the functionality required to change the color.popup.html
popup.js
Make sure that you give permissions for scripting with
"permissions": ["activeTab", "scripting"]
and link thepopup.js
with"default_popup": "popup.html"
This line should indeed change your own program’s background color like you say…
But to change that of the document inside a window/frame you need to change it to…