26 1 / 2014
Smallest piece of code that’s going to change the world (okay iOS world may be) :P
The iOS custom URL scheme is broken. Have a link to a custom url for your app in the browser, and it works like a charm, if you have the app installed. If not, then you are doomed! Safari shows a super helpful alert that says - ‘Safari cannot open the page because the address is invalid.’ The other browsers are even more helpful, and they do nothing! Absolutely nothing. They don’t have the decency to redirect you to an alternate URL (or provide one), or prompt you to download the app.
May be the solution is somewhere out there, but I couldn’t find it. Or may be google has been lazy lately, and their focus shifted to google+ =P
There are start-ups built around solving this problem, and I am going to give this away for free. Remember, I wanted to change the world ;)
To start with, this isn’t rocket science, but it took me a lot of trial and error, and fine tuning to get this working on all the iOS browsers. In safari, it still shows that alert, but it goes away in a couple of seconds when the alternate URL is loaded. Here is how I went about solving this:
If it ended here, then life would have been so much fun. But it’s like saying the world would have been so much better if there was no internet explorer. Simply put, it isn’t!
The bad news is that the above code works only for safari, because they designed iOS and came up with 'pageshow’ and 'pagehide’ events, so they have them working well. The other browsers don’t care or give a shit. They don’t fire those events on tab change, or when the browser switches to background/foreground: http://stackoverflow.com/questions/21311478/pagehide-and-pageshow-events-dont-work-as-expected-on-ios-chrome
Sad, but true! Not a problem. Below is another javascript snippet that works well on all the browsers (I tested safari, chrome and mercury, but logically it should work on others as well).
I increased the timeout value to 2000ms because chrome sometimes takes a bit too long to launch the app (may be tries to do some post processing magic), and triggers the code in timeout block before the timers are cleared. Tweak it as per your need, or you can even have timeouts per browser. Also, don’t forget to put the 'source_url’ class on your link tag.
That’s it. This should work in android as well (may be there are other events available in android), but I’ll cross that bridge when I am there. You have the tools now.
Let me know if you need an explanation, see some failure scenarios, or if I can make this better, or you just want to say thank you. If this really changed your world, as mentioned in the misleading title, then send me money instead =P