Swift webview:如何从JavaScript调用正确的swift代码?
我试图让我的JavaScript与swift代码交互,但不幸的是我没有成功。
目前,我只是试图改变标题的颜色,并显示一条消息,就像你会看到下面的代码。
这是我的( index.html )代码:
<!DOCTYPE html> <html> <head> <title>Test</title> <meta charset="UTF-8"> </head> <body> <h1>WebView Test</h1> <script type="text/javascript" src="main.js"></script> </body> </html>
这是我的( main.js -JavaScript )代码:
function callNativeApp () { try { webkit.messageHandlers.callbackHandler.postMessage("Send from JavaScript"); } catch(err) { console.log('error'); } } setTimeout(function () { callNativeApp(); }, 5000); function redHeader() { document.querySelector('h1').style.color = "red"; }
这是我的( ViewController.swift )代码:
import UIKit import WebKit class ViewController: UIViewController, WKScriptMessageHandler { @IBOutlet var containerView : UIView! = nil var webView: WKWebView? override func loadView() { super.loadView() var contentController = WKUserContentController(); var userScript = WKUserScript( source: "redHeader()", injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true ) contentController.addUserScript(userScript) contentController.addScriptMessageHandler( self, name: "callbackHandler" ) var config = WKWebViewConfiguration() config.userContentController = contentController self.webView = WKWebView() self.view = self.webView! } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. var url = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("index", ofType: "html")!) var req = NSURLRequest(URL: url) self.webView!.loadRequest(req) } func userContentController(userContentController: WKUserContentController!,didReceiveScriptMessage message: WKScriptMessage!) { if(message.name == "callbackHandler") { println("JavaScript is sending a message \(message.body)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
你有一切正确的设置,但是你没有把你的WKWebViewConfiguration
实例给WKWebView
。 由于configuration具有Javascript / Swift桥的细节,所以不能来回交谈。
override func loadView() { // ... var config = WKWebViewConfiguration() config.userContentController = contentController self.webView = WKWebView(frame: self.view.frame, configuration: config) self.view = self.webView! }
我的2美分,与JSON使用JavaScriptcallback…完整的类定义和布局,请参阅亚当的代码
import UIKit import WebKit class ViewController: UIViewController, WKScriptMessageHandler { var webView: WKWebView? ...
然后
override func loadView() { let theConfiguration = WKWebViewConfiguration() let contentController = theConfiguration.userContentController // alert fix, at start to allow a JS script to overwrite it contentController.addUserScript( WKUserScript( source: "window.alert = function(message){window.webkit.messageHandlers.messageBox.postMessage({message:message});};", injectionTime: WKUserScriptInjectionTime.AtDocumentStart, forMainFrameOnly: true ) ) contentController.addScriptMessageHandler(self, name: "messageBox") self.webView = WKWebView(frame: self.view.frame, configuration: theConfiguration) // and here things like: self.webView!.navigationDelegate = self self.view = self.webView! // fill controllers view }
具体地说
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if message.name == "messageBox" { let sentData = message.body as! Dictionary<String, String> let message:String? = sentData["message"] let alertController = UIAlertController(title: nil, message: message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment:"btnOK"), style: .Default, handler: nil)) self.presentViewController(alertController, animated: true) {} } }
- AFNetworking:setRedirectResponseBlock在我的类NSURLResponse总是返回空值
- React Native自定义组件不会动态设置组件的大小
- 如何获得cocoa的形象作者
- 使用Core Graphics在Objective-C(IOS)中绘制angular度/angular度/“圆锥形”/“弧光”渐变
- 当使用PushViewController时,选项卡不显示
- iOS指定的初始化程序:使用NS_DESIGNATED_INITIALIZER
- 在Swift中添加和删除一个视图覆盖
- Xcode 8-将Alcatraz的插件转换为Source Editor Extension
- 使用iOS 6.1模拟器和XCode 4.6进行testing