iOS:当参数包含换行符时,evaluateJavaScript 不会调用函数 [英] iOS: evaluateJavaScript will not invoke function when parameter contains newline character

查看:116
本文介绍了iOS:当参数包含换行符时,evaluateJavaScript 不会调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标是调用包含在 WKWebView 中的网页内的回调函数.

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

evaluateJavaScript 在其参数包含换行符时中断,这意味着永远不会调用回调函数.

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

这是为什么?

userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) 当用户按下网页上的按钮时调用.

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)")
    }
}

推荐答案

一个似乎有效的选项是在参数中转义换行符:

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.

这篇关于iOS:当参数包含换行符时,evaluateJavaScript 不会调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆