Reputation: 1
For reasons too long to explain here, I want to use javascript to redirect visitors from my index page to my mobile subdomain if they are certain devices using userAgent.
The issue I have is the mobile site has a "view full site" link that sends you to the index page. This creates a loop condition.
Here is what I am trying to accomplish.
If the referring url is not my own domain and the user agent matches, then redirect to the mobile subdomain.
I am close but missing something.
if (document.referrer != "mydomain.com" &&
(navigator.userAgent.match(/iPhone/i)) ||
(navigator.userAgent.match(/iPod/i)) ||
(navigator.userAgent.match(/iPad/i)) ||
(navigator.userAgent.match(/Googlebot-Mobile/i))); {
location.replace("https://m.mydomain.com");
}
Upvotes: 0
Views: 933
Reputation: 1980
Your condition is a bit funny and you have a semicolon where you shouldnt.
The the referrer condition will be ignored since its just or'ed with the other conditions. Put all the OR's in brackets and it should work.
if (document.referrer != "mydomain.com" &&
((navigator.userAgent.match(/iPhone/i)) ||
(navigator.userAgent.match(/iPod/i)) ||
(navigator.userAgent.match(/iPad/i)) ||
(navigator.userAgent.match(/Googlebot-Mobile/i)))) {
location.replace("https://m.mydomain.com");
}
Having a link is a good idea since it shows youre aware you can never second guess the user (and device recognition) 100%.
As mplungjan says its not very robust to rely on the referrer. I would recommend you store some 'session' information registering the users intention to view on the full site. This can then override your switch.
Most mobile browsers support sessionStorage which you could use to keep track of this (eg sessionStorage['site'] = 'full'
) although I've had issues with iOS and private mode (doesnt store anything in private mode).
Upvotes: 1