JavaScript broken in UIWebView "Start Download" interface

I am trying to execute some JS before the page onLoad event occurs.

But I am unable to successfully call stringByEvaluatingJavaScriptFromString in the delegate method of webViewDidStartLoad .

To reproduce the problem, 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 it does not work on all reboots, regardless of the method of reloading. As you probably expect, this does not work in the shouldStartLoadWithRequest .

I also tried to execute javascript right after webViewDidStartLoad with performSelector:withObject:afterDelay:0 , but to no avail.

Any ideas?

+6
iphone uiwebview
source share
2 answers

I managed to get it to work using 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"]; } } 
+1
source share

You need to do something like this:

Delegate Implementation:

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

.html file:

 <html> <head></head> <script type="text/javascript" charset="utf-8"> function foo (value) { if (value) { // 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>'); } document.write('<a href="javascript:window.location.reload();">Reload</a>'); } </script> <body> </body> </html> 
0
source share

All Articles