Skip to content

Instantly share code, notes, and snippets.

@JKirchartz
Created September 21, 2011 15:09
Show Gist options
  • Save JKirchartz/1232304 to your computer and use it in GitHub Desktop.
Save JKirchartz/1232304 to your computer and use it in GitHub Desktop.
Mobile Redirect

Here is a simple javascript redirect that uses the Mobile Link Discovery Spec a valid markup link tag that tells the browser where to find an Alternate for Hand-Held devices.

<link rel="alternate" media="handheld" href="http://m.google.com" />

simply replace m.google.com with the url of your mobile site.

and import this script

<script type="text/javascript" src="redirect.js"></script>

You can also add a link back to the full version of the site by adding full=true to the list of URL parameters.

http://domain.tld/?full=true
if(window.location.search.substring(1) !== "full=true"){
var l = document.getElementsByTagName("link");
for(var i = 0; i < l.length; i++)
{
// find the right link tag, test the userAgent & screen.width
if((/alternate/i.test(l[i].rel) && /handheld/i.test(l[i].media)) &&(/iPhone|iPad|Android|Blackberry|WebOs/i.test(navigator.userAgent) || screen.width <= 699))
{
window.location.replace(l[i].href);
}
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<LINK REL="HOME" TITLE="Idocs Home Page" HREF="http://www.idocs.com">
<LINK REL="PREVIOUS" TITLE="URLs" HREF="../urls/">
<LINK REL="NEXT" TITLE="Lines and Paragraphs" HREF="../linepar/">
<LINK REV="MADE" TITLE="Miko O'Sullivan" HREF="mailto:tags@idocs.com">
<LINK REL="COPYRIGHT" TITLE="copyright info" HREF="copyright.html">
<LINK REL="STYLESHEET" TITLE="style sheet" HREF="stdstyles.css">
<link rel="alternate" media="screen" href="http://google.com" />
<!-- begin redirect -->
<!-- link tag to direct script to media alternative -->
<link rel="alternate" media="handheld" href="http://m.google.com" />
<!-- import script to redirect -->
<script type="text/javascript" src="redirect.js"></script>
<!-- end redirect -->
</head>
<body>
If you can see this you're probably on a desktop browser. If you weren't you'd see m.google.com.
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment