ios/android native application interacts with H5

H5 and native interaction is a very common requirement, now introduce the basic interaction method

Android side:

1. The main implementation method of H5 calling Android native methods is to inject a custom js object into the web through the addJavascriptInterface method of WebView to implement js calling Android methods.

1. H5 calls the Android method

1.1. For example: the H5 end calls the finishActivity method on the Android end:

window.android.finishActivity('Send to android1')

1.2. Android injects an object (android) into WebView:

@JavascriptInterface public void finishActivity(String  value) {    

 Log.e("Native method invoked by js=",value);    

 finish();

}

1.3, webview code configuration:

 

2. Android calls the H5 method

2.1. H5 needs to mount events in the window and expose them to mobile calls:

window.setAuthentication = this.setAuthentication  

//specific method

setAuthentication(param) {      

this.roomTotal = JSON.stringify(param)      

return '...authentication information....'    

}

 2.2. Call the js method through the evaluateJavascript method of WebView: 

 2.3, Android 4.4 and above call evaluateJavascript to implement calling the js method, and at the same time can obtain the data returned by the web page. webview.evaluateJavascript(javascript: method name (parameter),

new ValueCallback{          

public void onReciveValue(String value){}

})

2. The parameter is a string in json format, and the web page will receive a json object

IOS side:

1. js calls iOS native methods JS calls iOS native methods through the WKScriptMessageHandler protocol provided by WkwebView.

The H5 side calls the nativeMethod method on the iOS side: window.webkit.messageHandlers.nativeMethod.postMessage('');

iOS native registration method

nativeMethod: [config.userContentController addScriptMessageHandler:self name:@"nativeMethod"]; 

When js calls the method registered by iOS, iOS will use the proxy method of WKScriptMessageHandler:

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message 

2. iOS calls the js method

Call the js method through evaluateJavaScript of WkWebView:

NSString *promptCode = [NSString stringWithFormat:@"%@()", @"nativeCalljs0"]; [self.wkWebView evaluateJavaScript:promptCode completionHandler:^(id _Nullable result, NSError * _Nullable error) {        

//result can receive the return value of the js method        

NSLog(@"%@",result);

 }];

Because iOS and Android have different calling methods from H5, we need to judge the embedded platform in advance. The complete code is as follows:

 

Guess you like

Origin blog.csdn.net/qq_26704997/article/details/127507966