如果它是搜寻器,我正在尝试执行一些代码。特别是Googlebot。这就是我的做法,但是我觉得有一种更清洁的方法。
我看到了一些包含正则表达式解决方案的帖子,但答案没有解释。我不使用我不理解的代码。
let agent = window.navigator.userAgent.indexOf("Googlebot") != -1;
if(agent) {
//DO Code
}
预先感谢朋友。
正确的做法是-
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之间存在命名冲突。contains
was removed in FireFox 48。
优选使用includes
,因为使用contains
或indexOf
let googlebot = window.navigator.userAgent.contains("Googlebot");
if(googlebot) {
//DO Code
}