h5 发起一个自定义协议请求,app 拦截这个请求后,再由 app 调用 h5 中的回调函数

 协议拦截 由 h5 发起一个自定义协议请求,app 拦截这个请求后,再由 app 调用 h5 中的回调函数

  1. 由 app 自定义协议,比如 sdk://action?params

  2. 在 h5 定义好回调函数,比如

    window.bridge={getDouble:value=>{},getTriple:value=>{}}

  3. 由 h5 发起一个自定义协议请求,比如 location.href=‘sdk://double?value=10’

  4. app 拦截这个请求后,进行相应的操作,获取返回值

  5. 由 app 调用 h5 中的回调函数,比如 window.bridge.getDouble(20);

javascript

window.bridge = {
​
  getDouble: value => { // 20
​
  }, 
​
  getTriple: value => {
  // more  
  }
};
location.href =  'sdk://double?value=10' ;

android:

webview.setWebViewClient( new WebViewClient () {
​
@Override
​
public boolean houldOverrideUrlLoading( WebView view,String url) {
​
// 判断如果 url 是 sdk:// 打头的就拦截掉
​
// 然后从 url sdk://action?params 中取出 action 与params 
​
    Uri uri = Uri.parse(url);                                 
​
    if ( uri.getScheme().equals( "sdk" )) {
    // 比如 action = double, params = value=10
        webview.evaluateJavascript( 'window.bridge.getDouble(20)' );
            return true;
    }
      
  }
​
});
​

ios:

(BOOL)webview:( UIWebView *)webview shouldStartLoadWithRequest:( NSURLRequest *)request navigationType:( UIWebViewNavigationType )navigationType { 
​
// 判断如果 url 是 sdk:// 打头的就拦截掉
​
// 然后从 url sdk://action?params 中取出 action 与params
​
NSString *urlStr = request.URL.absoluteString;
​
if ([urlStr hasPrefix:@ "sdk://" ]) {
​
  // 比如 action = double, params = value=10
​
  NSString *func = @"window.bridge.getDouble(20)" ;
​
  [webview stringByEvaluatingJavaScriptFromString:func];
​
      return NO; 
​
  }
​
  return YES;
​
}
​

猜你喜欢

转载自blog.csdn.net/weixin_43837268/article/details/109167268
今日推荐