Home > Web Front-end > H5 Tutorial > body text

How do HTML5 and native apps interact?

不言
Release: 2018-10-22 16:55:50
forward
8872 people have browsed it

The content of this article is about how HTML5 and native apps interact? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

h5 Principles of interaction with native apps

Now mobile web applications often need to interact and communicate with native apps (running in webview), such as WeChat's jssdk calls some native app functions through the window.wx object. So, this time let’s take a look at the principles of interaction between h5 and native apps.

The interaction between h5 and native app is essentially two kinds of calls:

  1. app calls h5 code

  2. h5 Code for calling app

1. Code for app calling h5

Because app is the host and can directly access h5, so this The call is relatively simple, which is to expose some global objects (including methods) in h5, and then call these objects in the native app.

How do HTML5 and native apps interact?

javascript

window.sdk = {
  double = value => value * 2,
  triple = value => value * 3,
};
Copy after login

android

webview.evaluateJavascript('window.sdk.double(10)', new ValueCallback<string>() {
  @Override
  public void onReceiveValue(String s) {
    // 20
  }
});</string>
Copy after login

ios

NSString *func = @"window.sdk.double(10)";
NSString *str = [webview stringByEvaluatingJavaScriptFromString:func]; // 20
Copy after login

2. h5 code for calling app

Because h5 cannot directly access the host app, this call is relatively complicated.

There are two common ways of calling this:

  1. The app injects a global js object into h5, and then directly accesses this object in h5

  2. H5 initiates a custom protocol request. After the app intercepts the request, the app calls the callback function in h5

2.1 From app to h5 Injecting a global js object

This method has a simple communication mechanism and is easier to understand, and there is nothing new for h5, so it is a more recommended method. But this method may have security risks. Check out the Android WebView usage vulnerabilities you don’t know about in detail.

How do HTML5 and native apps interact?

##android

webview.addJavascriptInterface(new Object() {
  @JavascriptInterface
  public int double(value) {
    return value * 2;
  }
  
  @JavascriptInterface
  public int triple(value) {
    return value * 3;
  }
}, "appSdk");
Copy after login

ios

NSString *scripts = @"window.appSdk = {double: value => value * 2, triple: value => value * 3}";
[webview stringByEvaluatingJavaScriptFromString:scripts];
Copy after login

javascript

window.appSdk.double(10); // 20
Copy after login

2.2 Initiate a custom protocol request from h5

This method is a little more complicated because it requires a custom protocol, which is relatively new to many front-end developers. Therefore, this method is generally not recommended and can be used as a supplement to the first method.

The following steps are roughly required:

  1. The protocol is customized by the app, such as sdk://action?params

  2. Define the callback function in h5, such as window.bridge = {getDouble: value => {}, getTriple: value => {}}


  3. Initiated by h5 A custom protocol request, such as location.href = 'sdk://double?value=10'

  4. app After intercepting this request, perform the corresponding operation and obtain the return value

  5. The callback function in h5 is called by the app, such as window.bridge.getDouble(20);


How do HTML5 and native apps interact?

javascript

window.bridge = {
  getDouble: value => {
    // 20
  }, 
  getTriple: value => {
    // more  
  }
};

location.href = 'sdk://double?value=10';
Copy after login

android

webview.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(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;
        }
        return super.shouldOverrideUrlLoading(view, url);
    }
});
Copy after login

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;
}
Copy after login


The above is the detailed content of How do HTML5 and native apps interact?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!