OC&&JS交互
OC调用JS
未约定好的方法 往JS上下文注入JS方法,以备OC调用
/// 往HTML 中 注入 JS代码字符串 源代码
/// @param scriptString script内容
- (void)insertScriptWithString:(NSString *)scriptSctring{
//用于进行JavaScript注入
WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:scriptSctring injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[self.webConfig.userContentController addUserScript:wkUScript];
}
已经约定好方法直接调用
WKWebView 调用JS 方法比较单一:
/// OC 调用 JS 代码
/// @param script 脚本 [NSString stringWithFormat:@"changeColor('%@')", @"Js参数"];
/// @param completionHandler 回调
- (void)OCHandleJSWithScriptString:(NSString *)script completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler{
/// OC 调 JS
[_webView evaluateJavaScript:script completionHandler:completionHandler];
}
UIWebView 使用下面的方法 OC 调用 JS
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NSString *textJS = @"showAlert('这里是JS中alert弹出的message')";
[context evaluateScript:textJS];
JS 调用OC
WKUserContentController
开启 JS交互开关 设置代理
设置代理 遵守协议 <WKScriptMessageHandler>
// 直接设置config对象中的preferences属性
_webConfig.preferences.javaScriptEnabled = YES;//打开js交互
//或者 单独设置自定义的 WKPreferences对象
_webPreference.javaScriptEnabled = YES;
// 设置交互代理
_webConfig.userContentController = self.webUserContentController;
观察JS调用OC方法
//注册一个name为jsToOcNoPrams的js方法
[_webUserContentController addScriptMessageHandler:self name:@"jsToOcNoPrams"];
[_webUserContentController addScriptMessageHandler:self name:@"jsToOcWithPrams"];
接收回调
#pragma mark ------- 交互的 delegate
/// 通过接收JS传出消息的name进行捕捉的回调方法 js调OC
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
}
移除注册
界面退出、销毁时需要一处下方法的注册!!
-(void)removeAllScriptMsgHandle{
WKUserContentController *controller = self.webView.configuration.userContentController;
[controller removeScriptMessageHandlerForName:@"jsToOcNoPrams"];
[controller removeScriptMessageHandlerForName:@"jsToOcWithPrams"];
}
scheme方式交互
遵守协议 & 设置代理
遵守协议 :<WKNavigationDelegate>
// 设置代理
_webView.navigationDelegate = self;
捕获Scheme
// 根据WebView对于即将跳转的HTTP请求头信息和相关信息来决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSLog(@"发送跳转请求:%@",urlStr);
// 根据自定义的scheme进行拦截
if ([urlStr hasPrefix:schemeHeader]) {
[ControllerUtils showViewWithURL:urlStr];
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
}