August 7, 2021August 7, 2021 0 Comments
JavaScript browser agent redirect
JavaScript browser agent redirect
I’ve got this little bit of code on my webpage header to redirect the user to a different page if they are using an iPhone:<script type="text/javascript"> if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1)) { document.location = "iPhone.aspx"; } </script> Is there an easy way to ‘reverse’ this code, so anyone landing on the iPhone page from ANY other browser will be redirected back to the home page?Many thanks. |
Best Answer
Simple solution. Replace your existing one with this.if(!/(iphone|ipod)/i.test(navigator.userAgent)) { window.location = "Desktop.aspx"; } Updated since its only for iPhone page. |
comments:Thanks! Very simple and works a treat! 🙂 |
Other Answer1
To reverse? Replace != -1 with == -1 Edit:Suppose you mean something like this:if ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1)) { document.location = "iPhone.aspx"; } else { document.location = "notiPhone.aspx"; } |
comments:I tried: <script type=”text/javascript”> if ((navigator.userAgent.indexOf(‘iPhone’) == -1) || (navigator.userAgent.indexOf(‘iPod’) == -1)) { document.location = “Default.aspx”;} </script> However, it just sends the iPhone on a loop, bouncing from Default.aspx to iPhone.aspxYou should log or alert the userAgent string and have a look to see if your string matches. Also, try alert(navigator.userAgent.indexOf(‘iPhone’)) – what comes up? |
Other Answer2
(navigator.userAgent.indexOf('iPhone') == -1 means there is no such string “iPhone” in the userAgent. So when you change from != to == , you need to change || to && as well.if ((navigator.userAgent.indexOf('iPhone') == -1) && (navigator.userAgent.indexOf('iPod') == -1)) { document.location = 'default.aspx'; } |