iOS原生与JS的交互(WKWebView)

一、JS调用原生

//注入监听js的事件

WKUserContentController *_userContentController = [[WKUserContentController alloc] init];

//    NSString *jsButtonId = @"buttonId";

NSString *jsMessage =@"UnityBack";//监听js的方法名【注:window.webkit.messageHandlers.UnityBack<这个方法名就是原生监听的方法名>.postMessage("这是js返回给原生的body")】

//给js按钮添加事件

//NSString *scriptStr = [NSString stringWithFormat:@"function fun(){window.webkit.messageHandlers.%@.postMessage(null);}(function(){var btn=document.getElementById(\"%@\");btn.addEventListener('click',fun,false);}());", jsMessage, jsButtonId];

//WKUserScript *userScript = [[WKUserScript alloc] initWithSource:scriptStr injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];

//[_userContentController addUserScript:userScript];

//webview监听js的事件【name:方法名】

[_userContentController addScriptMessageHandler:self name:jsMessage];//注:销毁时需做相应的移除操作 removeScriptMessageHandlerForName

WKWebViewConfiguration *_configuration = [[WKWebViewConfiguration alloc] init];

_configuration.userContentController = _userContentController;

WKWebView * webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:_configuration];

webView.translatesAutoresizingMaskIntoConstraints =NO;

webView.UIDelegate = self;

webView.navigationDelegate = self;

if(@available(iOS11.0, *)) {

        webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;

}

[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];

======    以上是简单的初始化方法    ========


======    以下是WKNavigationDelegate和WKScriptMessageHandler的代理方法    ========

#pragma WKNavigationDelegate 代理方法

// 页面开始加载时调用

- (void)webView:(WKWebView *)webViewdidStartProvisionalNavigation:(WKNavigation *)navigation{

    NSLog(@"页面开始加载");

}

// 当内容开始返回时调用

- (void)webView:(WKWebView *)webViewdidCommitNavigation:(WKNavigation *)navigation{

    NSLog(@"当内容开始返回时");

}

// 页面加载完成之后调用

- (void)webView:(WKWebView *)webViewdidFinishNavigation:(WKNavigation *)navigation{

    NSLog(@"页面加载完成之后");

}

// 页面加载失败时调用

- (void)webView:(WKWebView *)webViewdidFailProvisionalNavigation:(WKNavigation *)navigation{

    NSLog(@"页面加载失败");

}

/*- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    NSString *url = navigationAction.request.URL.absoluteString;

    if ([url rangeOfString:@"需要跳转源生界面的URL判断"].location != NSNotFound) {

        //跳转原生界面

        //Cancel the navigation

        decisionHandler(WKNavigationActionPolicyCancel);

        return;

    }

    /*

       a 超连接中target的意思

       _blank -- 在新窗口中打开链接

       _parent -- 在父窗体中打开链接

       _self -- 在当前窗体打开链接,此为默认值

       _top -- 在当前窗体打开链接,并替换当前的整个窗体(框架页)

*/

    //如果是跳转一个新页面需要loadRequest,否则点击网页的链接可能无反应

    if(navigationAction.targetFrame ==nil) {

           [webView loadRequest:navigationAction.request];

    }

    decisionHandler(WKNavigationActionPolicyAllow);

}*/

#pragma mark --- WKScriptMessageHandler ---

- (void)userContentController:(WKUserContentController *)userContentControllerdidReceiveScriptMessage:(WKScriptMessage *)message {

    NSLog(@"message.name:%@", message.name);

    NSLog(@"message.body:%@", message.body);//JS传过来的参数


    //TODO:根据注入js的name做想做的操作

    if([message.name isEqualToString:@"UnityBack"]){//处理js UnityBack的事件

        //TODO:

    }

}

二、原生调用JS

注入方法:- (void)evaluateJavaScript:(NSString*)javaScriptString completionHandler:(void(^ _Nullable)(_Nullableid,NSError* _Nullable error))completionHandler;

//这里需要设置js的方法名和所需传入的参数;如下:toCallJS是js的方法名

NSString*jsFunction = [NSStringstringWithFormat:@"toCallJS('%@')",AA];

[self.webView evaluateJavaScript:jsFunction completionHandler:^(id object,NSError* _Nullable error) {

    //TODO:

}];

你可能感兴趣的:(iOS原生与JS的交互(WKWebView))