iOS开发技巧之:JS调用WKWebview(简单)


- (void)setupWebView {
    WKUserContentController *userContent = [[WKUserContentController alloc] init];
    ALYJSHandler *jsHandler = [[ALYJSHandler alloc] init];
    [userContent addScriptMessageHandler:jsHandler name:@"jsObj"];
    
    WKWebViewConfiguration *configer = [[WKWebViewConfiguration alloc] init];
    
    NSString *js = @"\
        var jsObj = new Object();\
        jsObj.notify = function(event,session,data){\
            window.webkit.messageHandlers.jsObj.postMessage({'event':event, 'session':session, 'data':data});\
        }";
    
    WKUserScript *userScript = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
    [userContent addUserScript:userScript];

    configer.userContentController = userContent;
    configer.preferences = [[WKPreferences alloc] init];
    configer.preferences.javaScriptEnabled = YES;
    configer.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    configer.allowsInlineMediaPlayback = YES;
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) configuration:configer];
    [self setWebViewUA];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:URL_BOARD]]];
    [self.view addSubview:self.webView];
}

js端调用如下

jsObj.notify('a','b','c')

oc调用如下

[self.webView evaluateJavaScript:@"jsObj.notify('a','b','c')" completionHandler:nil];

说明: native主动声明js的一个全局变量,并实现注入js的函数,即可正常调用了。

你可能感兴趣的:(iOS开发技巧之:JS调用WKWebview(简单))