首先打开webstorm,将最下面h5拷贝到html中。然后导入工程

#define kMessageHandlerName @"mymobile"

1.创建配置类

- (WKWebView *)webView{
if (!_webView) {

WKWebViewConfiguration *config =[[WKWebViewConfiguration alloc]init];

config.preferences.javaScriptEnabled = YES;
/** 默认是不能通过JS自动打开窗口的,必须通过用户交互才能打开 */
config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
_webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:config];

_webView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

_webView.allowsBackForwardNavigationGestures = YES;//打开左划回退功能
_webView.navigationDelegate = self;
_webView.UIDelegate = self;
_webView.backgroundColor = [UIColor whiteColor];
[self.view addSubview:_webView];

}

return _webView;

}

2.加载H5页面

NSURL *path = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
[self.webView loadRequest:[NSURLRequest requestWithURL:path]];

3 注入对象名称 kMessageHandlerName

- (void)viewWillAppear:(BOOL)animated{
        [super viewWillAppear:animated];
        [self.webView.configuration.userContentController addScriptMessageHandler:self name:kMessageHandlerName];
}

- (void)viewDidDisappear:(BOOL)animated{
     [super viewDidDisappear:animated];
     [self.webView.configuration.userContentController removeScriptMessageHandlerForName:kMessageHandlerName];
}

/**代理方法
JS通过mymobile发送数据到iOS端时,在代理中接收
var message = {"method":"call","args":"let go"};
window.webkit.messageHandlers.mymobile(注:这里是注入的对象名).postMessage(message);
*/
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{

NSDictionary *dic = message.body;

NSString *method = dic[@"method"];

if ([method isEqualToString:@"call"]) {

[self call];
      }

NSLog(@"dic = %@", dic);
}

- (void)call{

UIAlertController *sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
[sheet addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//调用js
NSString *js = [NSString stringWithFormat:@"gotoCall()"];
[self.webView evaluateJavaScript:js completionHandler:nil];

}]];

[sheet addAction:[UIAlertAction actionWithTitle:@"不要点我" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

}]];
    [sheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:sheet animated:YES completion:nil];

}

/**  在JS端调用alert函数时,会触发此代理方法(确认框) */

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{

UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
      [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
      [self presentViewController:alertVC animated:YES completion:nil];

completionHandler();
}

<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
font-size: 40px;
}
</style>
</head>

<body>

<div style=" margin-top: 150px">

<p></p>

<div>
<button id="call">拍照</button>
</div>

<script type="text/javascript">

call.onclick = function() {
var message = {"method":"call","args":"let go"};
window.webkit.messageHandlers.mymobile.postMessage(message);
};

function gotoCall(){
alert('调用了OC中的alert')
}

</script>

</body>

</html>

WKWebView与Js交互的更多相关文章

  1. ios WKWebView 与 JS 交互实战技巧

    一.WKWebView 由于Xcode8发布之后,编译器开始不支持iOS 7了,这样我们的app也改为最低支持iOS 8.0,既然需要与web交互,那自然也就选择使用了 iOS 8.0之后 才推出的新 ...

  2. WKWebView与JS交互,UIWebView+JavascriptCore和JS交互

    最近一直在做有关Swift和JavaScript交互的程序,所以有关UIWebView和WKWebView在使用上的差别在此总结下: UIWebView: (1)创建 var webView: UIW ...

  3. WKwebView与JS交互(h5主动)

    先:WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler // 创建一个webiview的配置项 WKWebViewConfiguratio ...

  4. WKWebView与js交互中产生的内存泄漏

    最近开发中突然发现富文本帖子详情内存没有释放掉,找了好久问题都没找到,终于今天发现了问题,先上一点代码片段 WKWebViewConfiguration *configuration = [[WKWe ...

  5. iOS(WKWebView)OC与JS交互 之三

      随着H5功能愈发的强大,没进行过混合开发的小伙们都不好意思说自己能够独立进行iOS的app开发,在iOS7操作系统下,常用的native,js交互框架有easy-js,WebViewJavascr ...

  6. WKWebView新特性及JS交互

    引言 一直听说WKWebView比UIWebView强大许多,可是一直没有使用到,今天花了点时间看写了个例子,对其API的使用有所了解,为了日后能少走弯路,也为了让大家更容易学习上手,这里写下这篇文章 ...

  7. iOS(UIWebView 和WKWebView)OC与JS交互 之二

    在iOS应用的开发过程中,我们经常会使用到WebView,当我们对WebView进行操作的时候,有时会需要进行源生的操作.那么我记下来就与大家分享一下OC与JS交互. 首先先说第一种方法,并没有牵扯O ...

  8. UIWebView和WKWebView的使用及js交互

    UIWebView和WKWebView的使用及js交互 web页面和app直接的交互是很常见的东西,之前尝试过flex和js的相互调用以及android和js的相互调用,却只有ios没试过,据说比较复 ...

  9. 【Swift】WKWebView与JS的交互使用

    一.前言 近日,有朋友问我关于WKWebView与JS的交互问题,可我之前一直使用的是UIWebView,也不曾做过WKWebView的交互啊!接下来大家一块学习下WKWebView是怎么实现原生代码 ...

随机推荐

  1. cpu affinity (亲和性)

    来源:http://www.ibm.com/developerworks/cn/linux/l-affinity.html#download 管理处理器的亲和性(affinity) 为什么(3 个原因 ...

  2. 四步安装typecho(LNMP环境)

    ##1 安装nginx,mysql,php环境 sudo apt-get install nginx php5-fpm php5-cgi php5-cli php5-curl php5-gd php5 ...

  3. JS禁用右键,禁用打印,防止另存为,IE浏览器识别(转载)

    oncontextmenu="window.event.returnValue=false" style="overflow-y: hidden; overflow-x: ...

  4. js实现的笛卡尔乘积-商品发布

    //笛卡儿积组合 function descartes(list) { //parent上一级索引;count指针计数 var point = {}; var result = []; var pIn ...

  5. White space is required before the encoding pseudo attribute in the XML declaration.

    错误出现的位置: <?xml version="1.0"encoding="UTF-8"?> 正确方式: <?xml version=&quo ...

  6. ACdream 1083 人民城管爱人民

    拓扑排序,然后从终点开始递推. #pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio ...

  7. hdu 1217 Arbitrage

    Flody多源最短路 #include<cstdio> #include<cstring> #include<string> #include<cmath&g ...

  8. Partial Tree

    Partial Tree 题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5534 完全背包 做这题前去学习了下完全背包,觉得这个优化简直神技!(以前都是 ...

  9. Redis高可用配置(Keepalived)

    主:172.16.0.104 备:172.16.0.105 VIP:172.16.0.107 客户端直接连VIP,当master 104的redis挂掉后,105作为master.当104重启后,10 ...

  10. 第四十七节,random 随机数模块

    random 随机数模块格式: import random 引入随机模块文件 random.randrange(65,91) 调用随机函数random.randrange(随机数开始范围,随机数结束范 ...