Script message handler not working

I am trying to introduce a special WebKit script message handler. My controller is correctly loaded and displayed. However, on the JS side (from the Safari console) window.webkit.messageHandlers empty. Any idea why? My application uses iOS 8.1, but even when upgrading to 9.2 it does not work.

 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") } } 
+5
source share
2 answers

webkit.messageHandlers not an array. This is UserMessageHandlersNamespace .

Try

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

In the message handler.

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

In the javascript code below, the message is required.

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

The following javascript code without a message parameter,

webkit.messageHandlers.foo.postMessage();

did not call func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) as expected

-1
source

Source: https://habr.com/ru/post/1240391/


All Articles