https://blog.csdn.net/dolacmeng/article/details/79623708
h5 code
<html> <head> <meta charset='utf-8'/> <title></title> <script> function showAlert(String){ alert(String); } function onClickOC(String){ app.onClickOC(String); } function clickCallBack(result){ document.getElementById("result").innerHTML="Click results:"+result; } </script> </head> <body> <button type="button" onclick="onClickOC('html')">click me</button> <a href="tt://showmsg">showmsg</a> <p id="result">Click results:</p> </body> </html>
Intercept URL
For UIWebView and WKWebView, for h5 tags with hyperlinks, such as the 'a' tag in the h5 code above.
web tune OC
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *requestStr = request.URL.absoluteString; if ([requestStr isEqualToString:@"tt://showmsg"]) { NSLog(@"show OC msg"); //OC calls JS to return OC processing result to web page [webView stringByEvaluatingJavaScriptFromString:@"clickCallBack('Click Finish')"]; return NO; } return YES; }
JavaScriptCore
Method 1: use block
-(void)webViewDidFinishLoad:(UIWebView *)webView { JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; context[@"onClickOC"] = ^(NSString *string) { NSLog(@"onClickOC--%@", string); }; }
Method 2:
- The new class inherits from NSObject (such as AppJSObject).
- The. h file declares a proxy and follows JSExport. The methods in the proxy are consistent with the method names defined by js.
- The corresponding method in < 2 > agent is implemented in. m file, which can handle events or notify agent within the method.
- The AppJSObject instance object class is injected into JS in the agent that UIWebView completes loading. Then the calling method in JS will be invoked to the corresponding method in the native AppJSObject instance object.
//APPJSObject.h #import <Foundation/Foundation.h> #import <JavaScriptCore/JavaScriptCore.h> @protocol APPJSObjectDelegate <JSExport> -(void)onClickOC:(NSString *)name; @end @interface APPJSObject : NSObject<APPJSObjectDelegate> @property (nonatomic, weak) id<APPJSObjectDelegate> delegate; @end
//APPJSObject.m #import "APPJSObject.h" @implementation APPJSObject -(void)onClickOC:(NSString *)name { [self.delegate onClickOC:name]; } @end
-(void)webViewDidFinishLoad:(UIWebView *)webView { JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; APPJSObject *obj = [[APPJSObject alloc] init]; obj.delegate = self; context[@"app"] = obj; }
OC tune JS
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; //js string is the JavaSCript function to call NSString *js = [NSString stringWithFormat:@"clickCallBack('Click Finish')"]; [context evaluateScript:js];