evaluateJavaScript with string in javascript

I am having a problem using the evaluateJavaScript function in WkWebView.


I would like to use evaluateJavaScript to call a javaScript function:

let javascript = “funcName(“<json string>”)”
webView?.evaluateJavaScript(javascript, completionHandler: nil)


I obviously cannot do that because of the two levels of quotes on the javascript variable. I cannot escape the quotes around <json string> because when this finally calls the javascript function, the parameter must be a string.


In summary, how can you use evaluateJavaScript when the javaScript must contain quotes (that cannot be escaped)?

Accepted Reply

I found an answer to my problem. I was trying to call a javascript function (funcName) with a data dictionary as the parameter. The trick is to base64 encode the data before passing it as the function parameter:


let transferData: [String: String] = [
  "key1": "value1",
  "key2": "value1"
]

do {
  let jsonData = try NSJSONSerialization.dataWithJSONObject(transferData, options: [])  // serialize the data dictionary
  let jsonEncodedData = jsonData.base64EncodedStringWithOptions([])   // base64 eencode the data dictionary
  let javascript = "funcName('\(jsonEncodedData)')"     // set funcName parameter as a single quoted string
  webView?.evaluateJavaScript(javascript, completionHandler: nil)
} catch let error as NSError {
  print(error)
}


Then on the javascript side, you need to decode the data:


function funcName(data) {
  var decodedData = window.atob(data);  // decode the data
  var transferData = JSON.parse(decodedData);  // convert the decoded data to a dictionary
}

Replies

I found an answer to my problem. I was trying to call a javascript function (funcName) with a data dictionary as the parameter. The trick is to base64 encode the data before passing it as the function parameter:


let transferData: [String: String] = [
  "key1": "value1",
  "key2": "value1"
]

do {
  let jsonData = try NSJSONSerialization.dataWithJSONObject(transferData, options: [])  // serialize the data dictionary
  let jsonEncodedData = jsonData.base64EncodedStringWithOptions([])   // base64 eencode the data dictionary
  let javascript = "funcName('\(jsonEncodedData)')"     // set funcName parameter as a single quoted string
  webView?.evaluateJavaScript(javascript, completionHandler: nil)
} catch let error as NSError {
  print(error)
}


Then on the javascript side, you need to decode the data:


function funcName(data) {
  var decodedData = window.atob(data);  // decode the data
  var transferData = JSON.parse(decodedData);  // convert the decoded data to a dictionary
}