I have a UIWebView embedded in my view controller like this:
I have an outlet to my web view (_graphTotal
) and I can successfully load the contents of test.html
in it using this:
[_graphTotal loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];
I'm now trying to pass data to the web view and haven't had any luck. I have added the <UIWebViewDelegate>
and here's what I'm trying:
NSString *userName = [_graphTotal stringByEvaluatingJavaScriptFromString:@"testFunction()"];
NSLog(@"Web response: %@",userName);
And here are the contents of test.html
in my project:
<html>
<head></head>
<body>
Testing...
<script type="text/javascript">
function testFunction() {
alert("made it!");
return "hi!";
}
</script>
</body>
</html>
I can see "Testing..." in my webView, but I'm not seeing the alert nor the returned "hi!" string.
Any idea what I'm doing wrong?
Well the problem is that you tried to evaluate your javascript before the webview had the chance to load the page. First adopt the <UIWebViewDelegate>
protocol into your view controller:
@interface ViewController : UIViewController <UIWebViewDelegate>
Then connect the delegate of your webview to your view controller, make the request and finally implement the delegate methods. Here is the one that notifies you when the webview has finished loading:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.graphTotal loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *userName = [self.graphTotal stringByEvaluatingJavaScriptFromString:@"testFunction()"];
NSLog(@"Web response: %@",userName);
}
PS: One of the limits you must be aware of when you're evaluating javascript this way is that your script must be executed within 10 seconds. So if for example you've waited more than 10 secs to dismiss the alert you would get an error (failed to return after waiting 10 seconds). Find more about the limitations in the docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With