Chrome 扩展:Manifest 版本 3 上的 CSS 注入

lia*_*mhp 8 javascript css google-chrome google-chrome-extension manifest.json

我正在尝试从 chrome 扩展将 CSS 代码注入到活动选项卡中,但到目前为止我在网上看到的任何内容都对我不起作用。我对这一切都很陌生,所以如果我的问题有点天真并且我只是错过了一些基本的东西,我很抱歉。这是我到目前为止所想到的:

function inject_1(){
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    css = 'body { background-color = "red" !important; }';
    chrome.scripting.insertCSS(
     {
       target: {tabId: tabs[0].id},
       css: css,
     }, function() {
       if (chrome.runtime.lastError) {
         message.innerText = 'There was an error injecting css : \n' + chrome.runtime.lastError.message;
       }
     });
  });
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的第二种方法:

function inject_2(){
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.scripting.executeScript(
     {
       target: {tabId: tabs[0].id},
       files: ["inject.css"],
     }, function() {
       if (chrome.runtime.lastError) {
         message.innerText = 'There was an error injecting css : \n' + chrome.runtime.lastError.message;
       }
     });
  });
}
Run Code Online (Sandbox Code Playgroud)

这两个函数都不会返回错误消息,但它们也根本不会更改网页。我将非常感谢任何对此的帮助(修改我的代码或尝试一些全新的东西)。谢谢。

Alp*_*ine 14

有点晚了,但我把它用于个人项目;也许尝试一些达到以下效果的东西:

...
    chrome.scripting.insertCSS({
        target: { tabId: tabs.id },
        files: ["inject.css"]
    });
...
Run Code Online (Sandbox Code Playgroud)

您可以为 insertCSS 指定文件,就像在辅助方法中为 executeScript 所做的那样。


Vul*_*tyn 3

我只需将 .css 文件添加到扩展名中。

样式.css

body {
  background-color: red !important;
}
Run Code Online (Sandbox Code Playgroud)

然后将其添加到content_scriptsmanifest.json中,例如

...
"content_scripts": [
  {
    ...,
    "css": ["style.css"]
  }
Run Code Online (Sandbox Code Playgroud)

我也不确定你是否'body { background-color = "red" !important; }'不应该'body { background-color:red !important; }'