How i can make crossbrowser native-app urls with http url fallback on website?

喜夏-厌秋 提交于 2019-12-11 07:01:41

问题


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.


回答1:


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:

  • How to launch apps (facebook/twitter/etc) from mobile browser but fall back to hyperlink if the app isn't installed
  • URL schemes for iOS and Android (2/2)


来源:https://stackoverflow.com/questions/29906818/how-i-can-make-crossbrowser-native-app-urls-with-http-url-fallback-on-website

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!