您不能仅使用清单来执行此操作,您必须以编程方式注入 CSS。
参考:Chrome,“匹配模式和球体”
几个问题,从大到小:
解决方案:
- 为您的 CSS 使用类,不要直接更改元素 CSS。这是为了方便切换。
- 以编程方式注入 CSS。
- 监听
hashchange
事件以了解何时从目标元素中删除新类。
这是一个示例扩展:
清单.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"]
}
拦截器.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");
}
}
}