如果userAgent是GoogleBot,我想执行一个函数

问题描述 投票:0回答:2

如果它是搜寻器,我正在尝试执行一些代码。特别是Googlebot。这就是我的做法,但是我觉得有一种更清洁的方法。

我看到了一些包含正则表达式解决方案的帖子,但答案没有解释。我不使用我不理解的代码。

let agent = window.navigator.userAgent.indexOf("Googlebot") != -1;
if(agent) {
//DO Code
}  

预先感谢朋友。

javascript user-agent
2个回答
0
投票

正确的做法是-

const isGooglebot = window.navigator.userAgent.includes("Googlebot");

if (isGooglebot) {
  // some code
}

说明

我们正在访问userAgent对象下navigator对象下的window属性,并将返回值分配给一个常量变量。

此窗口对象和属性的层次结构在所有浏览器中都是一致的。

来自MDN-

User-Agent请求标头是一个特征字符串,可让服务器和网络对等方标识请求用户代理的应用程序,操作系统,供应商和/或版本

然后我们使用String.prototype.includes,这是一种用于确定某个字符串中是否包含一段文本的方法。

此外,String.prototype.contains也已弃用。 FireFox和MooTools之间存在命名冲突。containswas removed in FireFox 48

优选使用includes,因为使用containsindexOf


-1
投票
let googlebot = window.navigator.userAgent.contains("Googlebot");
if(googlebot) {
//DO Code
} 
© www.soinside.com 2019 - 2024. All rights reserved.