Running Content Scripts and CSS styles from Background Page in Chrome Extension - Manifest V3

I'm currently working on developing a chrome extension, and my goal is to have a small circle appear on the screen when the extension is active. I require CSS for this task, and my plan involves setting the background in the manifest file and triggering the content script upon clicking the icon. Right now, I have it set so that the tab URL change activates the feature, but I am still experimenting. Adding the necessary CSS to my content script has proven challenging. I researched and found mention of insertCSS(), but that seems to only accommodate single lines of code, whereas I have much more content to add. Any suggestions or ideas would be greatly appreciated. I've consulted the primary Google documentation and MDN as well.

//BACKGROUND

try {
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        if(changeInfo.status == 'complete') {
            chrome.scripting.executeScript({
                files: ['content-script.js'],
                target: {tabId: tab.id}
            });
        }
    });
} catch (e) {
    console.log(e);
}

//CONTENT-SCRIPT (in another file, wasn't sure how to add it to the question


if (typeof init === 'undefined') {
    const init = function() {
        const injectElement = document.createElement("button");
        injectElement.className = 'button_attempt';
        injectElement.innerHTML = "T";
        document.body.appendChild(injectElement);

    }

    init();
        
}
//CSS


@import url('https://fonts.googleapis.com/css2?family=Prociono&family=Sorts+Mill+Goudy&display=swap');

@font-face {
    font-family: 'Goudy Bookletter 1911';
    font-style: normal;
    font-weight: 400;
    src: url(https://fonts.gstatic.com/s/goudybookletter1911/v13/sykt-z54laciWfKv-kX8krex0jDiD2HbY6IJshzW.woff2) format('woff2');
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212,  U+2215, U+FEFF, U+FFFD;
}


.button_attempt {
      background-image: url(icon.png);
      width: 2.5rem;
      height: 2.5rem;
      font-family: 'Goudy Bookletter 1911';
      font-size: 1.25rem;
      color: white;
      background-color: #A485C7;
      cursor: pointer;
      border: 2px solid #D0B3F1;
      border-radius: 50%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 10;
      /*display: none;*/

      transition: color 0.2s, background-color 0.2s ease-in-out;
}

.button_attempt:hover {
      color: #A485C7;
      background-color: white;
}
//MANIFEST
{

"name" : "Practice",
"version" : "1.0.0",
"manifest_version" : 3,
"background" : {
    "service_worker": "background.js"
},

"permissions" : ["scripting"],

"host_permissions": ["<all_urls>"]

}

Answer №1

It really is quite straightforward :)

  1. Modify the manifest file to resemble something like this.

manifest.json:

{
"name" : "Practice",
"version" : "1.0.0",
"manifest_version" : 3,
"background" : {
    "service_worker": "background.js"
},

"permissions" : ["scripting"],

"host_permissions": ["<all_urls>"]
"content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "css": ["content_style.css"],
      "js": ["content_script.js"],
      "run_at": "document_end"
    }
  ],

}
  1. Call the content_script.js from background.js. You can set up any type of listener for this.

background.js:

chrome.tabs.onUpdated.addListener(function () {
  chrome.tabs.executeScript(null, { file: "content_script.js" });
});
  1. Utilize the content_script.js to make alterations to the DOM. You can apply style classes to DOM elements from the content_style.css or insert new elements according to your needs. Define all additional CSS rules in the content_style.css.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on adjusting the scrollbar color with CSS

Check out my jsfiddle here I am attempting to modify the color of the scrollbar, but unfortunately it is not working as expected. This is the CSS code I am using: .flexcroll { scrollbar-face-color: #367CD2; scrollbar-shadow-color: #FFFFFF; ...

Craft a CSS triangle shape from scratch

Looking at the image of a blue triangle, I am curious about how to recreate it using CSS. Would using a background image be the best approach, or is there a way to achieve this with CSS transforms? I noticed the triangle is on the left side but not on the ...

Frequent occurrence of unexpected 'Assertion failed' messages observed on Apple M1 chip

After making the switch from Windows 10 to Mac OS with the latest Apple M1 Silicon, I embarked on my first project on the Mac. I decided to use homebrew to install both node and yarn: brew install node brew install yarn yarn global add @vue/cli My Vue pro ...

JavaScript and inverted brackets

Why does Javascript allow the use of inverted parentheses in function calls? I'm currently using a Node console on the CLI with Node version 0.10.25. function a(){ return 42 } a() // -> 42 a)( // -> 42. Strange behavior? function b(t){ return ...

Angular: A guide to binding to the required/ngRequired attribute

There is a directive that may or may not be required, and it can be used in two different ways. <my-foo required></my-foo> or <my-foo ng-required="data.value > 10"></my-foo> Even though require and ngRequire are essentially t ...

The React properties continue to update, even when I am not actively utilizing them

I created a project using the create-react-app template. I am facing an issue with importing data from a JSON file and sending it to the Todos component file as props. Although I am not using it as a prop in the Todos file, the todo list updates when I use ...

What is the method for adding line breaks to a JSON file?

I've been developing a Discord bot and I'm currently storing currency values in a json file. The functionality is working smoothly, but the issue I'm facing is that it's adding them to the json file in a single line which makes it diffi ...

positioning a window.confirm dialog box in the center of the screen

I'm currently facing an issue with a dialog box that I have implemented successfully. However, I can't seem to get it centered on the page: <Button variant="danger" onClick={() => { if (window.confirm('Delete character?')) handle ...

Having trouble configuring webpack for CSS Modules? You may be dealing with an invalid configuration object

Encountering an issue while setting up webpack for CSS Modules... An error message is appearing stating that the configuration object is invalid. It seems that the output path specified as "build" is not an absolute path, which is required. Below are ext ...

Using an ASP.NET control along with jQuery within a standalone .js file

I recently created a jQuery voting script that functions perfectly when the code is kept within the header of the page. However, I am interested in transferring it to a separate .js file and simply including this .js file at the top of the page. Strangely, ...

extracting information from a database based on specific search criteria

"_id":{"$id":"61b5eb36029b48135465e766"}, "name":"push-ups","link":"https://google.com", "image":"https://google.com", "gender":["0","1" ...

Eliminate duplicate values in a JSON array using JavaScript

Good evening, I need to filter out duplicate country names from a list retrieved from mongoDB and then populate a select box with the unique country names stored in the "title" field. { "_id": { "$oid": "60885f86f642f81 ...

Display the number of likes without having to refresh the page

On my website, there is a like/unlike post feature. When I click the like button, I want the value of check2 to appear next to the like button without needing to refresh the page. Currently, after clicking like, the data is inserted but only appears after ...

Executing PHP scripts in Javascript to monitor active online users: identifies individuals who are currently not authenticated

I am currently developing a basic admin panel and looking to allow logged in users to view other active users. To achieve this functionality, I have set up a sessions MySQL table containing active session data (logged in users) alongside a PHP file that up ...

Guide to organizing files with custom directory layout in NodeJS

Imagine having multiple files spread across various folders. /parentDir/ |__dirA/ |__file1 |__file2 |... |__dirB/ |__file3 |... |... You want to consolidate them into an archive, with the option of using something like ...

Obtaining rotate3d values using JavaScript / jQuery

When dealing with an element that has a transformation like the following: style="transform: rotate3d(1, 0, 0, -50deg);" I am looking to extract the value -50 using Javascript or jQuery. It's essential for me to get the absolute value, so negative d ...

Updating content on a webpage via AJAX request without altering the original source code

Within the body of our document, referred to as "form.php," we have the following components: At the head section, there is a JavaScript code block: <script> function showUser(str) { if (str == "") { document.getElementById("txtHint").i ...

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...

AngularJS - smooth scrolling with $anchorScroll duration

While going through the AngularJS documentation, I have not been able to determine whether $anchorScroll has a duration or easing option for smoother scrolling to elements. The documentation only shows: $location.hash('bottom'); // call $ancho ...

Tips for creating stylish diagonal backgrounds using Bootstrap 5

Is there a way to achieve diagonal styled backgrounds, like the examples shown below, while using Bootstrap 5 and (s)css? It would be ideal if this could be seamlessly integrated with other Bootstrap background utilities as outlined in the documentation h ...