Swift接收JavaScript消息无效

时间:2019-03-04 22:09:33

标签: javascript ios swift

我需要Javascript快速发送消息,但不起作用。

Swift代码:

class FirstViewController: UIViewController, WKUIDelegate, WKScriptMessageHandler {

@IBOutlet weak var webview: WKWebView!

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
     print( "Enter here" )

    if message.name == "jsHandler" {
        print( message.body );
    }
}

override func viewDidLoad() {
    super.viewDidLoad()

    let htmlPath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "web")
    let url = URL(fileURLWithPath: htmlPath!)
    let request = URLRequest(url: url)

    let user = WKUserContentController()
    user.add(self, name: "jsHandler")
    webview.configuration.userContentController = user

    webview.uiDelegate = self
    webview.navigationDelegate = self
    webview.load(request)
}

javascript代码:

$(document).on( 'click', '.element', function() {
    window.webkit.messageHandlers.jsHandler.postMessage( "Invoke swift" );
} );

有什么问题还是缺少的东西?

2 个答案:

答案 0 :(得分:0)

我找到了解决方法。

我不知道这是否是更好的方法,但是为我解决了。

wkwebview启动时需要配置,因此无法使用图形视图创建。我是用代码创建的。

//@IBOutlet weak var webview: WKWebView!
var wk: WKWebView!

内部viewDidLoad函数:

let config = WKWebViewConfiguration()
let user = WKUserContentController()

user.add(self, name: "jsHandler")
config.userContentController = user

wk = WKWebView(frame: .zero, configuration: config)
view.addSubview(wk)

let layoutGuide = view.safeAreaLayoutGuide

wk.translatesAutoresizingMaskIntoConstraints = false
wk.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
wk.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
wk.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true
wk.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true

因此JavaScript可能会为Swift发送消息!

答案 1 :(得分:0)

如果您使用Storyboard,只需在webview.load(请求)之前在viewDidLoad中设置

//webview is your @IBOutlet
webview.configuration.userContentController.add(self, name: "yourHandler")
webview.configuration.preferences.javaScriptEnabled = true