7

I am trying to call a javascript function from loaded local html file in UIWebView but it deosn't respond

it look 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> 
1
  • 1
    Unrelated to your question, but no need to call stringWithFormat: here. Just assign the string literal directly: NSString *script = @"sample()"; Commented Jul 11, 2011 at 21:09

2 Answers 2

13

It looks to me as if you are not using a delegate on your UIWebView. If you set a delegate and put the call to the Javascript into the "- (void)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 alert message works fine.

Sign up to request clarification or add additional context in comments.

Comments

0

Additional note, if you are expecting an object back from the javascript function rather than a string then do the following:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.