javascript - WKUserScript在iOS10中不调用,但在iOS9中有效

标签 javascript ios swift wkwebview wkuserscript

我的代码在 iOS 9 中完美运行,但在 iOS 10 中不起作用,特别是 doBar() 未调用。在 WKWebView 中,我正在注入(inject) javascript 代码。

let jsFoo = "function doFoo() { window.webkit.messageHandlers.doFoo.postMessage(\"doFoo\"); }"
let jsBar = "class MyInterface { static doBar() { window.webkit.messageHandlers.doBar.postMessage(\"doBar\"); } }"

let fooScript = WKUserScript(source: jsFoo, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
let barScript = WKUserScript(source: jsBar, injectionTime: .atDocumentEnd, forMainFrameOnly: true)

contentController.addUserScript(logoutScript)
contentController.addUserScript(openPDFScript)

contentController.add(self, name: "doFoo")
contentController.add(self, name: "doBar")

在网页js代码中进行调用:

window.doFoo() // works in both iOS 9 and iOS 10
window.MyInterface.doBar() // works in iOS 9, but NOT working in iOS 10

Safari 调试器显示,在 iOS 10 窗口中。MyInterface 未定义,但存在带有 doBar 代码的用户脚本。

假设我无法更改网页代码,如何正确注入(inject) doBar,以便它可以在 iOS 10 中工作?

最佳答案

虽然我不是 JS 开发人员,但我认为注入(inject)的代码很好。但它不适用于 iOS 10 jsBar 必须是:

let jsBar = "function MyInterface() {}; { MyInterface.doBar = function() { window.webkit.messageHandlers.doBar.postMessage(\"doBar\"); };"

关于javascript - WKUserScript在iOS10中不调用,但在iOS9中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45116897/

相关文章:

ios - 在 iOS 上使用 Django 和 Alamofire 上传图像

swift - 尽管使用来自示例 (ArcGIS macOS SDK) 的相同格式的 URL,但未加载来自 URL 的 map

ios - 快速排序数组

javascript - 使用javascript检测屏幕上的元素位置

javascript - HTML5 视频 : Are there any benefits to using a source element over the src attribute

ios - xcode 自动调整 xib 的大小在 iphone 6s plus 上不合适

ios - 有没有办法在不发送 "Your Turn"推送通知的情况下更新 GKTurnBasedMatch 中的 matchData?

java - primefaces - 无 Activity 函数

javascript - AJAX 请求未使用 $.when(...) 并行执行

ios - iOS7中如何根据内容调整UITextField的大小?