You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展CSS切换异常:样式仅生效于弹窗/站点切换失效

问题描述
  • 按教程修改google.com及其搜索结果页的CSS后,切换功能出现异常:保留google匹配代码时,切换功能完全失效;注释该代码后,CSS仅对扩展弹窗生效,无法作用于目标站点。
  • 尝试调整函数顺序、嵌套CSS生效函数均无明显效果;添加chrome.storage.sync仅能保存切换状态,无法同步站点的CSS样式,且切换状态恢复后必须手动开关一次才会触发样式变更。
  • 当前代码的切换函数存在null参数问题,尝试学习extension api的insertcss用法但暂时没掌握。
当前扩展JS代码
//Get the URL
const site = window.location.hostname

//Function to add custom CSS
let customStyle;
const Add_Custom_Style = (css) => {
  customStyle = document.createElement("style")
  document.head.appendChild(customStyle).innerHTML = css;
}
const Remove_Custom_Style = () => customStyle.remove();

//Function to change CSS
function changeCSS(){
    //Function for Google.com
    if (site.includes("google.com")){/*Commenting this line out allows the toggle to take effect.
                                       To have the site-level effect take place, leave this line as is
                                       and comment out the "function changeCSS()" line above it and all    
                                       code below the css string brackets.*/
        Add_Custom_Style(`
        @import url('https://fonts.googleapis.com/css2?family=Advent+Pro:wght@300&display=swap');

        * {
            font-family: 'Advent Pro', sans-serif !important; 
            color: #fff !important;
        }

        a {
            color: #b0dff4 !important; 
            font-size: 140%;
        }

        h1, h2, h3, h4, h5, h6 {
            color: #b0dff4 !important;
        }
        `)
    }
}

//***Toggle function on off
window.onload = function() {
    document.getElementById("togBtn").addEventListener("change", function() {
        if(document.getElementById("togBtn").checked){
            changeCSS(site);
        }
        else{
            customStyle.remove();
        }
    });
};

// Saves options to chrome.storage
function saveOptions() {
    var cssOn = document.getElementById("togBtn").checked;
    chrome.storage.sync.set({
  cssOn: cssOn
}, function() {
  // Update status to let user know options were saved.
  var status = document.getElementById('status');
  status.textContent = 'Options saved.';
  setTimeout(function() {
    status.textContent = '';
  }, 750);
    });
}

  // Restores select box and checkbox state using the preferences
  // stored in chrome.storage.
  function restoreOptions() {
      // Use default value
    chrome.storage.sync.get({
      cssOn: true
    }, function(items) {
        document.getElementById("togBtn").checked = items.cssOn;
    });
  }
  document.addEventListener('DOMContentLoaded', restoreOptions);
  document.getElementById('save').addEventListener('click',
      saveOptions);

内容的提问来源于stack exchange,提问作者itsfrxst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 12:51:56