This article was mainly transferred from: https://www.jianshu.com/p/cdaf9bc3d65d
http://blog.csdn.net/u011993697/article/details/51577295
OC and JS Interactive implementation of a lot, before iOS7 used more is Webviewjavascriptbridge, after iOS7 Apple will javascriptcore framework open, so add a choice.
1. Preparatory work
First, you import the JavaScriptCore header file
#import <JavaScriptCore/JavaScriptCore.h>
2, loading HTML files with WebView, here is the local HTML
-(void*path = [[[NSBundle Mainbundle] Bundlepath] stringbyappendingpathcomponent:@ " jscalloc.html " *request = [Nsurlrequest requestwithurl:[nsurl fileurlwithpath:path]];[ Self.webview loadrequest:request];}
3, before the JS interaction, you need to create an environment using JS through Jscontent
- (void) Webviewdidfinishload: (UIWebView *) webview{//undocumented access to UIWebView ' s JscontextSelf.context = [WebView valueforkeypath:@"DocumentView.webView.mainFrame.javaScriptContext"]; //Printing ExceptionsSelf.context.exceptionHandler = ^ (Jscontext *context, Jsvalue *exceptionvalue) {context.exception=Exceptionvalue; NSLog (@"%@", Exceptionvalue); }; }
4, JS call OC Code
4.1. Call through block
<type= "button" value= "Test log" onclick= "log (' test ') );" />
self.context[@ "log"] = ^ (NSString *str) {NSLog (@ "%@ ", str);};
4.2. Implement Jsexport Protocol
Define what needs to be exposed to JS
<type= "button" value= "calculate factorial" onclick= " Native.calculateforjs (Input.value); " />
@protocol Testjsexport <JSExport>-(void) Handlefactorialcalculatewithnumber: (NSNumber *) number); @end
// The method of associating native with Jsexport protocol self.content[@ "native"] = self;
5, OC Call JS code
In OC, all the objects that represent JS are created with Jsvalue, and the JS object is obtained by means of the Objectforkeyedsubscript method or by using the subscript directly, and then using the Callwitharguments method to execute the function.
// method one. Jsvalue *function = [Self.context objectforkeyedsubscript:@ "factorial"]; // method Two. Jsvalue * function = self.context[@ "factorial"*result == [ NSString stringWithFormat:@ "%@", [result Tonumber]];
One Demon connection: Https://github.com/shaojiankui/JavaScriptCore-Demo
6. Encapsulation
The JavaScriptCore is packaged to make it easier for iOS and frontend to interact with the data and invoke the method, in the same way as Webviewjavascriptbridge, first configured in the Plist file, the externally exposed OC interface needs to implement the specified protocol.
Demo:https://github.com/hzquan/webviewjavascriptcorebridge
IOS JavaScriptCore Introduction