This article is mainly about UIWebView and JS interaction, UIWebView and JS Interactive detailed https://www.cnblogs.com/llhlj/p/6429431.html
A. Wkwebview Call JS
[WebView evaluatejavascript:@ " I am js" completionhandler:^ (ID _nullable response, Nserror * _nullable error) { }];
The method is executed asynchronously
Two. JS Call OC
When the JS side wants to pass some data to the iOS. Then they call the method below to send.
window.webkit.messagehandlers.< Object Name >.postmessage (< data >)
The above code in the JS side write error, resulting in the page behind the business does not execute. Can be used to try-catch execute.
Then the processing method in OC is as follows. It is the proxy method for Wkscriptmessagehandler. Name corresponds to the object name in JS above.
-(void) Addscriptmessagehandler: (ID <WKScriptMessageHandler>) scriptmessagehandler Name: ( NSString *) name;
Specifically add the following
1. Set the agent and name of the Addscriptmessagehandler
Wkwebviewconfiguration *configuration =[[Wkwebviewconfiguration alloc] init]; Wkusercontentcontroller*usercontentcontroller =[[Wkusercontentcontroller alloc] init]; [Usercontentcontroller addscriptmessagehandler:self Name:@"Test"]; Configuration.usercontentcontroller=Usercontentcontroller; //Wkpreferences *preferences = [wkpreferencesNew]; Preferences.javascriptcanopenwindowsautomatically=YES;//preferences.minimumfontsize = 40.0;Configuration.preferences =preferences; _webview= [[Wkwebview alloc] Initwithframe:cgrectmake (0,0, WIDTH, HEIGHT64) configuration:configuration];
2.WKScriptMessageHandler protocol Method
-(void ) Usercontentcontroller: (Wkusercontentcontroller *) Usercontentcontroller didreceivescriptmessage: (wkscriptmessage * Span style= "COLOR: #008000" >// js call oc method // message.boby is the argument passed in JS NSLog (@ " body:%@ " ,message.body); if ([message.name isequaltostring:@ " test " ] { // concrete logic [self sendMessage:message.body]; } }
3. Destruction
-(void) dealloc { ... [[_webview configuration].usercontentcontroller Removescriptmessagehandlerforname: @" Object Name " ]; ...}
iOS js with native interaction two