我的代码在 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/