美文网首页
2020-07-23 react-native-webview

2020-07-23 react-native-webview

作者: KingAmo | 来源:发表于2020-07-23 13:01 被阅读0次

我们知道,通过 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
我们需要重写webviewshouldOverrideUrlLoading方法,拦截需要打开的 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;
    }
})

参考:
https://stackoverflow.com/questions/41693263/android-webview-err-unknown-url-scheme/41693364#41693364

问题来了,在 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
很巧妙的方法。

相关文章

网友评论

      本文标题:2020-07-23 react-native-webview

      本文链接:https://www.haomeiwen.com/subject/ayoclktx.html