需求:
需要在手機端用WKWebView加載鏈接展示html,並且需要與html中按鈕做交互
實現:
#import "ViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController ()<WKScriptMessageHandler,WKNavigationDelegate>
@property(nonatomic,strong) WKWebView *webView ;
@end
static NSString *strID = @"pullnewactive";
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = self.titleName;
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
//strID: H5界面的標識符
WKUserContentController * wkUController = [[WKUserContentController alloc] init];
[wkUController addScriptMessageHandler:self name:strID];
config.userContentController = wkUController;
//創建WKWebView
self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) configuration:config];
self.webView.navigationDelegate = self;
[self.view addSubview:self.webView];
//加載url
NSURL * baseUrl = [NSURL URLWithString:self.urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:baseUrl];
[_webView loadRequest:request];
}
#pragma mark ------------ WKScriptMessageHandler --------
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
// NSDictionary * parameter = message.body; 如果帶參數可以從parameter獲取
if([message.name isEqualToString:strID]){//點擊按鈕執行的方法
}
}
#pragma mark ------------ WKNavigationDelegate ------------
//WKWebView自帶可以長按保存圖片,加上下面代碼,可以取消長按保存圖片
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
//禁止保存圖片
[self.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none'" completionHandler:nil];
[self.webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none'" completionHandler:nil];
}
//移除註冊的js方法(注意需要移除)
-(void)dealloc{
[[_webView configuration].userContentController removeScriptMessageHandlerForName:strID];
}
//如果H5界面有電話需要添加,撥打電話時調用
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSURL *URL = navigationAction.request.URL;
NSString *scheme = [URL scheme];
if ([scheme isEqualToString:@"tel"]) {
NSString *resourceSpecifier = [URL resourceSpecifier];
NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
/// 防止iOS 10及其之後,撥打電話系統彈出框延遲出現
dispatch_async(dispatch_get_global_queue(0, 0), ^{
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
});
}
decisionHandler(WKNavigationActionPolicyAllow);
}
HTML中需要在按鈕點擊事件中實現:
//不帶參數 (pullnewactive)標識符
function jsToOcFunction1(){
window.webkit.messageHandlers.pullnewactive.postMessage({});
}
//帶參數 (jsToOcWithPrams)標識符
function jsToOcFunction2(){
window.webkit.messageHandlers.jsToOcWithPrams.postMessage({"params":"我是參數"});
}