我试图在页面的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
委托中也不起作用。
我也尝试使用webViewDidStartLoad
在performSelector:withObject:afterDelay:0
之后立即执行javascript,但无济于事。
有什么想法吗?
答案 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>