Guide on utilizing the latest insertCSS and removeCSS features in manifest version 3

Need help with using the new insertCSS and removeCSS in manifest v3. The documentation is not very clear and lacks examples.

I have a CSS file that I need to inject into a page and then remove it.

The code looks something like this:

background.js

document.getElementById('chat').addEventListener('change', (e) => {
  var chat = e.path[0].value;
  // inject css file
  let css = document.createElement('link');
  css.rel = 'stylesheet';
  css.type = 'text/css';
  css.href = 'css/chat-rtl.css';

  if (chat == 'rtl') {
    chrome.scripting.insertCSS({ injection: { css } }); 
    console.log('rtl');
  } else {
    chrome.scripting.removeCSS({ injection: { css } }); 
    console.log('ltr');
  }
});

Error Log:

Uncaught TypeError: Error in invocation of scripting.removeCSS(scripting.CSSInjection injection, optional function callback): Error at parameter 'injection': Unexpected property: 'injection'. at HTMLSelectElement. (background.js:10:22)

Answer №1

I successfully resolved the issue!

The correct syntax for using insertCSS is as follows:

chrome.scripting.insertCSS({
  target: { tabId: tab.id },
  files: ['css/chat-rtl.css'],
});

To obtain the tab, ensure the function is asynchronous and use:

const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

code

document.getElementById('chat').addEventListener('change', async (e) => {
  var chat = e.path[0].value;
  // inject css file

  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

  if (chat == 'rtl') {
    chrome.scripting.insertCSS({
      target: { tabId: tab.id },
      files: ['css/chat-rtl.css'],
    });
    console.log('rtl');
  } else {
    chrome.scripting.removeCSS({
      target: { tabId: tab.id },
      files: ['css/chat-ltr.css'],
    });
    console.log('ltr');
  }
});

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

Issue with implementing LocomotiveScroll on a sticky element

Working on a personal project, I have been experimenting with Nextjs and locomotive-scroll. I am attempting to use position:sticky; along with data-scroll-sticky, but unfortunately the desired functionality is not working as expected. Here is the code snip ...

Display a message stating "No data available" using HighCharts Angular when the data series is empty

My Angular app utilizes Highchart for data visualization. One of the requirements is to display a message within the Highchart if the API returns an empty data set. I attempted a solution, but unfortunately, the message does not appear in the Highchart a ...

Change HTML canvas data into Angular form data before sending it to the Laravel backend

My JavaScript code to convert a data URL to blob and send it as a form request is: var canv = document.getElementById("mainCanvas"); var dataURL = canv.toDataURL('image/jpg'); documentData = {"image": dataURLtoBlob(dataURL), "gameName": "empero ...

Delving Into the Mysteries of Bootstrap Modal Fading

After updating our Bootstrap plugins file to version 2.2.1, I encountered an issue with adding the 'fade' class to modals. Previously, we had been using data-* api references for modals but decided to switch over. However, when I tried to incorpo ...

Utilize the match() method in JavaScript to target and extract a whole paragraph

I am attempting to extract an entire paragraph from a text file using JavaScript and then display it in an HTML element. Despite reading numerous posts and articles, I have been unable to find the correct regex formula. Here is an excerpt from the text fil ...

Is there a way for me to add a clickable link within a tooltip?

In my title, I want to insert a clickable link like 'Link' or 'a'. The title is ready for any string you input. <MaterialSwitch title={CLICKABLE STRING HERE} /> ...

The background image is trapping my text and preventing it from moving forward

As a beginner developer embarking on my first web page project, I've encountered a challenge. The text I inserted into a flexbox refuses to align beneath the image. .title { text-align: center; width: 500px; margin-left: auto; margin-right: a ...

A helpful guide on pulling information from a MySQL database and displaying it in a chart

Struggling to display a pie chart using chart.js? I've spent hours trying to figure it out with no success. If anyone has some insight, please help! I have data on various companies in my database and I need to calculate the total sales for each comp ...

Unable to showcase JavaScript outcome on the HTML page

I have been working on creating a JavaScript function to calculate the Highest Common Factor (HCF). While testing my code in the VS Code console, the correct value is displayed. However, I'm encountering an issue when trying to display the result on t ...

The MaskedInput text does not appear properly when it is passed through the props

Currently, I am facing an issue with a Material UI OutlinedInput along with the MaskedInput component from react-text-mask. Everything works fine when I input text initially and the element is not in focus. However, upon closing and reopening the Dialog wi ...

Tips for integrating JQuery into a JavaScript file seamlessly without causing conflicts

Similar Question: Dynamically Including jQuery using JavaScript if it's not already present I am currently working on a project that requires users to embed a piece of javascript code on their websites, similar to Google Analytics. My main concer ...

The mat-pagination component's mat-select feature is displaying unusual behavior

In a recent project I have created, users need to perform CRUD operations and view the output in a table. Everything is functioning properly, however, there are instances where the "mat-select" within the "mat-paginator" starts behaving strangely. This iss ...

Passing a variable from Twig to VueJS in Symfony 2.8 and VueJS 2: A beginner's guide

My Symfony 2.8 application now includes VueJs 2 as the front-end framework for added flexibility. Although my application is not single page, I utilize Symfony controllers to render views which are all enclosed in a base Twig layout: <!DOCTYPE html> ...

Navigating through the fetch API request when using express js

I'm looking to use the fetch API to send requests and have those requests handled by Express JS. In my setup, I've put together server.js (Express JS), index.html (home page), and signin.html (sign-in page). index.html <!DOCTYPE html> < ...

Create a focal point by placing an image in the center of a frame

How can an image be placed and styled within a div of arbitrary aspect ratio to ensure it is inscribed and centered, while maintaining its position when the frame is scaled? Ensure the image is both inscribed and centered Set dimensions and position usin ...

I need either XPATH or CSS to target a specific checkbox within a list of checkboxes wrapped in span tags

I'm trying to find the XPATH or CSS locator for a checkbox in an HTML span tag that has a label with specific text, like "Allow gender mismatch". I can locate the label using XPATH, but I'm not sure how to target the input tag so I can click on t ...

Z-order for ClockPicker

Within my application, I've implemented a pop-up for inputting event data. One of the fields within this pop-up is for setting the time using the DateTimePicker from MUI. <Popup width={600} height={600} ...

Showing a picture in Angular from a stored image on a node.js server

I'm curious about security measures. Let's say I've uploaded an image of an animal to the server, such as 1545419953137bear.jpg, which is stored in my backend uploads folder along with other images. On the frontend, I use an img element wit ...

Using a javascript variable in php within the Laravel framework

I am trying to retrieve an id from a button for use in my ajax request. Below is the code snippet for the button: <form> <div class="form-group"> <button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delet ...

Trying to align a Material UI button to the right within a grid item

I'm attempting to right float the button below using material-ui, but I'm unsure of how to achieve this: <Grid item xs={2}> <Button variant="contained" color="secondary&quo ...