Forum Moderators: open

Message Too Old, No Replies

mobile device detection and then back again

         

terrybarnes

3:06 pm on Nov 7, 2008 (gmt 0)

10+ Year Member



I have used this script to detect whether someone is looking at my site on an iPhone:

<script type="text/javascript">
if ((navigator.userAgent.indexOf('iPhone') != -1) ¦¦
(navigator.userAgent.indexOf('iPod') != -1)) {
document.location = "http://www.example.com/";
}
</script>

I then have a link on the iPhone site that lets the user view the main site, although it's not really optimised for the iPhone. The only trouble is when they click that link it then takes them to the index page which obviously has the detection script and so forwards them to the iPhone site!

Is there anything I can do to get around this?

[edited by: Fotiman at 5:42 pm (utc) on Nov. 7, 2008]
[edit reason] Examplified URL [/edit]

Fotiman

5:56 pm on Nov 7, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I can think of a couple of easy solutions.

1. Check the document.referrer to see if the user is coming from your redirect site:


if ((navigator.userAgent.indexOf('iPhone') != -1) ¦¦
(navigator.userAgent.indexOf('iPod') != -1)) {
if (document.referrer.indexOf('http://www.example.com/') == -1) {
// Not coming from example.com so redirect
document.location = 'http://www.example.com/';
}
}

2. Another alternative would be to pass a value in the query string on the link to direct them back to your site, and then look for that value before redirecting (similar to the referrer check above).

Hope that helps.

terrybarnes

8:12 pm on Nov 7, 2008 (gmt 0)

10+ Year Member



Thanks for this - it seems to work okay except when it's been directed to the main site and then I hit refresh on the browser it continues to go to the main site and not the iPhone site. Could be a caching issue with the iPhone because after a few more refresh attempts it goes back to the iPhone site.

Demaestro

9:00 pm on Nov 7, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



If it were me I would set a cookie if they click the link.

Check for the cookie before you do the redirect and if it exists then don't do the redirect.

You can store the cookie for a while that way when they come back to your site they don't have to click the link everytime.

Also you should add this as well

navigator.userAgent.indexOf('mini') != -1

It will catch all the Opera minis versions which is used on a lot of phones for web browsing.

[edited by: Demaestro at 9:01 pm (utc) on Nov. 7, 2008]

terrybarnes

10:00 pm on Nov 7, 2008 (gmt 0)

10+ Year Member



Thanks for your help