【问题标题】:Script message handler not working脚本消息处理程序不起作用
【发布时间】:2016-01-12 00:34:32
【问题描述】:

我正在尝试注入自定义 WebKit 脚本消息处理程序。我的控制器已正确加载,视图也已正确加载。但是,在 JS 端(来自 Safari 控制台),window.webkit.messageHandlers 是空的。知道为什么吗?我的应用使用的是 iOS 8.1,但即使升级到 9.2,它也无法正常工作。

import Foundation
import UIKit
import WebKit

public class FooController: UIViewController, WKScriptMessageHandler {
    private var wkWebView: WKWebView?

    public override func viewDidLoad() {
        super.viewDidLoad()

        let o = WKUserContentController()
        o.addScriptMessageHandler(self, name: "foo")
        let config = WKWebViewConfiguration()
        config.userContentController = o

        self.wkWebView = WKWebView(frame: self.view.bounds, configuration: config)
        self.view.addSubview(self.wkWebView!)

        self.wkWebView!.loadRequest(NSURLRequest(URL: NSBundle.mainBundle().URLForResource("foo", withExtension: "html")!))
    }

    public func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
        print("foo")
    }
}

【问题讨论】:

    标签: ios swift wkwebview wkwebviewconfiguration


    【解决方案1】:

    webkit.messageHandlers 不是数组。这是一个UserMessageHandlersNamespace

    试试

    var message = {"key1":"value1", "key2":"value2", "dictionary": {"name": "foo"}}
    webkit.messageHandlers.foo.postMessage(message);
    

    在您的消息处理程序中。

    public func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
        let body = message.body
        if let dict = body as? Dictionary<String, AnyObject> {
            print(dict)
        }
    }
    

    【讨论】:

    • 嗨 Onato,感谢您的回答。我知道messageHandlers 是一个对象。但它根本没有密钥,尤其是缺少foo
    • 您的快速代码对我来说效果很好。你能发布你如何调用你的消息处理程序或检查“foo”的存在吗?
    • 阿夫。刚刚重新测试,它工作正常。对困惑感到抱歉。但是,我现在有一个不同的问题。我无法发布任何自定义数据。我试图发布一个包含 2 个字符串的字典和另一个字典,而我收到的正文只包含一个字符串。没什么大不了的,但你知道吗?
    • 太棒了!它工作正常。我试图将身体投射为NSDictionary,但它没有按预期工作。
    【解决方案2】:

    在下面的 javascript 代码中,消息是强制性的。

    var message = {"key1":"value1", "key2":"value2", "dictionary": {"name": "foo"}}
    webkit.messageHandlers.foo.postMessage(message);
    

    以下不带message参数的javascript代码,

    webkit.messageHandlers.foo.postMessage();

    没有按预期调用func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)

    【讨论】:

      猜你喜欢
      • 2013-01-20
      • 2017-12-25
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 2016-10-28
      • 1970-01-01
      相关资源
      最近更新 更多