首先,我们需要准备一篇带有交互脚本的HTML
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<h1>我是大标题</h1>
<h2 id="showView" style="color: blue; font-size: 40px;">我是2标题</h2>
<hr/>
</head>
<body>
<script>
function func()
{
alert("奇葩的坨坨~~");
}
function func2()
{
<!-- window.location.href = "oc://ocFunc";//调用oc里面的方法-->
var messgeToPost = {'ButtonId':'clickMe'};
//这里的buttonClicked是WKwebView配置过的
window.webkit.messageHandlers.buttonClicked.postMessage(messgeToPost);
}
function func3()
{
window.location.href = "oc://ocFunc";//调用oc里面的方法
var messgeToPost = {'ButtonId':'touchUp'};
window.webkit.messageHandlers.touchUp.postMessage(messgeToPost);
}
function func4()
{
var result = confirm('confirm窗体');
if (result == true)
{
document.getElementById("showView").innerHTML = 'ture';
}else
{
document.getElementById("showView").innerHTML = 'false';
}
}
function func5()
{
var result = prompt('Title','Please input anything')
document.getElementById("jsShow").innerHTML = result;
}
</script>
<p>我就是为了测试</p>
<a href="http://www.baidu.com">百度</a>
<button onclick = "func2()" id="clickMe">JS调用OC</button>
<button onclick = "func3()" id="touchUp">TouchUp</button>
<button onclick = "func4()" id="confirm">Confirm</button>
<button onclick = "func5()" id="TextInput">TextInput</button>
<br/>
<div id="SwiftDiv">
<span id="jsShow" style="color: red; font-size: 100px;"></span>
</div>
</body>
</html>
当我们加载了这个网页文件之后,我们可以直接调用JS的function函数。(如上:func(),func2(),func3()等等)
卧槽,表达能力有限,还是贴代码吧。。。。。。。。。。。。。。。。。日了狗了!
//
// ViewController.m
// JS的调用
//
// Created by 曹敬贺 on 15/11/23.
// Copyright © 2015年 北京明兰网络科技有限公司. All rights reserved.
//
#import "ViewController.h"
#import <WebKit/WebKit.h>
@interface ViewController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>
@property (nonatomic,strong)WKWebView * mywebView;
@end
@implementation ViewController
@synthesize mywebView;
- (void)viewDidLoad {
[super viewDidLoad];
//读取本地的JS网页文件
NSString * local_JS_Path = [[NSBundle mainBundle]pathForResource:@"js" ofType:@"html"];
NSString * html = [NSString stringWithContentsOfFile:local_JS_Path encoding:NSUTF8StringEncoding error:nil];
WKUserContentController * wkVC = [[WKUserContentController alloc]init];
[wkVC addScriptMessageHandler:self name:@"buttonClicked"];
[wkVC addScriptMessageHandler:self name:@"touchUp"];
WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc]init];
WKPreferences * prefer = [[WKPreferences alloc]init];
prefer.javaScriptEnabled = YES;
prefer.minimumFontSize = 20;
prefer.javaScriptCanOpenWindowsAutomatically = YES;
configuration.preferences = prefer;
configuration.userContentController = wkVC;
mywebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 40, self.view.bounds.size.width, self.view.bounds.size.height - 40) configuration:configuration];
mywebView.UIDelegate = self;
mywebView.navigationDelegate = self;
[self.view addSubview:mywebView];
[mywebView loadHTMLString:html baseURL:nil];
NSArray* array = @[@"直接调用js"];
for(int i=0;i<array.count;i++)
{
UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(i*(320/array.count), 20, 320/array.count, 20);
button.tag = i + 100;
[button setTitle:array[i] forState:UIControlStateNormal];
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
}
- (void)buttonClick:(UIButton *)sender
{
if (sender.tag == 100) {
//调用html中已有的JS的方法(如Demo中js.html中的func()方法)
[mywebView evaluateJavaScript:@"func()" completionHandler:^(id obj, NSError * error) {
if (error) {
NSLog(@"调用html的JS方法出错!");
}
}];
}
}
#pragma mark -------WKWebDelegate---------
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"Name:%@ Body:%@",message.name,message.body);
}
//alert
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
NSLog(@"alert:%@==%@",message,frame);
UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"title" message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alert animated:YES completion:^{
}];
}
//confirm
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler
{
NSLog(@"confirm:%@==%@",message,frame);
UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"title" message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(YES);
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler(NO);
}]];
[self presentViewController:alert animated:YES completion:nil];
}
//TextInput
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * result))completionHandler
{
NSLog(@"TextInput:%@==%@",prompt,defaultText);
UIAlertController * alert = [UIAlertController alertControllerWithTitle:prompt message:defaultText preferredStyle:UIAlertControllerStyleAlert];
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.textColor = [UIColor blackColor];
}];
[alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(alert.textFields[0].text);
}]];
[self presentViewController:alert animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
这样就完成了对网页的基本调用。
另外还可以向网页中注入JS代码,注入方法网络上很多,这里不再赘述!
最近感觉网页加载型app越来越重要,所以我尝试了一下用WKWebView加载本地CSS样式和JS文件的方式挂载到网页上。
首先讲下CSS,在以前用UIWebView方式加载网页时,CSS样式可以自动的被应用到html中,但是在新的WKWebView中,工程中的CSS样式是不会被自动加载到网页中的,那么我们就必须手动添加CSS文件,但加载CSS样式的文件时遇到了困难,在github上和stackoverflow上搜索了好多帖子,发现好多人和我遇到了同样的问题。那么如何加载CSS样式呢,我们可以用脚本挂载CSS样式,然后将脚本注入到网页中,这样就能够实现CSS样式的加载了。
其次,JS的挂载,网上有很多,忽略。
第三,关于网页加载本地图片的问题,如果网页中需要本地图片,那么我们加载的时候,将baseurl设置称为bundle的pathURL即可,图片的路径只要写文件名即可。
第四,BUG?我在ios8下测试加载本地html,用WKWebView时,CSS用挂脚本的方式依然加载不上,在ios9上没有问题,应该是ios9把这个问题修复了?
第五,从网页中提取数据,这个需要完全的JS,我在一位JS大神同事的帮助下,能提取到几乎所有的节点数据,由于我对JS一知半解,不在这卖弄风骚了。
https://www.w3.org/2010/05/video/mediaevents.html