h5 app to interact with

Now move side web applications, often need to interact with a native app, communication (run in webview in), such as jssdk micro letter, call some native app functionality by window.wx object. So, this time to stroke a stroke h5 with the principle of native app interaction.

H5 interact with the native app is, in essence, is the two invocation:

 

  • app call code h5

  • h5 calling app code

 

1. app call code h5

Because the app is the host, you can access directly h5, so this call is relatively simple, is exposed to a number of global objects (including methods), then call these objects in a native app in the h5.

javascript:

29ef7c2ed10a44fc8af17358529e4384.png

android:

7865751cdf2840d49d6d9e853af67c8d.png

ios:

bed824d0d0de4710b19465e1f672367c.png

2. h5 calling app code

Because h5 can not directly access the host app, so this call is relatively little complicated.

This commonly invoked in two ways:

 

  • Js object is to inject a global h5 by the app, and then access the object directly in h5

  • After the h5 agreement to launch a custom request, app intercepts the request, then the app calls the callback function h5

 

Injection of 2.1 app js subject to a global h5

In this way communication mechanism is simple, relatively easy to understand, and for the h5, there is no new thing, it is more recommended way. However, this approach may be a security risk, you do not know in detail view using the Android WebView vulnerability.

 

android:

74a43fa8da294b68800f99728cc718aa.png

ios:

e61c92ec8352486abb0197624c528e0e.png

javascript:

40ec359e253b4140b0234c12d26cdfb1.png

2.2 h5 initiated by a request for a custom protocol

To this way a little bit more complex because of the need to customize the protocol, which is a relatively new thing for a lot of front-end developers. It is generally not recommended in this way, it can complement the first way.

Generally requires the following steps:

 

  • The app custom protocols, such as sdk: // action params?

  • In h5 defined the callback function, such as window.bridge = {getDouble: value => {}, getTriple: value => {}}

  • H5 initiated by a request for a custom protocol, such location.href = 'sdk:? // double value = 10'

  • After app intercept this request, the corresponding operation, acquires the return value

  • App h5 called by the callback function, such as window.bridge.getDouble (20);

 

javascript:

0204c45cfb1b428cb2f62029a4e636d0.png

android:

882674db65aa44e3888f09cf37126527.png

ios:

32883b3aa5694dceafb9c7bc345fe7c8.png

 

Guess you like

Origin www.cnblogs.com/yayaxuping/p/10958771.html