用户脚本是在文档加载开始时或文档加载完成后注入网页的 JS。用户脚本非常强大,因为它们允许客户端自定义网页,允许注入事件侦听器,甚至可以用于注入可以反过来回调到本机应用程序的脚本。以下代码片段创建一个在文档加载结束时注入的用户脚本。用户脚本被添加到 WKUserContentController 实例中,该实例是 WKWebViewConfiguration 对象的属性。
// Create WKWebViewConfiguration instance
var webCfg:WKWebViewConfiguration = WKWebViewConfiguration()
// Setup WKUserContentController instance for injecting user script
var userController:WKUserContentController = WKUserContentController()
// Get script that's to be injected into the document
let js:String = buttonClickEventTriggeredScriptToAddToDocument()
// Specify when and where and what user script needs to be injected into the web document
var userScript:WKUserScript = WKUserScript(source: js,
injectionTime: WKUserScriptInjectionTime.atDocumentEnd,
forMainFrameOnly: false)
// Add the user script to the WKUserContentController instance
userController.addUserScript(userScript)
// Configure the WKWebViewConfiguration instance with the WKUserContentController
webCfg.userContentController = userController;
您的网页可以通过以下方式将消息发布到您的本机应用程序window.webkit.messageHandlers.<name>.postMessage (<message body>)
方法。
这里,“name”是回发消息的名称。 JS 可以将任何 JS 对象作为消息体回发,并且 JS 对象会自动映射到相应的 Swift 原生对象。
当 ID 为“ClickMeButton”的按钮上发生按钮单击事件时,以下 JS 代码片段会发回一条消息。
var button = document.getElementById("clickMeButton");
button.addEventListener("click", function() {
varmessageToPost = {'ButtonId':'clickMeButton'};
window.webkit.messageHandlers.buttonClicked.postMessage(messageToPost);
},false);
为了接收网页发布的消息,您的本机应用程序需要实现 WKScriptMessageHandler 协议。
该协议定义了一个必需的方法。可以查询回调中返回的 WKScriptMessage 实例以获取有关回发消息的详细信息。
func userContentController(userContentController: WKUserContentController,
didReceiveScriptMessage message: WKScriptMessage) {
if let messageBody:NSDictionary= message.body as? NSDictionary{
// Do stuff with messageBody
}
}
最后,实现 WKScriptMessageHandler 协议的本机类需要将自身注册为 WKWebView 的消息处理程序,如下所示:
// Add a script message handler for receiving "buttonClicked" event notifications posted
// from the JS document
userController.addScriptMessageHandler(self, name: "buttonClicked")