Cheese1223
Cheese1223

Reputation: 107

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.

Upvotes: 1

Views: 1908

Answers (3)

Matt Lo
Matt Lo

Reputation: 5731

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.

Upvotes: 2

Grace Huang
Grace Huang

Reputation: 5679

(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';
}

Upvotes: 0

Johan
Johan

Reputation: 35194

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";
}

Upvotes: 0

Related Questions