我们知道,通过 url scheme 能在自己的app中打开第三方的app,使用url sheme 的场景有三种:原生中,RN中,web中,我们来一一分析一下:
原生中:
在原生中,第三方app通过 weixin://
是能打开这个 url scheme
是能打开微信的。比如安卓中:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse('weixin://'));
startActivity(intent);
RN中:
在RN
中,如何打开微信呢?
其实RN提供的 Linking
就能做到:
Linking.openURL("weixin://")
Linking 组件在原理上也是用的上面的原生的方法处理 url sheme:IntentModule.java
webview中
在原生的 webview
中,如果不做处理,直接通过 url scheme
打开微信会报错:net:err_unkown_url_scheme
。
我们需要重写webview
的shouldOverrideUrlLoading
方法,拦截需要打开的 url
,如果不是http
或者https
开头的,那就用上面的原生中的方法,然后就能打开微信了
webview.setWebViewClient(new WebViewClient(){
// 如果应用程序想要离开当前WebView并处理url本身,则返回true,否则返回false。
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// 以"http","https"开头的url在本页用webview进行加载,其他链接进行跳转
if( url.startsWith("http:") || url.startsWith("https:") ) {
return false;
}
Intent intent = new Intent();
intent.setData(Uri.parse(url));
startActivity(intent);
//如果不需要其他对点击链接事件的处理返回true,否则返回false
return true;
}
})
问题来了,在 react-native-webview
中,我们的h5页面不用做任何工作,就可以通过url sheme
直接跳转到微信,这个是如何做到的呢?
其实 react-native-webview
也是拦截了 url,做了一定的处理,只是这个处理是放在了js
端:
WebViewShared.tsx 这里定义了一个createOnShouldStartLoadWithRequest
方法,这个方法会检测传入的url
,通过正则匹配,如果是 url scheme 格式的url ,就会用 react native 的 linking
来打开这个url,也就能跳转到第三方应用了。
具体的执行位置在:WebView.android.tsx
很巧妙的方法。
网友评论