Search code examples
javascriptswiftwebview

iOS: Call JS function with 2 parameters in a Webview using SwiftUI


I am trying to call my JS function in my webview that takes 2 parameters using the evaluateJS however I do no appear to be hitting the function. (It works without params so I think I am getting the syntax wrong on the SwiftUI side. Wondering if anyone can advise please.

JS function:


function testFunction(message, ident) {
    document.getElementById('index_registernow').style.display = 'none';
}

SwiftUI side:

let token = (UserDefaults.standard.string(forKey: "Token") ?? "")
let ident = (UserDefaults.standard.string(forKey: "Ident") ?? "")

uiView.evaluateJavaScript("testFunction(\(token),\(ident))")


Solution

  • Assuming everything else is working (like there being values for Token and Ident and your Javascript function existing), the main issue looks like you're not wrapping your strings in quotes in Javascript:

    uiView.evaluateJavaScript("testFunction(\"\(token)\",\"\(ident)\")")