Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Broken in UIWebView's "Start Load" Callback

I'm trying to execute some JS before the page's onLoad event fires.

But I'm having trouble successfully calling stringByEvaluatingJavaScriptFromString in the webViewDidStartLoad delegate method.

To reproduce the issue, you can use the following code.

Delegate implementation:

-(void)webViewDidStartLoad:(UIWebView *)webView {
    [webView stringByEvaluatingJavaScriptFromString:@"window.valueHasBeenSet=true"];
}

View this HTML:

<html>
<head></head>
<body>

<script type="text/javascript" charset="utf-8">
    if (window.valueHasBeenSet)
    {
        // We enter this branch the first time
        document.write('<h3>Everything is OK. Value has been set.</h3>');
    }
    else
    {
        // We incorrectly enter this branch on reloads
        document.write('<h3>Error. Value has not been set.</h3>');
    }
</script>

<a href="javascript:window.location.reload()">Reload</a>

</body>
</html>

This page works on the first view ("Everything is OK.") but fails on all reloads, regardless of the reload method. As you'd probably expect, this doesn't work in the shouldStartLoadWithRequest delegate, either.

I also tried executing the javascript immediately following webViewDidStartLoad with performSelector:withObject:afterDelay:0, to no avail.

Any ideas?

like image 579
Ed McManus Avatar asked Aug 18 '10 05:08

Ed McManus


1 Answers

I managed to make it work using a NSTimer

- (void)viewDidLoad {
    timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(update) userInfo:nil repeats:YES];
}

-(void)update{
    if (Progress.progress <= 1.0) {
        [website stringByEvaluatingJavaScriptFromString:@"window.valueHasBeenSet=true"];
    }
}
like image 73
chris Avatar answered Oct 28 '22 10:10

chris