Swift和Javascript集成

时间:2016-10-13 07:46:53

标签: javascript ios swift wkwebview

我跟随this article关于整合 Swift(WKWebView)和Javascript。文章中的所有内容都运行正常,但我试图将一些变量从Swift传递给Javascript。

这是我在Swift中的ViewController:

import UIKit
import WebKit

class ViewController: UIViewController, WKScriptMessageHandler {

    @IBOutlet var containerView : UIView! = nil
    var webView: WKWebView?

    override func loadView() {
        super.loadView()

        let contentController = WKUserContentController();
        let userScript = WKUserScript(
            source: "redHeader()",
            injectionTime: WKUserScriptInjectionTime.AtDocumentEnd,
            forMainFrameOnly: true
        )
        contentController.addUserScript(userScript)
        contentController.addScriptMessageHandler(
            self,
            name: "callbackHandler"
        )

        let config = WKWebViewConfiguration()
        config.userContentController = contentController

        self.webView = WKWebView(
            frame: self.view.frame,
            configuration: config
        )
        self.view = self.webView!
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = NSURL(string:"https://example.com")
        let req = NSURLRequest(URL:url!)
        self.webView!.loadRequest(req)

        let simpleInt = 123

        self.webView?.evaluateJavaScript("redHeader(\(simpleInt)", completionHandler: nil);
    }

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

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

那就是 HTML和JS 驻留在服务器上:

function callNativeApp () {
    try {
        webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");
    } catch(err) {
        console.log('The native context does not exist yet');
    }
}

setTimeout(function () {
    callNativeApp();
}, 50000);

function redHeader(int) {
	console.log(int);
}
<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
            body {
                padding-top: 40px; 
            }
        </style>
        <title>WKWebView Demo</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <h1>WKWebView Test</h1>
        <script type="text/javascript" src="main.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    </body>
</html>

它仍然只是上面文章中的代码,但我无法将变量 simpleInt 传递给JS。

尽管有Javascript调用

webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");

不起作用。

我认为我传递的变量是错误的。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

你可以尝试一些事情

    您的方法调用中缺少
  1. 窗口

    webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");
    

    应该是

    window.webkit.messageHandlers.callbackHandler.postMessage("Hello from JavaScript");

  2. 检查您是否能够从浏览器打开调试菜单访问此Check for enabling debug mode

    的消息处理程序

    window.webkit.messageHandlers.callbackHandler

  3. Result

    1. 另一个问题可能是使用本机调用超时。删除超时并添加一个按钮来调用messageHandler。