【问题标题】:JavaScript Broken in UIWebView's "Start Load" CallbackJavaScript 在 UIWebView 的“开始加载”回调中中断
【发布时间】:2010-08-18 05:01:15
【问题描述】:

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

但我无法在 webViewDidStartLoad 委托方法中成功调用 stringByEvaluatingJavaScriptFromString

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

委托实施:

-(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,但无济于事。

有什么想法吗?

【问题讨论】:

    标签: iphone-sdk-3.0 uiwebview iphone


    【解决方案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"];
        }
    }
    

    【讨论】:

    • 感谢您抽出宝贵时间回答,克里斯。但是,这看起来不像是一个解决方案。除非服务器需要很长时间才能响应,否则这个计时器很可能不会在需要时触发。我真的在寻找一种确定性的解决方案,它不依赖于计时器。
    • 顺便说一下,这在间隔为 0 的情况下工作。但最好在 webViewDidStartLoad 中创建计时器并在 webViewDidStartLoad 和 webViewDidEndLoad 中使其无效,而不是让它始终运行。这似乎也支持 webViewDidStartLoad 在一些清理操作之前被调用的理论,并且在为下一个页面视图设置 web 框架之前窗口对象被破坏。
    【解决方案2】:

    你必须这样做:

    委托实施:

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

    【讨论】:

    • 这实际上会重写 web 视图的内容。我一直在寻找一种方法,通过在视图执行任何代码之前操作窗口对象来诱使页面认为它具有 Flash。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 2013-01-08
    相关资源
    最近更新 更多