OC端核心代码
#pragma mark - 初始化wkwebview并配置
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
// 设置偏好设置
config.preferences = [[WKPreferences alloc] init];
// 默认为0
config.preferences.minimumFontSize = 10;
// 默认认为YES
config.preferences.javaScriptEnabled = YES;
// 在iOS上默认为NO,表示不能自动通过窗口打开
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
// web内容处理池,由于没有属性可以设置,也没有方法可以调用,不用手动创建
config.processPool = [[WKProcessPool alloc] init];
// 通过JS与webview内容交互
config.userContentController = [[WKUserContentController alloc] init];
// 注入JS对象名称AppModel,当JS通过AppModel来调用时,
// 我们可以在WKScriptMessageHandler代理中接收到
[config.userContentController addScriptMessageHandler:self name:@"AppModel"];
// 穿件wkwebview并配置
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
// 导航代理
self.webView.navigationDelegate = self;
// 与webview UI交互代理
self.webView.UIDelegate = self;
[self.view addSubview:self.webView];
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"AppModel"]) {
// 打印所传过来的参数,只支持NSNumber, NSString, NSDate, NSArray,
// NSDictionary, and NSNull类型
NSLog(@"%@", message.body);
}
}
JS端核心代码
<script type="text/javascript">
function callJsAlert() {
alert('Objective-C call js to show alert');
window.webkit.messageHandlers.AppModel.postMessage({body: 'call js alert in js'});
}
function callJsConfirm() {
if (confirm('confirm', 'Objective-C call js to show confirm')) {
document.getElementById('jsParamFuncSpan').innerHTML
= 'true';
} else {
document.getElementById('jsParamFuncSpan').innerHTML
= 'false';
}
// AppModel是我们所注入的对象
window.webkit.messageHandlers.AppModel.postMessage({body: 'call js confirm in js'});
}
function callJsInput() {
var response = prompt('Hello', 'Please input your name:');
document.getElementById('jsParamFuncSpan').innerHTML = response;
// AppModel是我们所注入的对象
window.webkit.messageHandlers.AppModel.postMessage({body: response});
}
</script>