JS intercalls under UIWebView

1. Js calls native

Inject native objects into JS

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    JSContext *context=[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    jsSDK *jssdk = [jsSDK new];
    jssdk.delegate = self;
    context[@"jsSDK"] = jssdk;
}
Copy the code

The injected jsSDK needs to comply with the JSExport protocol

JsSDK agent in the implementation of the need for specific methods

@protocol jsSDKDelegate <JSExport>

- (void)previewImages:(NSString *)url position:(int)position;
- (void)previewImages;

@end

@interface jsSDK : NSObject <jsSDKDelegate>

@property(nonatomic,weak) id<jsSDKDelegate> delegate;

@end
Copy the code
Id args = [JSContext currentArguments]; NSArray *argArr = args; // There must be more than two arguments, so there is a judgment to modify the core code according to the actual situation is to parse out the arguments passedif (argArr.count < 2) {
        return;
    }
    JSValue *url = argArr[0];
    NSString *urlStr = [url toString];
    
    JSValue *positionJSValue = argArr[1];
    int position = [[positionJSValue toString] intValue];
    
    [self.delegate previewImages:urlStr position:position];
}
Copy the code

Native call JS

XxJS is a globally held class for the front end for native calls to do the same as jsSDK above.

- (void)loginSuccess
{
    JSContext *context=[self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; // No argument NSString *callBackJS = @"xxJS.loginSuccess"; // NSString *callBackJS = @"XxJS. LoginSuccess (' parameters')";
    
    [context evaluateScript:callBackJS];
}
Copy the code

JS intermodulation under WkWebView

Have no practice refer to other articles

www.jianshu.com/p/ca7eb797c…

www.jianshu.com/p/9b4f7f6d4…