uiWebview call javascript function syntax

10,655

As per this answer on another similar question, you need to implement the UIWebView delegate method webViewDidFinishLoad:, and in there implement [myWebView stringByEvaluatingJavaScriptFromString:@"myJavaScriptCode()"].

In order for this to work you need to set the delegate on the UIWebView instance and implement the delegate method mentioned above so that the JavaScript is executed after the page has loaded.

The documentation for - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script can be found here.

Now for the other part of your question (thanks for clarifying!).. to concatenate strings in Objective-C you can use the NSString class method stringWithFormat:.

For example, to pass two Objective-C values to a JavaScript string, you could do something like this:

// Substitute your Objective-C values into the string
NSString *javaScript = [NSString stringWithFormat:@"setVars('%@', '%@')", var1, var2, nil];

// Make the UIWebView method call
NSString *response = [webViewA stringByEvaluatingJavaScriptFromString:javaScript];
Share:
10,655
Jaume
Author by

Jaume

Updated on June 27, 2022

Comments

  • Jaume
    Jaume almost 2 years

    I am migrating my app from android to iOS and for following line, compiler returns me an error on iOS,

    webviewA.loadUrl("javascript:setVars(\"" + var1 + "\",\"" + var2 + "\")"); //properly executed on Android

    for iOS I am trying,

    [webViewA stringByEvaluatingJavaScriptFromString:@"javascript:setVars(\"" + var1 + "\",\""  + var2 +  "\")"];
    

    which would be correct syntax for iOS? Thank you.