根据浏览器重定向到特定页面

时间:2016-06-16 13:04:36

标签: javascript html url redirect

大家好我希望我的页面在Chrome浏览器中打开时重定向说“GOOGLE”,并在firefox中打开时说“YOUTUBE”。
我试图通过navigator.appCodeName检测用户的浏览器,它返回浏览器名称,但它无法正常工作,只能在mozilla中使用。

    <body onload="myFunction()">     <script> function myFunction() { var x = navigator.appCodeName; if(x.indexOf('Chrome')>=0){ window.location.href="http://youtube.com"; }else{ window.location.href="http://google.com"; } }       
任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

  • 使用window.location.replace(&#34; --- url here ---&#34;)
  • 出于兼容性原因,所有现代浏览器都会返回&#34; Mozilla&#34;
  • 所以Iam在这里使用navigator.userAgent返回浏览器发送给服务器的用户代理头。

  • 如果它是mozilla

  • ,则返回Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0
  • Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.84 Safari/537.36如果是铬。

    <body onload="myFunction()"> <script> function myFunction() { var x = navigator.userAgent; if(x.indexOf('Chrome')>=0){ window.location.replace("https://google.com") console.log("hello chrome"); }else{ window.location.replace("https://youtube.com"); console.log("hello mozilla"); } }
    希望这有帮助