问题
In swift iOS project, I have added JS file. And using WKWebview,
my question is,
In iOS do we need to write? How we can inject this ?
const JSInterface = {
alertMe: (text) => {
alert(text + '-> in hello.js');
}
}
Before I have written functions in JS file like;
function alertMe(text) {
alert(text + '-> in hello.js');
}
and injected JS
func loadJavaScript() {
self.jsContext = JSContext()
if let jsScript = jsScriptText(){
//Add an exception handler.
self.jsContext.exceptionHandler = { context, exception in
if let exc = exception {
print("JS Exception:", exc.toString())
self.webViewPWA.evaluateJavaScript("showToast(\(exc.toString() ?? ""))", completionHandler: { (result, error) in
guard error == nil else {
print("Script Error --> \(String(describing: error))")
return
}
})
}
}
///Inject 'user script' to WebPage
let userScript = WKUserScript(source: jsScript, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true)
webViewPWA.configuration.userContentController.addUserScript(userScript)
_ = jsContext?.evaluateScript(jsScript)
}
}
func jsScriptText() -> String? {
guard let jsPath = Bundle.main.path(forResource: "JSInterface", ofType: "js") else { return nil }
debugPrint("\n ** \n JS Path --> \(jsPath)")
do{
let jsScript = try String(contentsOfFile: jsPath, encoding: String.Encoding.utf8)
return jsScript
}catch{
debugPrint("Error")
return nil
}
}
来源:https://stackoverflow.com/questions/58134733/how-to-inject-js-file-to-interact-with-pwa-in-swift