在UIWebView的“Start Load”回调中破解了JavaScript

时间:2010-08-18 05:01:15

标签: iphone-sdk-3.0 uiwebview iphone

我试图在页面的onLoad事件触发之前执行一些JS。

但是我在stringByEvaluatingJavaScriptFromString委托方法中成功调用webViewDidStartLoad时遇到问题。

要重现此问题,您可以使用以下代码。

代表实施:

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

查看此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>

此页面适用于第一个视图(“一切正常。”),但无论重新加载方法如何,都会在所有重新加载时失败。正如您可能期望的那样,这在shouldStartLoadWithRequest委托中也不起作用。

我也尝试使用webViewDidStartLoadperformSelector:withObject:afterDelay:0之后立即执行javascript,但无济于事。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

我设法使用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 :(得分:0)

你必须做这样的事情:

代表实施:

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

.html文件:

<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>