├── .DS_Store ├── .gitignore ├── EasyJSWKWebView ├── EasyJSWKWebView.h ├── EasyJSWKWebView.m ├── EasyJSWKWebViewProxyDelegate.h └── EasyJSWKWebViewProxyDelegate.m ├── EasyJSWKWebViewSample.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── mrcao.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ └── mrcao.xcuserdatad │ ├── xcdebugger │ └── Breakpoints_v2.xcbkptlist │ └── xcschemes │ ├── EasyJSWKWebViewSample.xcscheme │ └── xcschememanagement.plist ├── EasyJSWKWebViewSample ├── .DS_Store ├── AppDelegate.h ├── AppDelegate.m ├── Assets.xcassets │ └── AppIcon.appiconset │ │ └── Contents.json ├── Base.lproj │ ├── LaunchScreen.storyboard │ └── Main.storyboard ├── EasyJSWKWebView │ ├── EasyJSWKWebView.h │ └── EasyJSWKWebView.m ├── Info.plist ├── ViewController.h ├── ViewController.m ├── index.html ├── main.m ├── testJavaScript.h └── testJavaScript.m └── README.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrcao2011/EasyJSWKWebView/e03c7e786f2840050ec845efe95986a362d81c06/.DS_Store -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Build generated 2 | build/ 3 | DerivedData/ 4 | 5 | ## Various settings 6 | *.pbxuser 7 | !default.pbxuser 8 | *.mode1v3 9 | !default.mode1v3 10 | *.mode2v3 11 | !default.mode2v3 12 | *.perspectivev3 13 | !default.perspectivev3 14 | xcuserdata/ 15 | 16 | ## Other 17 | *.moved-aside 18 | *.xcuserstate 19 | 20 | *.hmap 21 | *.ipa 22 | *.dSYM.zip 23 | *.dSYM 24 | 25 | .DS_Store 26 | /EasyJSWKWebViewSample.xcodeproj/project.xcworkspace/xcuserdata/ 27 | /EasyJSWKWebViewSample.xcodeproj/xcuserdata/ 28 | .idea -------------------------------------------------------------------------------- /EasyJSWKWebView/EasyJSWKWebView.h: -------------------------------------------------------------------------------- 1 | // 2 | // EasyJSWKWebView.h 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "EasyJSWKWebViewProxyDelegate.h" 11 | 12 | @interface EasyJSWKWebView : WKWebView 13 | 14 | 15 | - (void) addJavascriptInterfaces:(NSObject*) interface WithName:(NSString*) name; 16 | 17 | @end 18 | -------------------------------------------------------------------------------- /EasyJSWKWebView/EasyJSWKWebView.m: -------------------------------------------------------------------------------- 1 | // 2 | // EasyJSWKWebView.m 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import "EasyJSWKWebView.h" 10 | 11 | @interface EasyJSWKWebView() 12 | 13 | @property (nonatomic, strong) EasyJSWKWebViewProxyDelegate* proxyDelegate; 14 | 15 | @end 16 | 17 | @implementation EasyJSWKWebView 18 | 19 | - (id)init{ 20 | self = [super init]; 21 | if (self) { 22 | [self initEasyJS]; 23 | } 24 | return self; 25 | } 26 | - (id)initWithFrame:(CGRect)frame{ 27 | self = [super initWithFrame:frame]; 28 | if (self) { 29 | [self initEasyJS]; 30 | } 31 | return self; 32 | } 33 | - (id)initWithCoder:(NSCoder *)aDecoder{ 34 | self = [super initWithCoder:aDecoder]; 35 | 36 | if (self){ 37 | [self initEasyJS]; 38 | } 39 | 40 | return self; 41 | } 42 | 43 | - (void) initEasyJS{ 44 | self.proxyDelegate = [[EasyJSWKWebViewProxyDelegate alloc] init]; 45 | self.navigationDelegate = self.proxyDelegate; 46 | } 47 | 48 | - (void) setDelegate:(id)delegate{ 49 | if (delegate != self.proxyDelegate){ 50 | self.proxyDelegate.realNavigationDelegate = delegate; 51 | }else{ 52 | [super setNavigationDelegate:delegate]; 53 | } 54 | } 55 | 56 | - (void) addJavascriptInterfaces:(NSObject*) interface WithName:(NSString*) name{ 57 | [self.proxyDelegate addJavascriptInterfaces:interface WithName:name]; 58 | } 59 | 60 | - (void) dealloc{ 61 | 62 | self.proxyDelegate = nil; 63 | } 64 | @end 65 | -------------------------------------------------------------------------------- /EasyJSWKWebView/EasyJSWKWebViewProxyDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // EasyJSWKWebViewProxyDelegate.h 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | @interface EasyJSWKWebViewProxyDelegate : NSObject 12 | 13 | 14 | @property (nonatomic,weak) id realNavigationDelegate; 15 | 16 | 17 | - (void) addJavascriptInterfaces:(NSObject*) interface WithName:(NSString*) name; 18 | @end 19 | -------------------------------------------------------------------------------- /EasyJSWKWebView/EasyJSWKWebViewProxyDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // EasyJSWKWebViewProxyDelegate.m 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import "EasyJSWKWebViewProxyDelegate.h" 10 | #import 11 | 12 | NSString* INJECT_JS = @"window.EasyJS = {\ 13 | __callbacks: {},\ 14 | \ 15 | invokeCallback: function (cbID, removeAfterExecute){\ 16 | var args = Array.prototype.slice.call(arguments);\ 17 | args.shift();\ 18 | args.shift();\ 19 | \ 20 | for (var i = 0, l = args.length; i < l; i++){\ 21 | args[i] = decodeURIComponent(args[i]);\ 22 | }\ 23 | \ 24 | var cb = EasyJS.__callbacks[cbID];\ 25 | if (removeAfterExecute){\ 26 | EasyJS.__callbacks[cbID] = undefined;\ 27 | }\ 28 | return cb.apply(null, args);\ 29 | },\ 30 | \ 31 | call: function (obj, functionName, args){\ 32 | var formattedArgs = [];\ 33 | for (var i = 0, l = args.length; i < l; i++){\ 34 | if (typeof args[i] == \"function\"){\ 35 | formattedArgs.push(\"f\");\ 36 | var cbID = \"__cb\" + (+new Date);\ 37 | EasyJS.__callbacks[cbID] = args[i];\ 38 | formattedArgs.push(cbID);\ 39 | }else{\ 40 | formattedArgs.push(\"s\");\ 41 | formattedArgs.push(encodeURIComponent(args[i]));\ 42 | }\ 43 | }\ 44 | \ 45 | var argStr = (formattedArgs.length > 0 ? \":\" + encodeURIComponent(formattedArgs.join(\":\")) : \"\");\ 46 | \ 47 | var iframe = document.createElement(\"IFRAME\");\ 48 | iframe.setAttribute(\"src\", \"easy-js:\" + obj + \":\" + encodeURIComponent(functionName) + argStr);\ 49 | document.documentElement.appendChild(iframe);\ 50 | iframe.parentNode.removeChild(iframe);\ 51 | iframe = null;\ 52 | },\ 53 | \ 54 | inject: function (obj, methods){\ 55 | window[obj] = {};\ 56 | var jsObj = window[obj];\ 57 | \ 58 | for (var i = 0, l = methods.length; i < l; i++){\ 59 | (function (){\ 60 | var method = methods[i];\ 61 | var jsMethod = method.replace(new RegExp(\":\", \"g\"), \"\");\ 62 | jsObj[jsMethod] = function (){\ 63 | return EasyJS.call(obj, method, Array.prototype.slice.call(arguments));\ 64 | };\ 65 | })();\ 66 | }\ 67 | }\ 68 | };"; 69 | @interface EasyJSWKWebViewProxyDelegate() 70 | { 71 | 72 | } 73 | 74 | @property (nonatomic, strong) NSMutableDictionary* javascriptInterfaces; 75 | 76 | 77 | 78 | @end 79 | @implementation EasyJSWKWebViewProxyDelegate 80 | 81 | 82 | - (void) addJavascriptInterfaces:(NSObject*) interface WithName:(NSString*) name{ 83 | if (! self.javascriptInterfaces){ 84 | self.javascriptInterfaces = [[NSMutableDictionary alloc] init]; 85 | } 86 | 87 | [self.javascriptInterfaces setValue:interface forKey:name]; 88 | } 89 | - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error { 90 | [self.realNavigationDelegate webView:webView didFailProvisionalNavigation:navigation withError:error]; 91 | } 92 | 93 | 94 | - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { 95 | [self.realNavigationDelegate webView:webView didFinishNavigation:navigation]; 96 | } 97 | - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { 98 | 99 | NSString *requestString =[[navigationAction.request URL]absoluteString]; 100 | 101 | if ([requestString hasPrefix:@"easy-js:"]) { 102 | NSArray *components = [requestString componentsSeparatedByString:@":"]; 103 | 104 | NSString* obj = (NSString*)[components objectAtIndex:1]; 105 | NSString* method = [(NSString*)[components objectAtIndex:2] 106 | stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 107 | 108 | NSObject* interface = [self.javascriptInterfaces objectForKey:obj]; 109 | 110 | // execute the interfacing method 111 | SEL selector = NSSelectorFromString(method); 112 | NSMethodSignature* sig = [[interface class] instanceMethodSignatureForSelector:selector]; 113 | NSInvocation* invoker = [NSInvocation invocationWithMethodSignature:sig]; 114 | invoker.selector = selector; 115 | invoker.target = interface; 116 | 117 | NSMutableArray* args = [[NSMutableArray alloc] init]; 118 | 119 | if ([components count] > 3){ 120 | NSString *argsAsString = [(NSString*)[components objectAtIndex:3] 121 | stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 122 | 123 | NSArray* formattedArgs = [argsAsString componentsSeparatedByString:@":"]; 124 | for (int i = 0, j = 0, l = [formattedArgs count]; i < l; i+=2, j++){ 125 | NSString* type = ((NSString*) [formattedArgs objectAtIndex:i]); 126 | NSString* argStr = ((NSString*) [formattedArgs objectAtIndex:i + 1]); 127 | 128 | if ([@"s" isEqualToString:type]){ 129 | NSString* arg = [argStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 130 | [args addObject:arg]; 131 | [invoker setArgument:&arg atIndex:(j + 2)]; 132 | } 133 | } 134 | } 135 | [invoker invoke]; 136 | 137 | decisionHandler(WKNavigationActionPolicyCancel); 138 | return; 139 | } 140 | 141 | decisionHandler(WKNavigationActionPolicyAllow); 142 | } 143 | 144 | - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { 145 | 146 | [self.realNavigationDelegate webView:webView didStartProvisionalNavigation:navigation]; 147 | 148 | 149 | if (! self.javascriptInterfaces){ 150 | self.javascriptInterfaces = [[NSMutableDictionary alloc] init]; 151 | } 152 | 153 | NSMutableString* injection = [[NSMutableString alloc] init]; 154 | 155 | //inject the javascript interface 156 | for(id key in self.javascriptInterfaces) { 157 | NSObject* interface = [self.javascriptInterfaces objectForKey:key]; 158 | 159 | [injection appendString:@"EasyJS.inject(\""]; 160 | [injection appendString:key]; 161 | [injection appendString:@"\", ["]; 162 | 163 | unsigned int mc = 0; 164 | Class cls = object_getClass(interface); 165 | Method * mlist = class_copyMethodList(cls, &mc); 166 | for (int i = 0; i < mc; i++){ 167 | [injection appendString:@"\""]; 168 | [injection appendString:[NSString stringWithUTF8String:sel_getName(method_getName(mlist[i]))]]; 169 | [injection appendString:@"\""]; 170 | 171 | if (i != mc - 1){ 172 | [injection appendString:@", "]; 173 | } 174 | } 175 | 176 | free(mlist); 177 | 178 | [injection appendString:@"]);"]; 179 | } 180 | 181 | 182 | NSString* js = INJECT_JS; 183 | [webView evaluateJavaScript:js completionHandler:nil]; 184 | [webView evaluateJavaScript:injection completionHandler:nil]; 185 | 186 | } 187 | 188 | - (void)dealloc{ 189 | if (self.javascriptInterfaces){ 190 | 191 | self.javascriptInterfaces = nil; 192 | } 193 | 194 | if (self.realNavigationDelegate){ 195 | 196 | self.realNavigationDelegate = nil; 197 | } 198 | 199 | } 200 | 201 | 202 | @end 203 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 46; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | C6EFB2041DD486FB00C25748 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = C6EFB2031DD486FB00C25748 /* main.m */; }; 11 | C6EFB2071DD486FB00C25748 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = C6EFB2061DD486FB00C25748 /* AppDelegate.m */; }; 12 | C6EFB20A1DD486FB00C25748 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = C6EFB2091DD486FB00C25748 /* ViewController.m */; }; 13 | C6EFB20D1DD486FB00C25748 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = C6EFB20B1DD486FB00C25748 /* Main.storyboard */; }; 14 | C6EFB20F1DD486FB00C25748 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C6EFB20E1DD486FB00C25748 /* Assets.xcassets */; }; 15 | C6EFB2121DD486FB00C25748 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = C6EFB2101DD486FB00C25748 /* LaunchScreen.storyboard */; }; 16 | C6EFB2211DD48A7F00C25748 /* WebKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C6EFB2201DD48A7E00C25748 /* WebKit.framework */; }; 17 | C6EFB2231DD48AFA00C25748 /* index.html in Resources */ = {isa = PBXBuildFile; fileRef = C6EFB2221DD48AFA00C25748 /* index.html */; }; 18 | C6EFB2261DD48BDD00C25748 /* testJavaScript.m in Sources */ = {isa = PBXBuildFile; fileRef = C6EFB2251DD48BDD00C25748 /* testJavaScript.m */; }; 19 | C6EFB22C1DD495E800C25748 /* EasyJSWKWebView.m in Sources */ = {isa = PBXBuildFile; fileRef = C6EFB2291DD495E800C25748 /* EasyJSWKWebView.m */; }; 20 | /* End PBXBuildFile section */ 21 | 22 | /* Begin PBXFileReference section */ 23 | C6EFB1FF1DD486FB00C25748 /* EasyJSWKWebViewSample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = EasyJSWKWebViewSample.app; sourceTree = BUILT_PRODUCTS_DIR; }; 24 | C6EFB2031DD486FB00C25748 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 25 | C6EFB2051DD486FB00C25748 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 26 | C6EFB2061DD486FB00C25748 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 27 | C6EFB2081DD486FB00C25748 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; 28 | C6EFB2091DD486FB00C25748 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; 29 | C6EFB20C1DD486FB00C25748 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 30 | C6EFB20E1DD486FB00C25748 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 31 | C6EFB2111DD486FB00C25748 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 32 | C6EFB2131DD486FB00C25748 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 33 | C6EFB2201DD48A7E00C25748 /* WebKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WebKit.framework; path = System/Library/Frameworks/WebKit.framework; sourceTree = SDKROOT; }; 34 | C6EFB2221DD48AFA00C25748 /* index.html */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.html; name = index.html; path = EasyJSWKWebViewSample/index.html; sourceTree = ""; }; 35 | C6EFB2241DD48BDD00C25748 /* testJavaScript.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = testJavaScript.h; sourceTree = ""; }; 36 | C6EFB2251DD48BDD00C25748 /* testJavaScript.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = testJavaScript.m; sourceTree = ""; }; 37 | C6EFB2281DD495E800C25748 /* EasyJSWKWebView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = EasyJSWKWebView.h; sourceTree = ""; }; 38 | C6EFB2291DD495E800C25748 /* EasyJSWKWebView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = EasyJSWKWebView.m; sourceTree = ""; }; 39 | /* End PBXFileReference section */ 40 | 41 | /* Begin PBXFrameworksBuildPhase section */ 42 | C6EFB1FC1DD486FB00C25748 /* Frameworks */ = { 43 | isa = PBXFrameworksBuildPhase; 44 | buildActionMask = 2147483647; 45 | files = ( 46 | C6EFB2211DD48A7F00C25748 /* WebKit.framework in Frameworks */, 47 | ); 48 | runOnlyForDeploymentPostprocessing = 0; 49 | }; 50 | /* End PBXFrameworksBuildPhase section */ 51 | 52 | /* Begin PBXGroup section */ 53 | C6EFB1F61DD486FB00C25748 = { 54 | isa = PBXGroup; 55 | children = ( 56 | C6EFB2221DD48AFA00C25748 /* index.html */, 57 | C6EFB2201DD48A7E00C25748 /* WebKit.framework */, 58 | C6EFB2011DD486FB00C25748 /* EasyJSWKWebViewSample */, 59 | C6EFB2001DD486FB00C25748 /* Products */, 60 | ); 61 | sourceTree = ""; 62 | }; 63 | C6EFB2001DD486FB00C25748 /* Products */ = { 64 | isa = PBXGroup; 65 | children = ( 66 | C6EFB1FF1DD486FB00C25748 /* EasyJSWKWebViewSample.app */, 67 | ); 68 | name = Products; 69 | sourceTree = ""; 70 | }; 71 | C6EFB2011DD486FB00C25748 /* EasyJSWKWebViewSample */ = { 72 | isa = PBXGroup; 73 | children = ( 74 | C6EFB2271DD495E800C25748 /* EasyJSWKWebView */, 75 | C6EFB2051DD486FB00C25748 /* AppDelegate.h */, 76 | C6EFB2061DD486FB00C25748 /* AppDelegate.m */, 77 | C6EFB2251DD48BDD00C25748 /* testJavaScript.m */, 78 | C6EFB2241DD48BDD00C25748 /* testJavaScript.h */, 79 | C6EFB2081DD486FB00C25748 /* ViewController.h */, 80 | C6EFB2091DD486FB00C25748 /* ViewController.m */, 81 | C6EFB20B1DD486FB00C25748 /* Main.storyboard */, 82 | C6EFB20E1DD486FB00C25748 /* Assets.xcassets */, 83 | C6EFB2101DD486FB00C25748 /* LaunchScreen.storyboard */, 84 | C6EFB2131DD486FB00C25748 /* Info.plist */, 85 | C6EFB2021DD486FB00C25748 /* Supporting Files */, 86 | ); 87 | path = EasyJSWKWebViewSample; 88 | sourceTree = ""; 89 | }; 90 | C6EFB2021DD486FB00C25748 /* Supporting Files */ = { 91 | isa = PBXGroup; 92 | children = ( 93 | C6EFB2031DD486FB00C25748 /* main.m */, 94 | ); 95 | name = "Supporting Files"; 96 | sourceTree = ""; 97 | }; 98 | C6EFB2271DD495E800C25748 /* EasyJSWKWebView */ = { 99 | isa = PBXGroup; 100 | children = ( 101 | C6EFB2281DD495E800C25748 /* EasyJSWKWebView.h */, 102 | C6EFB2291DD495E800C25748 /* EasyJSWKWebView.m */, 103 | ); 104 | path = EasyJSWKWebView; 105 | sourceTree = ""; 106 | }; 107 | /* End PBXGroup section */ 108 | 109 | /* Begin PBXNativeTarget section */ 110 | C6EFB1FE1DD486FB00C25748 /* EasyJSWKWebViewSample */ = { 111 | isa = PBXNativeTarget; 112 | buildConfigurationList = C6EFB2161DD486FB00C25748 /* Build configuration list for PBXNativeTarget "EasyJSWKWebViewSample" */; 113 | buildPhases = ( 114 | C6EFB1FB1DD486FB00C25748 /* Sources */, 115 | C6EFB1FC1DD486FB00C25748 /* Frameworks */, 116 | C6EFB1FD1DD486FB00C25748 /* Resources */, 117 | ); 118 | buildRules = ( 119 | ); 120 | dependencies = ( 121 | ); 122 | name = EasyJSWKWebViewSample; 123 | productName = EasyJSWKWebViewSample; 124 | productReference = C6EFB1FF1DD486FB00C25748 /* EasyJSWKWebViewSample.app */; 125 | productType = "com.apple.product-type.application"; 126 | }; 127 | /* End PBXNativeTarget section */ 128 | 129 | /* Begin PBXProject section */ 130 | C6EFB1F71DD486FB00C25748 /* Project object */ = { 131 | isa = PBXProject; 132 | attributes = { 133 | LastUpgradeCheck = 0720; 134 | ORGANIZATIONNAME = mr.cao; 135 | TargetAttributes = { 136 | C6EFB1FE1DD486FB00C25748 = { 137 | CreatedOnToolsVersion = 7.2.1; 138 | }; 139 | }; 140 | }; 141 | buildConfigurationList = C6EFB1FA1DD486FB00C25748 /* Build configuration list for PBXProject "EasyJSWKWebViewSample" */; 142 | compatibilityVersion = "Xcode 3.2"; 143 | developmentRegion = English; 144 | hasScannedForEncodings = 0; 145 | knownRegions = ( 146 | en, 147 | Base, 148 | ); 149 | mainGroup = C6EFB1F61DD486FB00C25748; 150 | productRefGroup = C6EFB2001DD486FB00C25748 /* Products */; 151 | projectDirPath = ""; 152 | projectRoot = ""; 153 | targets = ( 154 | C6EFB1FE1DD486FB00C25748 /* EasyJSWKWebViewSample */, 155 | ); 156 | }; 157 | /* End PBXProject section */ 158 | 159 | /* Begin PBXResourcesBuildPhase section */ 160 | C6EFB1FD1DD486FB00C25748 /* Resources */ = { 161 | isa = PBXResourcesBuildPhase; 162 | buildActionMask = 2147483647; 163 | files = ( 164 | C6EFB2121DD486FB00C25748 /* LaunchScreen.storyboard in Resources */, 165 | C6EFB2231DD48AFA00C25748 /* index.html in Resources */, 166 | C6EFB20F1DD486FB00C25748 /* Assets.xcassets in Resources */, 167 | C6EFB20D1DD486FB00C25748 /* Main.storyboard in Resources */, 168 | ); 169 | runOnlyForDeploymentPostprocessing = 0; 170 | }; 171 | /* End PBXResourcesBuildPhase section */ 172 | 173 | /* Begin PBXSourcesBuildPhase section */ 174 | C6EFB1FB1DD486FB00C25748 /* Sources */ = { 175 | isa = PBXSourcesBuildPhase; 176 | buildActionMask = 2147483647; 177 | files = ( 178 | C6EFB22C1DD495E800C25748 /* EasyJSWKWebView.m in Sources */, 179 | C6EFB20A1DD486FB00C25748 /* ViewController.m in Sources */, 180 | C6EFB2071DD486FB00C25748 /* AppDelegate.m in Sources */, 181 | C6EFB2261DD48BDD00C25748 /* testJavaScript.m in Sources */, 182 | C6EFB2041DD486FB00C25748 /* main.m in Sources */, 183 | ); 184 | runOnlyForDeploymentPostprocessing = 0; 185 | }; 186 | /* End PBXSourcesBuildPhase section */ 187 | 188 | /* Begin PBXVariantGroup section */ 189 | C6EFB20B1DD486FB00C25748 /* Main.storyboard */ = { 190 | isa = PBXVariantGroup; 191 | children = ( 192 | C6EFB20C1DD486FB00C25748 /* Base */, 193 | ); 194 | name = Main.storyboard; 195 | sourceTree = ""; 196 | }; 197 | C6EFB2101DD486FB00C25748 /* LaunchScreen.storyboard */ = { 198 | isa = PBXVariantGroup; 199 | children = ( 200 | C6EFB2111DD486FB00C25748 /* Base */, 201 | ); 202 | name = LaunchScreen.storyboard; 203 | sourceTree = ""; 204 | }; 205 | /* End PBXVariantGroup section */ 206 | 207 | /* Begin XCBuildConfiguration section */ 208 | C6EFB2141DD486FB00C25748 /* Debug */ = { 209 | isa = XCBuildConfiguration; 210 | buildSettings = { 211 | ALWAYS_SEARCH_USER_PATHS = NO; 212 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 213 | CLANG_CXX_LIBRARY = "libc++"; 214 | CLANG_ENABLE_MODULES = YES; 215 | CLANG_ENABLE_OBJC_ARC = YES; 216 | CLANG_WARN_BOOL_CONVERSION = YES; 217 | CLANG_WARN_CONSTANT_CONVERSION = YES; 218 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 219 | CLANG_WARN_EMPTY_BODY = YES; 220 | CLANG_WARN_ENUM_CONVERSION = YES; 221 | CLANG_WARN_INT_CONVERSION = YES; 222 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 223 | CLANG_WARN_UNREACHABLE_CODE = YES; 224 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 225 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 226 | COPY_PHASE_STRIP = NO; 227 | DEBUG_INFORMATION_FORMAT = dwarf; 228 | ENABLE_STRICT_OBJC_MSGSEND = YES; 229 | ENABLE_TESTABILITY = YES; 230 | GCC_C_LANGUAGE_STANDARD = gnu99; 231 | GCC_DYNAMIC_NO_PIC = NO; 232 | GCC_NO_COMMON_BLOCKS = YES; 233 | GCC_OPTIMIZATION_LEVEL = 0; 234 | GCC_PREPROCESSOR_DEFINITIONS = ( 235 | "DEBUG=1", 236 | "$(inherited)", 237 | ); 238 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 239 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 240 | GCC_WARN_UNDECLARED_SELECTOR = YES; 241 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 242 | GCC_WARN_UNUSED_FUNCTION = YES; 243 | GCC_WARN_UNUSED_VARIABLE = YES; 244 | IPHONEOS_DEPLOYMENT_TARGET = 9.2; 245 | MTL_ENABLE_DEBUG_INFO = YES; 246 | ONLY_ACTIVE_ARCH = YES; 247 | SDKROOT = iphoneos; 248 | TARGETED_DEVICE_FAMILY = "1,2"; 249 | }; 250 | name = Debug; 251 | }; 252 | C6EFB2151DD486FB00C25748 /* Release */ = { 253 | isa = XCBuildConfiguration; 254 | buildSettings = { 255 | ALWAYS_SEARCH_USER_PATHS = NO; 256 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; 257 | CLANG_CXX_LIBRARY = "libc++"; 258 | CLANG_ENABLE_MODULES = YES; 259 | CLANG_ENABLE_OBJC_ARC = YES; 260 | CLANG_WARN_BOOL_CONVERSION = YES; 261 | CLANG_WARN_CONSTANT_CONVERSION = YES; 262 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 263 | CLANG_WARN_EMPTY_BODY = YES; 264 | CLANG_WARN_ENUM_CONVERSION = YES; 265 | CLANG_WARN_INT_CONVERSION = YES; 266 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 267 | CLANG_WARN_UNREACHABLE_CODE = YES; 268 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 269 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; 270 | COPY_PHASE_STRIP = NO; 271 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 272 | ENABLE_NS_ASSERTIONS = NO; 273 | ENABLE_STRICT_OBJC_MSGSEND = YES; 274 | GCC_C_LANGUAGE_STANDARD = gnu99; 275 | GCC_NO_COMMON_BLOCKS = YES; 276 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 277 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 278 | GCC_WARN_UNDECLARED_SELECTOR = YES; 279 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 280 | GCC_WARN_UNUSED_FUNCTION = YES; 281 | GCC_WARN_UNUSED_VARIABLE = YES; 282 | IPHONEOS_DEPLOYMENT_TARGET = 9.2; 283 | MTL_ENABLE_DEBUG_INFO = NO; 284 | SDKROOT = iphoneos; 285 | TARGETED_DEVICE_FAMILY = "1,2"; 286 | VALIDATE_PRODUCT = YES; 287 | }; 288 | name = Release; 289 | }; 290 | C6EFB2171DD486FB00C25748 /* Debug */ = { 291 | isa = XCBuildConfiguration; 292 | buildSettings = { 293 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 294 | INFOPLIST_FILE = EasyJSWKWebViewSample/Info.plist; 295 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 296 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 297 | PRODUCT_BUNDLE_IDENTIFIER = com.Het.EasyJSWKWebViewSample; 298 | PRODUCT_NAME = "$(TARGET_NAME)"; 299 | }; 300 | name = Debug; 301 | }; 302 | C6EFB2181DD486FB00C25748 /* Release */ = { 303 | isa = XCBuildConfiguration; 304 | buildSettings = { 305 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 306 | INFOPLIST_FILE = EasyJSWKWebViewSample/Info.plist; 307 | IPHONEOS_DEPLOYMENT_TARGET = 8.0; 308 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 309 | PRODUCT_BUNDLE_IDENTIFIER = com.Het.EasyJSWKWebViewSample; 310 | PRODUCT_NAME = "$(TARGET_NAME)"; 311 | }; 312 | name = Release; 313 | }; 314 | /* End XCBuildConfiguration section */ 315 | 316 | /* Begin XCConfigurationList section */ 317 | C6EFB1FA1DD486FB00C25748 /* Build configuration list for PBXProject "EasyJSWKWebViewSample" */ = { 318 | isa = XCConfigurationList; 319 | buildConfigurations = ( 320 | C6EFB2141DD486FB00C25748 /* Debug */, 321 | C6EFB2151DD486FB00C25748 /* Release */, 322 | ); 323 | defaultConfigurationIsVisible = 0; 324 | defaultConfigurationName = Release; 325 | }; 326 | C6EFB2161DD486FB00C25748 /* Build configuration list for PBXNativeTarget "EasyJSWKWebViewSample" */ = { 327 | isa = XCConfigurationList; 328 | buildConfigurations = ( 329 | C6EFB2171DD486FB00C25748 /* Debug */, 330 | C6EFB2181DD486FB00C25748 /* Release */, 331 | ); 332 | defaultConfigurationIsVisible = 0; 333 | defaultConfigurationName = Release; 334 | }; 335 | /* End XCConfigurationList section */ 336 | }; 337 | rootObject = C6EFB1F71DD486FB00C25748 /* Project object */; 338 | } 339 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample.xcodeproj/project.xcworkspace/xcuserdata/mrcao.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrcao2011/EasyJSWKWebView/e03c7e786f2840050ec845efe95986a362d81c06/EasyJSWKWebViewSample.xcodeproj/project.xcworkspace/xcuserdata/mrcao.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /EasyJSWKWebViewSample.xcodeproj/xcuserdata/mrcao.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample.xcodeproj/xcuserdata/mrcao.xcuserdatad/xcschemes/EasyJSWKWebViewSample.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 32 | 33 | 39 | 40 | 41 | 42 | 43 | 44 | 54 | 56 | 62 | 63 | 64 | 65 | 66 | 67 | 73 | 75 | 81 | 82 | 83 | 84 | 86 | 87 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample.xcodeproj/xcuserdata/mrcao.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | EasyJSWKWebViewSample.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | SuppressBuildableAutocreation 14 | 15 | C6EFB1FE1DD486FB00C25748 16 | 17 | primary 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mrcao2011/EasyJSWKWebView/e03c7e786f2840050ec845efe95986a362d81c06/EasyJSWKWebViewSample/.DS_Store -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | 11 | @interface AppDelegate () 12 | 13 | @end 14 | 15 | @implementation AppDelegate 16 | 17 | 18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 19 | // Override point for customization after application launch. 20 | return YES; 21 | } 22 | 23 | - (void)applicationWillResignActive:(UIApplication *)application { 24 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 25 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 26 | } 27 | 28 | - (void)applicationDidEnterBackground:(UIApplication *)application { 29 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 30 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 31 | } 32 | 33 | - (void)applicationWillEnterForeground:(UIApplication *)application { 34 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. 35 | } 36 | 37 | - (void)applicationDidBecomeActive:(UIApplication *)application { 38 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 39 | } 40 | 41 | - (void)applicationWillTerminate:(UIApplication *)application { 42 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 43 | } 44 | 45 | @end 46 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "29x29", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "29x29", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "40x40", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "40x40", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "60x60", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "60x60", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "ipad", 35 | "size" : "29x29", 36 | "scale" : "1x" 37 | }, 38 | { 39 | "idiom" : "ipad", 40 | "size" : "29x29", 41 | "scale" : "2x" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "size" : "40x40", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "size" : "40x40", 51 | "scale" : "2x" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "size" : "76x76", 56 | "scale" : "1x" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "size" : "76x76", 61 | "scale" : "2x" 62 | } 63 | ], 64 | "info" : { 65 | "version" : 1, 66 | "author" : "xcode" 67 | } 68 | } -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/EasyJSWKWebView/EasyJSWKWebView.h: -------------------------------------------------------------------------------- 1 | // 2 | // EasyJSWKWebView.h 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface EasyJSWKWebView : WKWebView 12 | 13 | 14 | /** 15 | * 16 | * 17 | * @param interface 18 | * @param name js对象名字 19 | */ 20 | - (void) addJavascriptInterfaces:(NSObject*) interface WithJSObjName:(NSString*) name; 21 | 22 | @end 23 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/EasyJSWKWebView/EasyJSWKWebView.m: -------------------------------------------------------------------------------- 1 | // 2 | // EasyJSWKWebView.m 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import "EasyJSWKWebView.h" 10 | #import 11 | 12 | NSString* INJECT_JS = @"window.EasyJS = {\ 13 | \ 14 | call: function (obj, functionName, args){\ 15 | var formattedArgs = [];\ 16 | for (var i = 0, l = args.length; i < l; i++){\ 17 | formattedArgs.push(encodeURIComponent(args[i]));\ 18 | }\ 19 | \ 20 | var argStr = (formattedArgs.length > 0 ? \":\" + encodeURIComponent(formattedArgs.join(\":\")) : \"\");\ 21 | \ 22 | window.webkit.messageHandlers[obj].postMessage(obj + \":\" + encodeURIComponent(functionName) + argStr);\ 23 | \ 24 | },\ 25 | \ 26 | inject: function (obj, methods){\ 27 | window[obj] = {};\ 28 | var jsObj = window[obj];\ 29 | \ 30 | for (var i = 0, l = methods.length; i < l; i++){\ 31 | (function (){\ 32 | var method = methods[i];\ 33 | var jsMethod = method.replace(new RegExp(\":\", \"g\"), \"\");\ 34 | jsObj[jsMethod] = function (){\ 35 | return EasyJS.call(obj, method, Array.prototype.slice.call(arguments));\ 36 | };\ 37 | })();\ 38 | }\ 39 | }\ 40 | };"; 41 | 42 | @interface EasyJSWKWebView() 43 | 44 | @property (nonatomic,strong)NSMutableDictionary *javascriptInterfaces; 45 | 46 | @end 47 | 48 | @implementation EasyJSWKWebView 49 | - (void) addJavascriptInterfaces:(NSObject*) interface WithJSObjName:(NSString*) name{ 50 | if (! self.javascriptInterfaces){ 51 | self.javascriptInterfaces = [[NSMutableDictionary alloc] init]; 52 | } 53 | 54 | [self.javascriptInterfaces setValue:interface forKey:name]; 55 | // 注入JS对象interface 56 | WKUserContentController *userContentController = self.configuration.userContentController; 57 | if (!userContentController) { 58 | userContentController = [[WKUserContentController alloc]init]; 59 | } 60 | WKUserScript *script1 = [[WKUserScript alloc] initWithSource:INJECT_JS injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]; 61 | [userContentController addUserScript:script1]; 62 | 63 | NSMutableString* injection = [NSMutableString new]; 64 | //inject the javascript interface 65 | [injection appendString:@"EasyJS.inject(\""]; 66 | [injection appendString:name]; 67 | [injection appendString:@"\", ["]; 68 | 69 | unsigned int mc = 0; 70 | Class cls = object_getClass(interface); 71 | Method * mlist = class_copyMethodList(cls, &mc); 72 | for (int i = 0; i < mc; i++){ 73 | [injection appendString:@"\""]; 74 | [injection appendString:[NSString stringWithUTF8String:sel_getName(method_getName(mlist[i]))]]; 75 | [injection appendString:@"\""]; 76 | 77 | if (i != mc - 1){ 78 | [injection appendString:@", "]; 79 | } 80 | } 81 | 82 | free(mlist); 83 | 84 | [injection appendString:@"]);"]; 85 | 86 | WKUserScript *script2 = [[WKUserScript alloc] initWithSource:injection injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]; 87 | [userContentController addUserScript:script2]; 88 | // 声明WKScriptMessageHandler 协议 89 | [userContentController addScriptMessageHandler:self name:name]; 90 | self.configuration.userContentController=userContentController; 91 | 92 | } 93 | 94 | - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { 95 | 96 | NSArray *components = [message.body componentsSeparatedByString:@":"]; 97 | 98 | NSString* obj = (NSString*)[components objectAtIndex:0]; 99 | NSString* method = [(NSString*)[components objectAtIndex:1] 100 | stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 101 | 102 | NSObject* interface = [self.javascriptInterfaces objectForKey:obj]; 103 | if(!interface) 104 | { 105 | return; 106 | } 107 | // execute the interfacing method 108 | SEL selector = NSSelectorFromString(method); 109 | NSMethodSignature* sig = [[interface class] instanceMethodSignatureForSelector:selector]; 110 | NSInvocation* invoker = [NSInvocation invocationWithMethodSignature:sig]; 111 | invoker.selector = selector; 112 | invoker.target = interface; 113 | 114 | if ([components count] > 2){ 115 | NSString *argsAsString = [(NSString*)[components objectAtIndex:2] 116 | stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 117 | 118 | NSArray* formattedArgs = [argsAsString componentsSeparatedByString:@":"]; 119 | for (int i = 0; i < [formattedArgs count]; i++){ 120 | NSString* argStr = ((NSString*) [formattedArgs objectAtIndex:i ]); 121 | 122 | NSString* arg = [argStr stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 123 | [invoker setArgument:&arg atIndex:(i + 2)]; 124 | 125 | } 126 | } 127 | [invoker invoke]; 128 | 129 | 130 | } 131 | 132 | @end 133 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | LSRequiresIPhoneOS 24 | 25 | UILaunchStoryboardName 26 | LaunchScreen 27 | UIMainStoryboardFile 28 | Main 29 | UIRequiredDeviceCapabilities 30 | 31 | armv7 32 | 33 | UISupportedInterfaceOrientations 34 | 35 | UIInterfaceOrientationPortrait 36 | UIInterfaceOrientationLandscapeLeft 37 | UIInterfaceOrientationLandscapeRight 38 | 39 | UISupportedInterfaceOrientations~ipad 40 | 41 | UIInterfaceOrientationPortrait 42 | UIInterfaceOrientationPortraitUpsideDown 43 | UIInterfaceOrientationLandscapeLeft 44 | UIInterfaceOrientationLandscapeRight 45 | 46 | 47 | 48 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | #import "EasyJSWKWebView.h" 11 | #import "testJavaScript.h" 12 | 13 | @interface ViewController () 14 | { 15 | EasyJSWKWebView *_webView; 16 | } 17 | 18 | @end 19 | 20 | @implementation ViewController 21 | 22 | - (void)viewDidLoad { 23 | [super viewDidLoad]; 24 | // Do any additional setup after loading the view, typically from a nib. 25 | _webView = [[EasyJSWKWebView alloc] initWithFrame:CGRectMake(0,0, 26 | self.view.frame.size.width, 27 | self.view.frame.size.height)]; 28 | 29 | _webView.backgroundColor = [UIColor clearColor]; 30 | _webView.clipsToBounds = YES; 31 | [self.view addSubview:_webView]; 32 | NSString *path=[[NSBundle mainBundle]pathForResource:@"index" ofType:@"html"]; 33 | NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path] 34 | cachePolicy:NSURLRequestReloadIgnoringLocalCacheData 35 | timeoutInterval:60.0]; 36 | [_webView loadRequest:request]; 37 | testJavaScript* bridge = [[testJavaScript alloc]init]; 38 | [_webView addJavascriptInterfaces:bridge WithJSObjName:@"testJavaScript"]; 39 | bridge.ocCallJSBolck=^() 40 | { 41 | [_webView evaluateJavaScript:[NSString stringWithFormat:@"OCCallJS('%@')",@"厉害了world哥"]completionHandler:nil]; 42 | 43 | }; 44 | bridge.jsCallOCBolck=^() 45 | { 46 | UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"js调用oc" message:nil delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定",nil]; 47 | [alertView show]; 48 | }; 49 | } 50 | 51 | 52 | - (void)didReceiveMemoryWarning { 53 | [super didReceiveMemoryWarning]; 54 | // Dispose of any resources that can be recreated. 55 | } 56 | 57 | @end 58 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/index.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | JS与OC互调 13 | 14 | 32 | 33 | 34 | 35 | 36 |
37 | 38 |
39 |
40 | 41 | 42 | 44 | 45 | 46 |
47 | 48 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/testJavaScript.h: -------------------------------------------------------------------------------- 1 | // 2 | // testJavaScript.h 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | typedef void (^OCCallJSBolck)(); 12 | typedef void (^JSCallOCBolck)(); 13 | @interface testJavaScript : NSObject 14 | 15 | @property(copy,nonatomic)OCCallJSBolck ocCallJSBolck; 16 | @property(copy,nonatomic)JSCallOCBolck jsCallOCBolck; 17 | @end 18 | -------------------------------------------------------------------------------- /EasyJSWKWebViewSample/testJavaScript.m: -------------------------------------------------------------------------------- 1 | // 2 | // testJavaScript.m 3 | // EasyJSWKWebViewSample 4 | // 5 | // Created by mr.cao on 16/11/10. 6 | // Copyright © 2016年 mr.cao. All rights reserved. 7 | // 8 | 9 | #import "testJavaScript.h" 10 | 11 | @implementation testJavaScript 12 | 13 | -(void)JSCallOC 14 | { 15 | if(self.jsCallOCBolck) 16 | { 17 | self.jsCallOCBolck(); 18 | } 19 | 20 | 21 | } 22 | 23 | -(void)OCCallJS 24 | { 25 | if(self.ocCallJSBolck) 26 | { 27 | self.ocCallJSBolck(); 28 | } 29 | } 30 | @end 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EasyJSWKWebView 2 | 3 | Enable adding Javascript Interface to WKWebView like Android WebView 4 | 5 | 6 | 类似与Android WebView,注册本地类对象和JS中类对象名称的方式实现Javascript与WKWebView的交互,基于[EasyJSWebView(UIWebView)](https://github.com/dukeland/EasyJSWebView)移植到WKWebView 7 | 8 | ###JS调用Objective-C 9 | 10 | 首先创建个类,类实例方法需要与js端方法名称保持一致 11 | ```objc 12 | #import "testJavaScript.h" 13 | 14 | @implementation testJavaScript 15 | 16 | -(void)JSCallOC 17 | { 18 | 19 | } 20 | 21 | -(void)OCCallJS 22 | { 23 | 24 | } 25 | @end 26 | ``` 27 | 28 | 注册类对象给WKWebview 29 | 30 | ```objc 31 | 32 | testJavaScript* bridge = [[testJavaScript alloc]init]; 33 | 34 | [_webView addJavascriptInterfaces:bridge WithJSObjName:@"testJavaScript"]; 35 | 36 | ``` 37 | 38 | 在JS代码里面,调用Objective-C方法: 39 | 40 | ```javascript 41 | window.testJavaScript.JSCallOC(); 42 | ``` 43 | 44 | 45 | ###Objective-C调用JS 46 | 47 | 直接调用WKWebView API 48 | ```objc 49 | - (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ __nullable)(__nullable id, NSError * __nullable error))completionHandler; 50 | ``` 51 | 即可 52 | 53 | 54 | 例如: 55 | 56 | ```objc 57 | [_webView evaluateJavaScript:[NSString stringWithFormat:@"OCCallJS('%@')",@"厉害了world哥"]completionHandler:nil]; 58 | ``` 59 | 60 | 具体代码请参考工程代码 --------------------------------------------------------------------------------