GitHub:https://github.com/1205665266/WKWebView
HTML代碼
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<script language="javascript">
//JS執(zhí)行window.webkit.messageHandlers.Share.postMessage(<messageBody>)
function shareClick() {
window.webkit.messageHandlers.Share.postMessage({title:'測試分享的標題',content:'測試分享的內(nèi)容',url:'https://github.com/maying1992'});
}
//分享回調(diào)結(jié)果顯示
function shareResult(channel_id,share_channel,share_url) {
var content = channel_id+","+share_channel+","+share_url;
alert(content);
document.getElementById("returnValue").value = content;
}
//JS執(zhí)行window.webkit.messageHandlers.Camera.postMessage(<messageBody>)
function cameraClick() {
window.webkit.messageHandlers.Camera.postMessage(null);
}
//調(diào)用相冊回調(diào)結(jié)果顯示
function cameraResult(result) {
alert(result);
document.getElementById("returnValue").value = result;
}
</script>
</head>
<body>
<h1>這是按鈕調(diào)用</h1>
<input type="button" value="分享" onclick="shareClick()" />
<input type="button" value="相機" onclick="cameraClick()" />
<h1>回調(diào)展示區(qū)</h1>
<textarea id ="returnValue" type="value" rows="5" cols="40">
</textarea>
</body>
</html>
創(chuàng)建WKWebView代碼
//
// BaseWebViewController.m
// Capp
//
// Created by apple on 2017/10/18.
// Copyright ? 2017年 apple. All rights reserved.
//
#import "BaseWebViewController.h"
#import <WebKit/WebKit.h>
@interface BaseWebViewController ()<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>
@end
@implementation BaseWebViewController
{
WKWebView *_webView;
}
- (void)dealloc {
NSLog(@"web 走了 dealloc");
//這里remove掉 添加的js標識
[[_webView configuration].userContentController removeScriptMessageHandlerForName:@"Camera"];
}
- (void)viewDidLoad {
[super viewDidLoad];
//技術(shù)文檔
self.view.backgroundColor = [UIColor whiteColor];
self.navigationItem.title = self.titleStr;
[self setupUI];
}
//導(dǎo)航左返回
-(void)leftBarButtonAction
{
if (_webView.canGoBack) {
[_webView goBack];
}else{
[self.navigationController popViewControllerAnimated:YES];
}
}
- (void)setupUI {
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
//這里add 添加的js標識 用于處理接受的js通知做判斷
[userContentController addScriptMessageHandler:self name:@"Camera"];
configuration.userContentController = userContentController;
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, kHEIGHT-64) configuration:configuration];
// _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, kHEIGHT-64)];
_webView.navigationDelegate = self;
_webView.UIDelegate = self;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]];
[_webView loadRequest:request];
_webView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:_webView];
[_webView setOpaque:NO];
}
#pragma mark - UIWebViewDelegate uiwebview代理方法
- (void)webViewDidStartLoad:(UIWebView *)webView {
[_progressLayer startLoad];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[_progressLayer finishedLoad];
//自動獲取 webView的title
// self.navigationItem.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
[_progressLayer finishedLoad];
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
// NSLog(@"request.URL---%@",request.URL);
// NSLog(@"request.description(str)---%@",request.description);
//點擊
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
}
return YES;
}
#pragma mark <WKNavigationDelegate> WKWebView代理方法
// 頁面開始加載時調(diào)用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation
{
}
// 頁面加載完成之后調(diào)用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
//自動獲取 webView的title
// self.navigationItem.title = webView.title;
}
//頁面加載失敗時 調(diào)用
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
}
// 接收到服務(wù)器跳轉(zhuǎn)請求之后調(diào)用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
NSLog(@"=======接收到服務(wù)器跳轉(zhuǎn)請求之后調(diào)用======");
}
/**
* 在發(fā)送請求之前椒舵,決定是否跳轉(zhuǎn)
*
* @param webView 實現(xiàn)該代理的webview
* @param navigationAction 當前navigation
* @param decisionHandler 是否調(diào)轉(zhuǎn)block
*/
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
NSLog(@"````````````在發(fā)送請求之前,決定是否跳轉(zhuǎn)```````````");
NSLog(@"IP地址=======%@", navigationAction.request.URL.host.lowercaseString);
NSLog(@"======request.URL.absoluteString---%@",navigationAction.request.URL.absoluteString);
NSLog(@"======request.description(str)---%@",navigationAction.request.description);
if ([navigationAction.request.URL.absoluteString containsString:@"collectionStore"]) {//
//在這里做特定的操作
decisionHandler(WKNavigationActionPolicyCancel);
}else{
decisionHandler(WKNavigationActionPolicyAllow);
}
}
/**
* 在收到響應(yīng)后优俘,決定是否跳轉(zhuǎn)
*
* @param webView 實現(xiàn)該代理的webview
* @param navigationResponse 當前navigation
* @param decisionHandler 是否跳轉(zhuǎn)block
*/
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
NSLog(@"============在收到響應(yīng)后镇防,決定是否跳轉(zhuǎn)========");
NSLog(@"IP地址=======%@", navigationResponse.response.URL.host.lowercaseString);
NSLog(@"request.URL.absoluteString---%@",navigationResponse.response.URL.absoluteString);
NSLog(@"request.description(str)---%@",navigationResponse.response.description);
decisionHandler(WKNavigationResponsePolicyAllow);
}
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"message.name:%@", message.name);
NSLog(@"message.body:%@", message.body);
//根據(jù)添加的js標識 做特定的操作
if ([message.name isEqualToString:@"Camera"]) {
}
if ([message.name isEqualToString:@"ShowMessageFromWKWebView"]) {
// [self showMessageWithParams:message.body];
}
}
#pragma mark - OC傳數(shù)據(jù)給JS
- (void)showMessageWithParams:(NSDictionary *)dict {
if (![dict isKindOfClass:[NSDictionary class]]) {
return;
}
// 將結(jié)果返回給js oc調(diào)用js
//注:showMessageResult('%@')", @"message傳到OC成功,oc傳數(shù)據(jù)給js"
//showMessageResult是js的方法名
// ('%@') 是 傳給js的參數(shù)
NSString *returnJSStr = [NSString stringWithFormat:@"showMessageResult('%@')", @"message傳到OC成功,oc傳數(shù)據(jù)給js"];
[_webView evaluateJavaScript:returnJSStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"oc調(diào)用js回調(diào),,result==%@,error==%@", result, error);
}];
}
@end