直接上代碼
JS調(diào)OC
OC中的實現(xiàn)
1.創(chuàng)建一個WKWebViewConfiguration
WKWebViewConfiguration 是用來配置WKWebView的
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = [WKUserContentController new];
// 注冊一個處理事件 參數(shù)1:誰來響應(yīng)這個操作事件(類似于代理恕刘,遵守 WKScriptMessageHandler 協(xié)議) 參數(shù)2: 操作唯一標(biāo)識符
//[configuration.userContentController addScriptMessageHandler:self name:@"操作的唯一標(biāo)識"];
[configuration.userContentController addScriptMessageHandler:self name:@"testAction"];
2.創(chuàng)建一個WKWebView 與 WKWebViewConfiguration關(guān)聯(lián)起來
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
self.webView.backgroundColor = [UIColor whiteColor];
[self.webView loadRequest:[NSURLRequest requestWithURL:@"........."]];
[self.view addSubview:self.webView];
- 實現(xiàn) WKScriptMessageHandler 協(xié)議中的 userContentController: didReceiveScriptMessage 方法來監(jiān)聽上述配置中的操作事件
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSLog(@"%@",message.name); // 注冊操作事件時的唯一標(biāo)示符
NSLog(@"%@",message.body); // JS返回回來的數(shù)據(jù)
// 判定name來決定是哪個操作事件
if([message.name isEqualToString:@"testAction"]){
NSLog(@"testAction")
}
}
4.使用結(jié)束后 確定該標(biāo)識不需要用 需要刪除 要不然會強引用
[configuration.userContentController removeScriptMessageHandlerForName:@"testAction"];
Swift
let configuration = WKWebViewConfiguration()
configuration.userContentController = WKUserContentController()
configuration.userContentController.add(self, name: "testAction")
self.webView = WKWebView.init(frame: self.view.bounds, configuration: configuration)
self.view.addSubview(self.webView)
let url = URL(string: "----")!
self.webView.load(URLRequest(url: url))
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message.name)
print(message.body)
}
使用結(jié)束同樣需要刪除
configuration.userContentController.removeScriptMessageHandler(forName: "testAction")
同樣也是要遵守協(xié)議 WKScriptMessageHandler
JS中的實現(xiàn)
在哪里需要調(diào)用OC 那么就在哪個函數(shù)中調(diào)用
例:
<script>
function testAction() {
<!--window.webkit.messageHandlers.方法名(與注冊的一致(message.name) ).postMessage(JS傳下來的數(shù)據(jù)(message.body))-->
<!--data 可以是數(shù)組 字典 json字符串.....-->
window.webkit.messageHandlers.testAction.postMessage(data)
}
</script>
OC調(diào)JS
OC中的實現(xiàn)
WKWebView中直接有方法可以調(diào)用
// 字符串內(nèi)容為:JS中的方法名(參數(shù)) 參數(shù)可以是數(shù)組 字典 json字符串
NSString *jsStr = [NSString stringWithFormat:@"showResult('10086')"];
[self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"%@----%@",result, error);
}];
Swift
let arr = ["1","2","3"]
let js = "showResult(\(arr))"
self.webView.evaluateJavaScript(js, completionHandler: { (result, error) in
print(result ?? "nil",error ?? "nil")
})
completionHandler 會調(diào)中的 result 是js方法的返回值 (result是個 id / Any 類型,也就是說js中可以返回任意值)
JS中的實現(xiàn)
<script>
function showResult(result) {
alert(result)
return "hello,word"
}
</script>
其他
關(guān)于 JS中的alert彈框在WKWebView中無法彈出
原生的alert彈框在WK上面無法彈出
解決方法 :
1. 不使用原生的alert, 自定義一個彈框
2. 遵守WKUIDelegate 實現(xiàn)WKWebView的UIDelegate
// 顯示一個按鈕。點擊后調(diào)用completionHandler回調(diào)
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"確認(rèn)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
// 顯示兩個按鈕,通過completionHandler回調(diào)判斷用戶點擊的確定還是取消按鈕
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler(NO);
}])];
[alertController addAction:([UIAlertAction actionWithTitle:@"確認(rèn)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(YES);
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
// 顯示一個帶有輸入框和一個確定按鈕的,通過completionHandler回調(diào)用戶輸入的內(nèi)容
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.text = defaultText;
}];
[alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(alertController.textFields[0].text?:@"");
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
相當(dāng)于是系統(tǒng)在檢測到alert彈框時镐侯,會調(diào)用這些代理方法,然后通過代理方法把對應(yīng)參數(shù)告訴我們,我們自己實現(xiàn)alert方法來彈框
關(guān)于 JS中的select下拉框在WKWebView中的顯示樣式
js 中 select 下拉框在不同的瀏覽器顯示的樣式就不一樣拗军,在WKWebView中會已UIPickerView的形式展示,如果無法滿足需求蓄喇,需要自定義下拉框