1

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)")
    }
}
4
  • Now that the question has been reformulated, it seems like a matter of escaping the newline inside of evaluateJavaScript ... one option is to encode to base64 (then decode on the JavaScript side), but is there a cleaner way to pass through newline characters? Commented Oct 27, 2016 at 19:37
  • why would you want to pass a new line in a callback parameter? Commented Oct 27, 2016 at 19:41
  • @VladimirM if you're serializing a paragraph of text, for instance. Commented Oct 27, 2016 at 19:43
  • Ah, you actually want to escape the \n. how to handle new-lines in JSON people seem to agree with your approach. Commented Oct 27, 2016 at 19:52

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

A big problem with this is that not all line break characters are \n.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.