加载Html代码
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
[self.view addSubview:webView];
加载的状态回调 (WKNavigationDelegate)
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation;
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation;
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation;
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation;
WKWebView图片自适应 超过屏幕宽的自适应,小于屏幕宽度的图片不放大
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
[webView evaluateJavaScript:[NSString stringWithFormat:@"var script = document.createElement('script');"
"script.type = 'text/javascript';"
"script.text = \"function ResizeImages() { "
"var myimg,oldwidth;"
"var maxwidth = %f;" //判断条件
"for(i = 0;i < document.images.length;i++){"
"myimg = document.images[i];"
"if(myimg.width > maxwidth){" //小于或者大于
"oldwidth = myimg.width;"
"myimg.width = maxwidth;"
// "myimg.height *= (maxwidth/oldwidth);" //图片高度
"}"
"}"
"}\";"
"document.getElementsByTagName('head')[0].appendChild(script);",screen_width-20] completionHandler:nil];
[webView evaluateJavaScript:@"ResizeImages();" completionHandler:nil];
}
UIWebView调用js方法
//禁用webview长按(提高用户体验)
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"]
WKWebView调用js方法 (替换方法)
[webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:nil];
[webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
网友评论