在WKWebView中注入js代碼,從而實(shí)現(xiàn)改變js事件實(shí)現(xiàn)方法诈茧。
比如,在H5頁面中有一個打印按鈕捂掰,iOS 端沒有打印功能敢会,這時就要提示用戶不能使用此功能
主要代碼
// printFrame js打印事件
- (void)createWebView {
// js配置
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
// WKWebView的配置
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = userContentController;
// 顯示W(wǎng)KWebView
self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, self.hideNavigationBar?kStatusH:0, ScreenWidth, self.hideNavigationBar?ScreenHeight-kStatusH:ScreenHeight-NavitionbarHeight) configuration:configuration];
self.webView.UIDelegate = self; // 設(shè)置WKUIDelegate代理
self.webView.navigationDelegate = self;
[self.view addSubview:self.webView];
configuration.userContentController = userContentController;
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"printLog"];//js打印事件
//注入js的代碼,就相當(dāng)于重寫了js的printLog方法这嚣,在printLog方法中去調(diào)用原生方法
// function 后面的方法名跟js代碼中的方法名要一致
NSString *printContent = @"function printLog() {
//此處的printLog 可自己定義但是要跟上面的addScriptMessageHandler 的name保持一致
window.webkit.messageHandlers.printLog.postMessage(null);}
";
WKUserScript *userScript = [[WKUserScript alloc] initWithSource:printContent injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[self.webView.configuration.userContentController addUserScript:userScript];
}
//js調(diào)用打印方法時就會調(diào)用此方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"%@",message);
NSLog(@"%@",message.body);
NSLog(@"%@",message.name);
if ([@"printLog" isEqualToString:message.name]) {
[self printLog:@"jjj"];
}
}
- (void) printLog:(NSString *)hhh {
//重新實(shí)現(xiàn)js方法
}