WKWebView
<!DOCTYPE html>
<head>
<title>HTML</title>
<meta charset="utf-8">
</head>
<style type='text/css'>
img{
cursor:pointer;
}
</style>
<body>
<h2 style="text-align:center">Title</h2>
<p style="text-align:center"> <button id="btn1" type = "button" onclick = "clickOne()" > JS调用OC:无参数 </button> </p>
<p style="text-align:center"> <button id="btn2" type = "button" onclick = "clickTwo()"> JS调用OC:带参数 </button> </p>
<p style="text-align:center"> <button id="btn3" type = "button" onclick = "showAlert()" > OC捕获弹框 </button> </p>
<script type = "text/javascript">
function clickOne()
{
window.webkit.messageHandlers.clickOne.postMessage({});
}
function clickTwo()
{
window.webkit.messageHandlers.clickTwo.postMessage({"pdid":"大厦1001"});
}
function showAlert()
{
alert("我传递了一个数据");
}
//OC调用JS改变背景色
function changeColor()
{
document.body.style.backgroundColor = randomColor();
}
//随机生成颜色
function randomColor()
{
var r=Math.floor(Math.random()*256);
var g=Math.floor(Math.random()*256);
var b=Math.floor(Math.random()*256);
return "rgb("+r+','+g+','+b+")";//所有方法的拼接都可以用ES6新特性`其他字符串{$变量名}`替换
}
</script>
</body>
</html>
#import "KSViewController.h"
#import <WebKit/WebKit.h>
#import <objc/runtime.h>
@interface KSViewController ()<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView * webView;
@end
@implementation KSViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithTitle:@"修改颜色" style:UIBarButtonItemStyleDone target:self action:@selector(changeColor)];
self.navigationItem.rightBarButtonItem = item;
NSString *jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
WKUserScript * wksc = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
_webView.UIDelegate = self;
_webView.navigationDelegate = self;
_webView.userInteractionEnabled = YES;
[[_webView configuration].userContentController addScriptMessageHandler:self name:@"clickOne"];
[[_webView configuration].userContentController addScriptMessageHandler:self name:@"clickTwo"];
[[_webView configuration].userContentController addUserScript:wksc];
//请求网页
NSString * path = [[NSBundle mainBundle] pathForResource:@"KS.html" ofType:nil];
// NSURL * url = [NSURL URLWithString:@""];
// [_webView loadRequest:[NSURLRequest requestWithURL:url]];
NSString * url = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[_webView loadHTMLString:url baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
[self.view addSubview:_webView];
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSString * name = message.name;
NSDictionary * dic = message.body;
if ([name isEqual:@"clickTwo"]) {
[self clickTwo:dic[@"pdid"]];
}else if ([name isEqual:@"clickOne"]){
[self clickOne];
}
}
-(void)clickOne{
NSLog(@"%s",__func__);
}
-(void)clickTwo:(NSString *)pdid{
NSLog(@"%@",pdid);
}
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Alert" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
-(void)changeColor{
NSString * str = @"changeColor()";
[_webView evaluateJavaScript:str completionHandler:^(id _Nullable item, NSError * _Nullable error) {
NSLog(@"修改颜色");
}];
}
@end