所以我正在尝试创建一个switch语句,当页面是某个URL时,会在文档头中嵌入以下代码:
<meta name="robots" content="noindex">
目前,我看起来像这样:
switch(document.URL){
case "url/i/want/to/noindex":
var m = document.createElement('meta');
m.name = 'robots';
m.content = 'noindex';
document.head.appendChild(m);
break;
...
}
然而,它似乎没有按预期工作。我是不是错了?
答案 0 :(得分:0)
大多数搜索引擎都会忽略这一点,因为他们正在抓取HTML而不是后期处理的DOM信息。那就是说,你要找的更像是这样:
if (window.location.href.indexOf("url/i/want/to/noindex") >= 0) {
var m = document.createElement('meta');
m.name = 'robots';
m.content = 'noindex';
document.head.appendChild(m);
}
document.URL和window.location.href将返回包含域名,协议,端口等的URL路径。因此,您只想搜索您的URL路径。您可以提出许多聪明的方法,包括正则表达式,以匹配模式或过滤掉URL路径之前的内容。您也可以使用window.location.pathname,但我不确定哪些浏览器支持它。
缺点是switch语句中的测试条件不匹配。例如,本页面上的document.URL是:
http://stackoverflow.com/questions/37977060/dynamically-creating-noindex-meta-tags-for-certain-urls/37977662#37977662