JS和webView的交互

JSContext的交互方式最为简单快捷:

1.申明一个JSContext对象

self.jsRunner = [[JSContext alloc] init];

2.在原生中定义申明一个JS函数方法(JS代码函数中可以使用)

self.jsRunner[@"action1"] = ^(int value){

printf("啦啦啦\n");

};

self.jsRunner[@"action2"] = ^(JSValue *value){

NSLog(@"%@",value);

};

3.通过执行JS代码的方式执行自己定义的函数(热更新通过加载自定义好的JS函数专门来转移实现原生消息发送相关函数,而后通过下载JS文件然后执行预定的代码尝试或达到替代原生代码过程)

[self.jsRunner evaluateScript:@"action1(10);"];

[self.jsRunner evaluateScript:@"action2([1,2,3,\'你好哦\']);function testAction(){return 99;};"];

JSValue *result = [self.jsRunner evaluateScript:@"testAction();"];

NSLog(@"返回的结果:%@",result);

在UIWebView中获得JSContext,在代理OnFinshload函数中通过

self.jsRunner =[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

获得

在WKWebView中

You cannot obtain the context, because layout and javascript is handled on another process.

Instead, add scripts to your webview configuration, and set your view controller (or another object) as the script message handler.

- (void)setupWKWebView
{
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
// 设置偏好设置
config.preferences = [[WKPreferences alloc] init];
// 默认为0
config.preferences.minimumFontSize = ;
// 默认认为YES
config.preferences.javaScriptEnabled = YES;
// 在iOS上默认为NO,表示不能自动通过窗口打开
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
config.processPool = [[WKProcessPool alloc] init];
config.userContentController = [[WKUserContentController alloc] init];
//注意在这里注入JS对象名称 "JSObjec"
[config.userContentController addScriptMessageHandler:self name:@"JSObjec"]; self.showWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
self.showWebView.navigationDelegate = self;
[self.view addSubview:self.showWebView]; NSURL *path = [NSURL fileURLWithPath:网页文件路径];
[self.showWebView loadRequest:[NSURLRequest requestWithURL:path]];
} Now, send messages from JavaScript like so: //在JS函数代码中调用
//这里的内容差不多全部一样 只是调用的方法有区别 一定要注意区分
//这个是用UIWebView时调用的方法 JSObjec.getCall(callInfo);
//下面是用WKWebView调用的方法
window.webkit.messageHandlers.JSObjec.postMessage(callInfo);
//当执行到上述语句是将回调下面这个函数
Your script message handler will receive a callback: - (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"%@", message.body);
  //此处body可以放回调给WebView的js端回调函数名称参数个数类型描述等内容,通过调用执行该JS函数将操作结果返回给Web端
}


普通的实现方式:
通过WebView调用页面中的JS函数,获得返回值
通过代理链接截获,执行原生代码
上一篇:Java 单例模式详解


下一篇:【XSY1295】calc n个点n条边无向连通图计数 prufer序列