在Swift WKWebView中捕获window.postMessage [英] Capture window.postMessage in Swift WKWebView

查看:809
本文介绍了在Swift WKWebView中捕获window.postMessage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个快速的ios应用程序,该应用程序使用WKWebView加载电子商务网站.
当用户在此处购买产品时,结帐页面允许用户以加密货币付款.

I am developing a swift ios app that uses WKWebView to load up an ecommerce site.
When a user purchases a product here, the checkout page allows the user to pay in cryptocurrency.

当用户单击在电子钱包中打开"时,该网站会弹出 window.postMessage(paymentData) 付款数据是其中包含比特币网址的js对象.

When the user clicks "Open in Wallet", the site shoots off a window.postMessage(paymentData) where payment data is a js object with a bitcoin url in it.

我正在将WKUserScriptWKWebConfiguration一起使用,以注入一个侦听窗口消息的脚本,然后将数据发射到我的webkit.messageHandler.

I am using a WKUserScript with WKWebConfiguration to inject a script that listens for a window message and then fires off data to my webkit.messageHandler.

let source = """
    window.addEventListener('message', function(e) { window.webkit.messageHandlers.iosListener.postMessage(JSON.stringify(e.data)) } )
    """

不幸的是,此代码从未触发.

Unfortunately this code never triggers.

当我使用chrome或safari devtools注入相同的javascript时,效果很好.

When I use chrome or safari devtools to inject the same javascript, it works just fine.

我已经检查了堆栈溢出情况,以查看WKWebView中的window.postMessage是否有特殊情况,但是到目前为止还没有运气.

I have scoured stack overflow to see if there is a special condition for window.postMessage in WKWebView but have had no luck thus far.

是否可以捕获window.postMessage()事件并将事件数据通过管道传回我的ios应用?

Is it possible to capture a window.postMessage() event and pipe the event data back to my ios app?

先谢谢了!!!! 这是我现有的代码.

Thanks in advance!!!! Here is my existing code.

  let webConfiguration = WKWebViewConfiguration()
    let source = """
    window.addEventListener('message', function(e) { window.webkit.messageHandlers.iosListener.postMessage(JSON.stringify(e.data)) } )
    """
    let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
    userContentController.addUserScript(script)

    userContentController.add(self, name: "iosListener")
    webConfiguration.userContentController = userContentController
    webView = WKWebView(frame: .zero, configuration: webConfiguration)
    webView.uiDelegate = self
    webView.navigationDelegate = self
    webView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(webView)

 func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print("message body: \(message.body)")
    print("message frameInfo: \(message.frameInfo)")
  }

推荐答案

是的,有可能.您还需要设置javascriptEnabled = true

Yes, it is possible. You also need to set javascriptEnabled = true

self.webView.configuration.preferences.javaScriptEnabled = true

您还可以像这样配置侦听器:

You can also configure the listener like this:

self.webView.configuration.userContentController.add(self, name: "iosListener")

并确保您同时应用了这两个命令

And make sure you're applying both commands before

self.webView.load(/*some request*/)

在页面didFinish加载后,您可以进行简单的测试:

You can make a simple test after the page didFinish loading with:

self.webView.evaluateJavaScript("window.webkit.messageHandlers.iosListener.postMessage('test');", completionHandler: { (result, err) in
    if (err != nil) {
        // show error feedback to user.
    }
})

另一建议是与webView进行交互时,请始终在javascript代码的命令末尾添加;,因为某些内容可能依赖于标准javascript.

Another advice is to always have ; at the end of commands on javascript code when interacting with webView as some can rely on standard javascript.

let source = """
    window.addEventListener('message', function(e) {
        window.webkit.messageHandlers.iosListener.postMessage(JSON.stringify(e.data));
    });
    """


注意:我还建议将webView作为类变量而不是方法变量,您可能是在viewDidLoad()上创建它,我建议您将变量移至您的班级.


Note: I'd also suggest to have the webView as a class variable instead of a method variable, you're probably creating it on viewDidLoad(), I'd suggest that you move the variable to your class.

var webView: WKWebView!

这篇关于在Swift WKWebView中捕获window.postMessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆