1

I need to open vk.com, facebook, twitter apps when user clicks on url, in case this app is installed.

Otherwise, new tab should be opened with http url.

Are there some ready solutions for this?

I need this to work at ios, android & windows devices.

avasin
  • 9,186
  • 18
  • 80
  • 127

1 Answers1

2

This can be done using a URL scheme. Unfortunately, different operating systems (ios, android, etc) respond to different URL schemes for their mobile apps. So, first you will have to find out what device the user is using. This can be obtained by making use of the navigator.userAgent property:

var ua = window.navigator.userAgent;

The ua variable is a string representing user information, such as, which browser they are using. So you can use String's match method to look for specific values:

var IS_IPAD = ua.match(/iPad/i) != null,
    IS_IPHONE = !IS_IPAD && ((ua.match(/iPhone/i) != null) || (ua.match(/iPod/i) != null)),
    IS_IOS = IS_IPAD || IS_IPHONE,
    IS_ANDROID = !IS_IOS && ua.match(/android/i) != null,
    IS_MOBILE = IS_IOS || IS_ANDROID;

Now that you know which device the user is using, you can use the correct URL scheme. Android uses Intents with an intent:// prefix and IOS uses the format appname://parameters. So, you can do:

if(IS_IOS){
    window.location = "myapp://view?id=123";
}else if(IS_ANDROID){
    window.location = 'intent://view?id=123#Intent;package=my.app.id;scheme=myapp;launchFlags=268435456;end;';
}

You may want to use a timeout for IOS (Android will bring to the Play Store if app is not installed) to see if the app loaded or not. If the app didn't load then you can set the window location to your standard URL.

This solves the problem for Android and IOS, however, it doesn't cover Windows mobile devices. Though, I'm sure it's a similar approach. I haven't found any particular libraries that abstracts and handles this code for you but it's fairly simple to implement.

Resources / Further Reading:

Community
  • 1
  • 1
chRyNaN
  • 3,592
  • 5
  • 46
  • 74
  • There is a problem: Safari will show error for such custom protocol, if app not installed. Perhaps app links could be a solution, but i can't make them work. – avasin May 19 '15 at 17:32