gpszymczak
6/23/2011 - 6:30 AM

Prevent links in standalone web apps opening Mobile Safari

Prevent links in standalone web apps opening Mobile Safari

// Mobile Safari in standalone mode
if(("standalone" in window.navigator) && window.navigator.standalone){

	// If you want to prevent remote links in standalone web apps opening Mobile Safari, change 'remotes' to true
	var noddy, remotes = false;
	
	document.addEventListener('click', function(event) {
		
		noddy = event.target;
		
		// Bubble up until we hit link or top HTML element. Warning: BODY element is not compulsory so better to stop on HTML
		while(noddy.nodeName !== "A" && noddy.nodeName !== "HTML") {
	        noddy = noddy.parentNode;
	    }
		
		if('href' in noddy && noddy.href.indexOf('http') !== -1 && (noddy.href.indexOf(document.location.host) !== -1 || remotes))
		{
			event.preventDefault();
			document.location.href = noddy.href;
		}
	
	},false);
}
<!DOCTYPE html>
<head>
<title>Stay Standalone</title>
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<script src="stay_standalone.js" type="text/javascript"></script>
</head>
<body>
<ul>
<li><a href="http://google.com/">Remote Link (Google)</a></li>
<li><a href="javascript:alert('Awesome script is awesome')">JavaScript Link</a></li>
<li><a href="/">Local Link</a></li>
<li><a href="#amp">Local Anchor</a></li>
</ul>
</body>