Я работаю с приложением MacOS, которому необходимо использовать возможность WKUserScript для отправки сообщения с веб-страницы обратно в приложение MacOS.Я работаю со статьей https://medium.com/capital-one-tech/javascript-manipulation-on-ios-using-webkit-2b1115e7e405, которая показывает, как это работает в iOS и работает просто отлично.
Однако я уже несколько недель пытаюсь заставить его работать на моем MacOS.Вот мой пример его кода, который прекрасно работает и работает, но не может успешно напечатать сообщение, найденное в обработчике userContentController ()
import Cocoa
import WebKit
class ViewController: NSViewController, WKNavigationDelegate {
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let userContentController = WKUserContentController()
// Add script message handlers that, when run, will make the function
// window.webkit.messageHandlers.test.postMessage() available in all frames.
userContentController.add(self, name: "test")
// Inject JavaScript into the webpage. You can specify when your script will be injected and for
// which frames–all frames or the main frame only.
let scriptSource = "window.webkit.messageHandlers.test.postMessage(`Hello, world!`);"
let userScript = WKUserScript(source: scriptSource, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
userContentController.addUserScript(userScript)
// let config = WKWebViewConfiguration()
// config.userContentController = userContentController
// let webView = WKWebView(frame: .zero, configuration: config)
webView.navigationDelegate = self
webView.configuration.userContentController = userContentController
// Make sure in Info.plist you set `NSAllowsArbitraryLoads` to `YES` to load
// URLs with an HTTP connection. You can run a local server easily with services
// such as MAMP.
let htmlStr = "<html><body>Hello world - nojs</body></html>"
webView.loadHTMLString(htmlStr, baseURL: nil)
}
}
extension ViewController: WKScriptMessageHandler {
// Capture postMessage() calls inside loaded JavaScript from the webpage. Note that a Boolean
// will be parsed as a 0 for false and 1 for true in the message's body. See WebKit documentation:
// https://developer.apple.com/documentation/webkit/wkscriptmessage/1417901-body.
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if let messageBody = message.body as? String {
print(messageBody)
}
}
}
Другая странная вещь заключается в том, что я не могу создатьпростое приложение WKWebView, которое загружает страницу и отображает ее.Это всего лишь простые тесты, и мое основное приложение способно нормально загружать / отображать веб-страницы, используя AlamoFire / loadHTMLString () для отображения страниц, я просто не смог ввести требуемый JS.
Все, что я 'Все, что было сделано в преобразовании, довольно прямолинейно и практически не требует изменений, за исключением назначения userContentController - так что, может быть, в этом проблема?Этот пример прекрасно работает в iOS с его оригинальным образцом в качестве прототипа.https://github.com/rckim77/WKWebViewDemoApp/blob/master/WKWebViewDemoApp/ViewController.swift
Я предполагаю, что должно быть что-то очень простое, что я здесь упускаю.Любая помощь будет принята с благодарностью!