I found that the selected answer works for the browser apps but I was having issues with the code working in non browser apps that implement a UIWebView
.
The problem for me was a user on the Twitter app would click a link that would take them to my site through a UIWebView
in the Twitter app. Then when they clicked a button from my site Twitter tries to be fancy and only complete the window.location
if the site is reachable. So what happens is a UIAlertView
pops up saying are you sure you want to continue and then immediately redirects to the App Store without a second popup.
My solution involves iframes. This avoids the UIAlertView
being presented allowing for a simple and elegant user experience.
jQuery
var redirect = function (location) {
$('body').append($('<iframe></iframe>').attr('src', location).css({
width: 1,
height: 1,
position: 'absolute',
top: 0,
left: 0
}));
};
setTimeout(function () {
redirect('http://itunes.apple.com/app/id');
}, 25);
redirect('custom-uri://');
Javascript
var redirect = function (location) {
var iframe = document.createElement('iframe');
iframe.setAttribute('src', location);
iframe.setAttribute('width', '1px');
iframe.setAttribute('height', '1px');
iframe.setAttribute('position', 'absolute');
iframe.setAttribute('top', '0');
iframe.setAttribute('left', '0');
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
};
setTimeout(function () {
redirect('http://itunes.apple.com/app/id');
}, 25);
redirect('custom-uri://');
EDIT:
Add position absolute to the iframe so when inserted there isn't a random bit of whitespace at the bottom of the page.
Also it's important to note that I have not found a need for this approach with Android. Using window.location.href
should work fine.