将CSS文件注入限制为仅一个网站主页(没有超过域的内容)

Limit CSS file inject to only a website homepage (nothing past the domain)

本文关键字:主页 网站 一个 注入 CSS 文件      更新时间:2023-09-26

我正在创建一个简单的Chrome扩展,该扩展使用内容脚本仅在谷歌主页上屏蔽黑条。但我不希望它在用户搜索后屏蔽黑条。

也就是说,我希望它适用于这个地址:

http://www.google.com

但不是这个地址:

http://www.google.com/search-terms-here/

在manifest.json中,我一直在使用这个来阻止条:

  "content_scripts": [
   {
    "matches": ["http://google.com"],
    "css": ["blocker.css"]
   }

但是使用"matches": ["http://google.com"]是不起作用的。有人知道我应该在"matches"下使用什么地址才能得到想要的结果吗?

您不能单独使用清单来执行此操作,必须以编程方式注入CSS。

参考:Chrome,"匹配图案和球体"

从大到小的几个问题:

  • Chrome仍然存在一个错误,CSS注入会忽略exclude_globsexclude_matches
  • 谷歌大量使用标签和查询参数,而matchesexclude_matches不适用于这些
  • 谷歌大量使用AJAX,所以"新"页面不会新鲜加载。这意味着您必须能够关闭您添加的任何CSS
  • 谷歌使用www.。您的匹配项必须为:"http://www.google.com/"
  • "http://google.com"match无效。它将给出错误:

    无法从"{没关系!}"加载扩展。"content_scripts[0]。matches[0]"的值无效:路径为空


解决方案:

  1. 使用CSS的类,不要直接更改CSS元素。这是为了便于切换
  2. 以编程方式注入CSS
  3. 监听hashchange事件,了解何时从目标元素中删除新类

下面是一个扩展示例:

manifest.json:

{
    "manifest_version": 2,
    "content_scripts":  [ {
        "js":               [ "CSS_handler.js" ],
        "matches":          [ "http://www.google.com/", "https://www.google.com/" ],
        "exclude_globs":    [ "http://www.google.com/#*", "https://www.google.com/#*" ]
    } ],
    "name":         "AJAX aware, CSS injection switching",
    "description":  "From SO 17395877.  Inject at home page, not 'results' pages. css property fires incorrectly due to bug. Target pages (Google) load 'new' pages via AJAX.",
    "version":      "1",
    "web_accessible_resources": ["blocker.css"]
}


blocker.css:

.mycsHide {
    display: none !important;
}


CSS_handler.js:

var link    = document.createElement ("link");
link.href   = chrome.extension.getURL ("blocker.css");
link.type   = "text/css";
link.rel    = "stylesheet";
document.head.appendChild (link);
//-- Global vars
var cssSelectorsToHide  = [
    "#gbz",
    "#gbx3"
];
var hideElems           = true;

//-- Initial run on cold start or full reload.
fireOnNewPage ();
//-- Run on "new" ajax pages.
window.addEventListener ("hashchange", fireOnNewPage,  false);
function fireOnNewPage () {
    /*-- Only hide if there is no hash or URL params.
        The manifest makes sure there is no path.
    */
    hideElems = ! (location.hash  ||  location.search);
    cssSelectorsToHide.forEach (setElemVisibility);
}
function setElemVisibility (selector) {
    var nodes   = document.querySelectorAll (selector);
    //-- Add or remove our special CSS class...
    for (var J = nodes.length - 1;  J >= 0;  --J) {
        if (hideElems) {
            nodes[J].classList.add ("mycsHide");
        }
        else {
            nodes[J].classList.remove ("mycsHide");
        }
    }
}