首页 > 解决方案 > Chrome 扩展:Manifest 版本 3 上的 CSS 注入

问题描述

我正在尝试将 CSS 代码从 chrome 扩展程序注入到活动选项卡中,但到目前为止我在网上看到的任何内容都没有为我工作。我对这一切都很陌生,所以如果我的问题有点天真,我只是缺少一些基本的东西,我深表歉意。到目前为止,这是我想出的:

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;
       }
     });
  });
}

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

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;
       }
     });
  });
}

这两个函数都不会返回错误消息,但它们也根本不会更改网页。我将不胜感激任何帮助(我的代码的返工或全新的尝试)。谢谢。

标签: javascriptcssgoogle-chromegoogle-chrome-extensionmanifest.json

解决方案


有点晚了,但我把它用于个人项目;也许尝试一些效果:

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

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


推荐阅读