Method interworking between H5 and native app

Time:2020-6-29

Recently, I have done mixed development with app, and learned the method interworking between H5 and native app


First, we define methods for app side to use (take Vue as an example)

Define a method name in methods
VContent() {
    console.log ("method for app")
},
Then we can mount this method to window in the life cycle. Yes, it is so simple

mounted(){
  window.VerifyContent = this.VerifyContent;
},
So the app can use our method

Sometimes Android and IOS need to be handled differently

getDemo() {
          let u = navigator.userAgent;
          Let isios =!! u.match (/ \ (I [^;] +; (U;)? CPU. + Mac OS X /); // IOS terminal
          if (isiOS) {
          //Operation of IOS side
          } else {   
          //Operation of androdel
        }
    },
Also, mount the method to window in the lifecycle

In these methods, parameter passing is supported. For example, during the development process, IOS supports passing multiple parameters to my method, while Android side needs to merge all parameters into one object and pass them to me

How can we call app side methods in H5?

First, Android
Android will inject a global JS object into H5 by app, and then directly access this object in H5, similar to this
Method interworking between H5 and native app
H5 is also very simple to call:
`

try {
          window.android.XXX(type, id);
        } catch (error) {
          console.log("Android error");
        }
    Android is the name in the picture above. XXX is the way Android gives you

Next is IOS

try {                      
      window.webkit.messageHandlers.XXX.postMessage(JSON.str     ingify(json));
            } catch(error) {  
              console.log("ios error");
     }
   This XXX is the way IOS gives you