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![0].text) })) self.presentViewController(alert, animated: true) { () -> Void in } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
