WKWebView与JavaScript交互基础

login.html 代码

<!DOCTYPE html>
<html>
<head>
<title>使用JavaScript</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="stylesheet" type="text/css" href="login.css" />
<script type = "text/javascript" src = "login.js"></script>
</head>
<body>
<div>
<form>
<input type="text" />
<input type="button" value="按钮" onclick="fun();"/>
<input type="button" value="Alert" onclick="alert();"/>
<input type="button" value="Confirm" onclick="confirm();"/>
<input type="button" value="TextInput" onclick="prompt('提示','占位符');"/>
</form>
</div>
<span id="id"></span>
</body> </html>

login.css代码     样式随意,做做样子而已

div{
width:200px;
height:30px;
position:absolute;/*绝对坐标*/
left:50px;
top:50px;
}

login.js代码

function fun(){
var message = {
'method':'hello',
'param':'刘冠'
};
window.webkit.messageHandlers.webViewApp.postMessage(message);
}
function mess(){
alert("My First JavaScript");
}

ViewController.swift代码

//
// ViewController.swift
// 第一个测试程序
//
// Created by liuguan on 16/11/16.
// Copyright © 2016年 刘冠. All rights reserved.
// import UIKit
import WebKit class ViewController: UIViewController,WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler{ var wkWebview:WKWebView?; override func viewDidLoad() {
super.viewDidLoad()
/**js调用app 分三步
1.app注册handler
2.app处理handler
2.js调用
*/
let config = WKWebViewConfiguration()
//注册js方法
config.userContentController.addScriptMessageHandler(self, name: "webViewApp") wkWebview = WKWebView(frame: self.view.bounds, configuration: config)
wkWebview!.navigationDelegate = self
wkWebview!.UIDelegate = self
self.view.addSubview(wkWebview!)
//加载本地页面
wkWebview!.loadRequest(NSURLRequest(URL: NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("login", ofType: "html")!)))
//允许手势,后退前进等操作
wkWebview!.allowsBackForwardNavigationGestures = true
} // 实现js调用iOS的handle委托
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage){
//接收传过来的消息,从而决定APP调用的的方法
let dic = message.body as! Dictionary<String,String>
if dic["param"] == "刘冠"{
//app调用js
wkWebview!.evaluateJavaScript("document.getElementById('id').innerText=document.getElementById('id').outerText+'完成|';",completionHandler: nil)
wkWebview!.evaluateJavaScript("mess();",completionHandler: nil)
} }
//注意:wkWebview默认不会弹框,js中有三种弹框类型
//js的alert方法调用
func webView(webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: () -> Void) { let alert = UIAlertController(title: "提示", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (alertAction) -> Void in
completionHandler()
}))
self.presentViewController(alert, animated: true) { () -> Void in
}
}
//js的confirm方法调用
func webView(webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: (Bool) -> Void) { let alert = UIAlertController(title: "提示", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Cancel, handler: { (alertAction) -> Void in
completionHandler(false)
}))
alert.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: { (alertAction) -> Void in
completionHandler(true)
}))
self.presentViewController(alert, animated: true) { () -> Void in
}
}
//js的prompt方法调用
func webView(webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: (String?) -> Void) { let alert = UIAlertController(title: prompt, message: "", preferredStyle: UIAlertControllerStyle.Alert)
alert.addTextFieldWithConfigurationHandler { (textFiled) -> Void in
textFiled.text = defaultText
}
alert.addAction(UIAlertAction(title: "完成", style: UIAlertActionStyle.Default, handler: { (alertAction) -> Void in
completionHandler(alert.textFields![].text)
}))
self.presentViewController(alert, animated: true) { () -> Void in
}
} override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} }
上一篇:iOS 系统分析(一) 阅读内核准备知识


下一篇:微信公众平台应用开发:方法、技巧与案例--柳峰,Java语言版本