最终目标:我正在尝试制作一个javascript文件,该文件将隐藏页面上的所有内容,除非该网址包含在黑名单中。
今日目标:使用if语句检查currentLocation
变量是否等于某个网址。如果是这样的代码...如果不这样做代码...
到目前为止我有什么:
var currentLocation = window.location;
if (currentLocation == "https://www.google.com") {
document.documentElement.style = "display:none";
}
答案 0 :(得分:2)
你很亲密。这是更正后的代码。 window.location
是一个对象,您必须在其中一个键上设置条件,例如:
if (window.location.origin === 'https://stacksnippets.net') {
document.documentElement.style.display = 'none';
}

<div>
Something to show
</div>
&#13;
答案 1 :(得分:0)
使用类并将此类添加到document.body
var currentLocation = window.location;
if (currentLocation.trim() === "https://www.google.com") {
document.body.classList.add('hideAll');
}
CSS
.hideAll{
display:none
}
如果css不可用,请使用内联样式
document.body.style.display='none';
答案 2 :(得分:0)
由于您没有ID
或class
,因此您应使用body
标记。您可以使用body
获取getElementsByTagName
代码并将其显示为none
:
var currentHostLocation = window.location.hostname;
if (currentHostLocation == "google.com") {
document.getElementsByTagName("body").style.display = "none";
}
OR
var currentHostLocation = window.location.hostname;
if (currentHostLocation == "google.com") {
document.getElementsByTagName("body").style = "display:none";
}
我相信,即使这应该有效:
document.body.style.display = "none";
答案 3 :(得分:0)
向window.location添加href方法。它以你拥有它的方式重新控制对象,但是使用href它会将href(地址)作为字符串返回
window.location.href
答案 4 :(得分:0)
您应该使用以下代码获取当前hostname
并隐藏所有内容:
var currentHostLocation = window.location.hostname;
alert(currentHostLocation);
if (currentHostLocation == "google.com") {
document.body.style.display='none';
}