如何在 manifiest v3 中使用新的 insertCSS 和 removeCSS

how to use the new insertCSS and removeCSS in manifiest v3

如何使用 manifiest v3 中的新插入CSS 和删除CSS? 文档对我没有帮助,也没有给出一些例子。

我有一个 CSS 文件,我想将其插入页面并删除它

代码是这样的:

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 } }); // i know it is wrong syntax
    console.log('rtl');
  } else {
    chrome.scripting.removeCSS({ injection: { css } }); // i know it is wrong syntax
    console.log('ltr');
  }
});

错误日志:

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)

我解决了!

使用 insertCSS 的正确语法是:

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

并获得 tab 使函数成为异步函数并使用:

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

代码

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-rtl.css'],
    });
    console.log('ltr');
  }
});