StringByEvaluatingJavaScriptFromString not working

I am trying to call a javascript function from a loaded local html file in a UIWebView but it is not responding

he looks like this

 NSString *script=[NSString stringWithFormat:@"sample()"]; if (tekst.loading) { NSLog(@"Loading"); } else { NSLog(@"Fully loaded"); [tekst stringByEvaluatingJavaScriptFromString:script]; } 

and in html

 <head> .... <script type='text/javascript'> function sample() { alert('Paznja'); } </script> ... </head> 
+7
source share
2 answers

It seems to me that you are not using a delegate in your UIWebView. If you set the delegate and put the Javascript call in the webViewDidFinishLoad: (UIWebView *) webView method, it works fine:

 UIWebView *wv = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, 0.0, 700.0, 700.0)]; [self.view addSubview:wv]; wv.delegate = self; [wv loadHTMLString:@"<html><head><script type='text/javascript'>function sample() {alert('Paznja');}</script></head><body><h1>TEST</h1></body></html>" baseURL:nil]; [wv release]; 

and in the same class:

 - (void)webViewDidFinishLoad:(UIWebView *)webView { [webView stringByEvaluatingJavaScriptFromString:@"sample()"]; } 

When I run this code, the warning message is working fine.

+13
source

Additional note: if you expect the object to return from a javascript function rather than a string, follow these steps:

 NSString *json = [self.webView stringByEvaluatingJavaScriptFromString:@"JSON.stringify(TestMethod())"]; 
0
source

All Articles