mybecks
mybecks

Reputation: 2473

UIWebView calling JS with arguments won't work

I have a UIWebView with a HTML page inside. Now I want to call a JS function inside the HTML and pass some values from Objective-C variables in it.

-  (void) webViewDidFinishLoad:(UIWebView *)_webView{
    NSString *selectedValue = [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"initWithDataFromObjC(%@)", @"hello"]];

    NSLog(@"webViewDidFinishLoad %@", @"YES");
}

The JS function in the HTML file:

  function initWithDataFromObjC(param1) {
           alert(param1);        
  }            

When I run the App in the simulator sometimes it loads my HTML correct, sometimes it stuck and don't finished loading. But nevertheless it don't show a popup with "hello"!

If I change the coding to the following:

-  (void) webViewDidFinishLoad:(UIWebView *)_webView{
    NSString *selectedValue = [_webView stringByEvaluatingJavaScriptFromString:@"initWithDataFromObjC()"];

    NSLog(@"webViewDidFinishLoad %@", @"YES");
}

The JS function without any parameters

function initWithDataFromObjC() {
      alert("hello");        
} 

The second construct will run without any issues. But I'm wondering why I don't work properly when I try to pass in some parameters?

BR & THX,

mybecks

Upvotes: 0

Views: 4232

Answers (1)

Jonathan Naguin
Jonathan Naguin

Reputation: 14776

Try with:

 NSString *selectedValue = [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"initWithDataFromObjC('%@')", @"hello"]];

or

 NSString *selectedValue = [_webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"initWithDataFromObjC(\"%@\")", @"hello"]];

Upvotes: 4

Related Questions