Sunday, March 29, 2015

Webapp for iOS: How to avoid links opening in Safari

If you're a web developer, you may have found out that any website can be added to the home screen of any iOS devices.

It's a feature that is builtin iOS and with the proper meta-tags in your HTML code, you can create a webapp for iPhones and iPads quite easily.

The main issue is when your webpage has links.  The default behaviour in iOS is to open Safari to view the link, meaning that your webapp will open in Safari as soon as the user clicks a link in your webpage.  This is annoying as you may want the link to open inside the webapp and not in Safari.

Do not despair, there is a simply trick that you can use with Javascript to avoid this issue.  Nothing fancy and nothing complicated.  Just a simple line of Javascript will solve this problem...

Here's a common link in a webpage:

<a href="viewer.php">View this link</a>
The problem is that as the user will click this link on his iPhone, Safari will popup to display the content of the link instead displaying the "viewer.php" from inside the webapp.  Instead, create your links as such:
<div onclick="document.location='viewer.php';">View this link</div>
This will load the new webpage and stay inside the webapp instead of opening in Safari.  As a bonus, the "onclick" event is available on almost all elements, meaning that you can transform any element into a clickable link.

The, you just have to use CSS to set the proper look on the element to it looks like it is a link and behaves like a link...

Have fun!