今天在工作中,调试网页代码时, 偶然遇到下面一段代码 ,这是电脑管家的网页广告过滤的js代码
/*
电脑管家chrome 广告过滤
*/
var GJAD_CS =
{
elemhideElt : null,
setElemhideCSSRules: function (selectors)
{
if (GJAD_CS.elemhideElt && GJAD_CS.elemhideElt.parentNode)
GJAD_CS.elemhideElt.parentNode.removeChild(GJAD_CS.elemhideElt);
if (!selectors)
return;
GJAD_CS.elemhideElt = document.createElement("style");
GJAD_CS.elemhideElt.setAttribute("type", "text/css");
// Try to insert the style into the <head> tag, inserting directly under the
// document root breaks dev tools functionality:
// http://code.google.com/p/chromium/issues/detail?id=178109
(document.head || document.documentElement).appendChild(GJAD_CS.elemhideElt);
var elt = GJAD_CS.elemhideElt; // Use a local variable to avoid racing conditions
function setRules()
{
if (!elt.sheet)
{
// Stylesheet didn't initialize yet, wait a little longer
window.setTimeout(setRules, 0);
return;
}
elt.innerText = selectors;
}
setRules();
},
QueryCss: function()
{
var query_param={
"url": window.location.href
};
chrome.extension.sendRequest({cmd: "query_css", json: JSON.stringify(query_param)}, function(response)
{
if (response && response.selectors != "")
{
GJAD_CS.setElemhideCSSRules(response.selectors);
}
});
},
};
/*
电脑管家chrome 广告过滤
*/
var GJAD_CS =
{
elemhideElt : null,
setElemhideCSSRules: function (selectors)
{
if (GJAD_CS.elemhideElt && GJAD_CS.elemhideElt.parentNode)
GJAD_CS.elemhideElt.parentNode.removeChild(GJAD_CS.elemhideElt);
if (!selectors)
return;
GJAD_CS.elemhideElt = document.createElement("style");
GJAD_CS.elemhideElt.setAttribute("type", "text/css");
// Try to insert the style into the <head> tag, inserting directly under the
// document root breaks dev tools functionality:
// http://code.google.com/p/chromium/issues/detail?id=178109
(document.head || document.documentElement).appendChild(GJAD_CS.elemhideElt);
var elt = GJAD_CS.elemhideElt; // Use a local variable to avoid racing conditions
function setRules()
{
if (!elt.sheet)
{
// Stylesheet didn't initialize yet, wait a little longer
window.setTimeout(setRules, 0);
return;
}
elt.innerText = selectors;
}
setRules();
},
QueryCss: function()
{
var query_param={
"url": window.location.href
};
chrome.extension.sendRequest({cmd: "query_css", json: JSON.stringify(query_param)}, function(response)
{
if (response && response.selectors != "")
{
GJAD_CS.setElemhideCSSRules(response.selectors);
}
});
},
};
GJAD_CS.QueryCss();
其中document.head || document.documentElement这一块不是很理解 网上查了下
如果网页是<html>开头 使用 document.head,
类似于<!DOCTYPE><html></html> ,使用 document.documentElement
在 IE 和 Firefox 中均是如此。
为了兼容,不管有没有 DTD,可以使用上面的代码: