JavaScript浏览器代理重定向

JavaScript browser agent redirect

本文关键字:重定向 代理 浏览器 JavaScript      更新时间:2023-09-26

如果用户使用iPhone,我在网页标题上有一小段代码可以将用户重定向到另一个页面:

<script type="text/javascript">
if ((navigator.userAgent.indexOf('iPhone') != -1) ||  
(navigator.userAgent.indexOf('iPod') != -1)) {  
document.location = "iPhone.aspx"; }
</script>

有没有一种简单的方法可以"反转"这个代码,这样任何从其他浏览器登录iPhone页面的人都会被重定向回主页?

非常感谢。

简单的解决方案。用此替换现有的。

if(!/(iphone|ipod)/i.test(navigator.userAgent)) {
   window.location = "Desktop.aspx";
}

更新,因为它只适用于iPhone页面。

要反转吗?用== -1 替换!= -1

编辑:

假设你的意思是:

if ((navigator.userAgent.indexOf('iPhone') != -1) ||  
(navigator.userAgent.indexOf('iPod') != -1)) {  
document.location = "iPhone.aspx"; } else {
document.location = "notiPhone.aspx";
}

(navigator.userAgent.indexOf('iPhone') == -1表示userAgent中没有这样的字符串"iPhone"。因此,当您从!=更改为==时,还需要将||更改为&&

if ((navigator.userAgent.indexOf('iPhone') == -1) 
   && (navigator.userAgent.indexOf('iPod') == -1)) {  
    document.location = 'default.aspx';
}