简体   繁体   English

Javascript 从 UIWebView 调用 Swift

[英]Javascript call to Swift from UIWebView

I am trying to make a call from a javascript function in a UIWebView to Swift in iOS 10. I have setup a very basic project just to try and get this working, the code is below.我正在尝试从 UIWebView 中的 javascript 函数调用 iOS 10 中的 Swift。我已经设置了一个非常基本的项目,只是为了尝试使其正常工作,代码如下。

import UIKit

class ViewController: UIViewController, UIWebViewDelegate  {    
  @IBOutlet var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = Bundle.main.url(forResource: "products", withExtension: "html")
        let request = NSURLRequest(url: url! as URL)
        webView.loadRequest(request as URLRequest)
    }

    @IBAction func closeDocumentViewer() {
        displayView.isHidden = true;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

If I just one to receive a string from a javascript function what would I have to add to the above?如果我只是从 javascript 函数接收一个字符串,我必须在上面添加什么?

I would suggest looking into using WKWebView instead UIWebView .我建议考虑使用WKWebView而不是UIWebView You then won't need to register custom URL scheme.然后您将不需要注册自定义 URL 方案。 Additionally, UIWebView is obsolete and WKWebView has a lot of advantages, most notably performance and rendering as it runs in a separate process.此外,UIWebView 已经过时,WKWebView 有很多优点,最显着的是性能和渲染,因为它在单独的进程中运行。

Link to Apple documentation and recommendation to use WKWebView https://developer.apple.com/reference/webkit/wkwebview/链接到 Apple 文档和使用 WKWebView 的建议https://developer.apple.com/reference/webkit/wkwebview/

Important重要的

Starting in iOS 8.0 and OS X 10.10, use WKWebView to add web content to your > app.从 iOS 8.0 和 OS X 10.10 开始,使用 WKWebView 将 Web 内容添加到您的 > 应用程序。 Do not use UIWebView or WebView.不要使用 UIWebView 或 WebView。

That said, it's very simple to setup a native to javascript bridge:也就是说,设置一个原生到 javascript 的桥是非常简单的:

import WebKit

class ViewController: UIViewController, WKScriptMessageHandler {
   var webView: WKWebView?
    override func loadView() {
        super.loadView()
        
        webView = WKWebView(frame: self.view.frame)
        webView?.configuration.userContentController.add(self, name: "scriptHandler")
        
        self.view.addSubview(webView!)
    }
    
    public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print("Message received: \(message.name) with body: \(message.body)")
    }
// rest of code
}

Then in your javascript code, call it:然后在您的 javascript 代码中,调用它:

window.webkit.messageHandlers["scriptHandler"].postMessage("hello");

I have written a library that leverages this and adds some fancy javascript syntax.我编写了一个库,利用它并​​添加了一些花哨的 javascript 语法。 https://github.com/tmarkovski/BridgeCommander https://github.com/tmarkovski/BridgeCommander

To use it, just reference the project (or add the swift and javascript files to your Xcode project) and call要使用它,只需引用项目(或将 swift 和 javascript 文件添加到您的 Xcode 项目)并调用

    webView = WKWebView(frame: self.view.frame)
    let commander = SwiftBridgeCommander(webView!)
    
    commander.add("echo") {
        command in
        command.send(args: "You said: \(command.args)")
    }

You then will be able to use callback syntax in javascript like this然后,您将能够像这样在 javascript 中使用回调语法

var commander = new SwiftBridgeCommander();
commander.call("echo", "Hello", function(args) {
        // success callback
    }, function(error) { 
        // error callback
});

You must a custom URL Scheme such as myawesomeapp and intercept requests to it using:您必须使用自定义URL Scheme例如myawesomeapp并使用以下方法拦截对它的请求:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool

Fire a call to native code using window.location=myawesomeapp://hello=world , and get the query params you pass from request.URL.query in the native code.使用window.location=myawesomeapp://hello=world调用本机代码,并获取您从本机代码中的request.URL.query传递的查询参数。

For more information, see my question about UIWebView s here: JavaScript synchronous native communication to WKWebView有关更多信息,请参阅我关于UIWebView的问题: JavaScript synchronous native communication to WKWebView

We can call the swift function from Javascript with the help of WKScriptMessageHandler我们可以在WKScriptMessageHandler的帮助下从 Javascript 调用 swift 函数

A class conforming to the WKScriptMessageHandler protocol provides a method for receiving messages from JavaScript running on a webpage.符合 WKScriptMessageHandler 协议的类提供了一种从运行在网页上的 JavaScript 接收消息的方法。

we need to add a listener to the event into our WKUserContentController我们需要在我们的 WKUserContentController 中添加一个事件监听器

 let contentController = WKUserContentController()
    contentController.add(self, name: "loginAction”)

We have to implement its userContentController to receive the content sent from Javascript.我们必须实现它的 userContentController 来接收从 Javascript 发送的内容。 for ex.例如。 limiting only to the "logout" we want for now.仅限于我们现在想要的“注销”。

  func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {       
       if message.name == "logout" {
           print("JavaScript is sending a message \(message.body)")
       }
   }

And from JavaScript end, They have to implement like this:从 JavaScript 端,他们必须像这样实现:

 function sendLogoutAction() {
       try {
           webkit.messageHandlers.logout.postMessage("logout");
       } catch(err) {
           console.log('The native context does not exist yet');
       }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM