iOS: evaluateJavaScript will not invoke function when parameter contains newline character

眉间皱痕 提交于 2019-12-25 08:16:11

问题


The goal is to invoke a callback function inside a web page contained inside a WKWebView.

evaluateJavaScript breaks when its parameter contains the newline character, meaning the callback function never gets called.

Why is this?

userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) is invoked when the user presses a button on the web page.

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    let dict = message.body as! [String:AnyObject]
    let callback = dict["callback"] as! String

    // Fails
    let serializedClipboard = "hello\n" 

    // Works
    // let serializedClipboard = "hello" 

    webView!.evaluateJavaScript("\(callback)('\(serializedClipboard)')") { (object: Any?, error: Error?) -> Void in
        print("Done invoking \(callback)")
    }
}

回答1:


One option that seems to be working is to escape newline characters inside the parameter:

let escapedClipboard = serializedClipboard.stringByReplacingOccurrencesOfString("\n", withString: "\\n")

Please post suggestions if you see a cleaner solution.



来源:https://stackoverflow.com/questions/40292348/ios-evaluatejavascript-will-not-invoke-function-when-parameter-contains-newline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!