【问题标题】:Can I handle alert inside UIWebViewDelegate?我可以在 UIWebViewDelegate 中处理警报吗?
【发布时间】:2010-12-06 14:40:28
【问题描述】:
<script language="javascript">
    alert("Hell! UIWebView!");
</script>

我可以在我的 UIWebView 中看到警报消息,但我可以处理这种情况吗?

更新:

我正在将网页加载到我的 UIWebView 中:

- (void)login {
    NSString *requestText = [[NSString alloc] initWithFormat: @"%@?user=%@&password=%@", DEFAULT_URL, user.name, user.password];    // YES, I'm using GET request to send password :)
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestText]];
    [webView loadRequest:request];
}

目标页面包含一个JS。如果用户名或密码不正确,此 JS 将显示警报。 我无法访问其来源。 我想在我的 UIWebViewDelegate 中处理它。

【问题讨论】:

  • 当 alert 被调用时你想做其他事情吗?
  • 怎么处理?使用 JavaScript,你可以重新定义 alert() 函数来做任何你想做的事情,例如调用你自己的函数;你问的是这个吗?

标签: javascript iphone uiwebview


【解决方案1】:

这似乎可以做到:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    JSContext *ctx = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    ctx[@"window"][@"alert"] = ^(JSValue *message) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"JavaScript Alert" message:[message toString] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    };
}

注意:仅在 iOS 8 上测试。

【讨论】:

    【解决方案2】:

    更好的解决这个问题的方法是为方法创建一个Category for UIWebView

    webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:
    

    这样您就可以以任何您喜欢的方式处理警报事件。我这样做是因为我不喜欢 UIWebView 将源文件名放在 UIAlertView 标题中时的默认行为。类别看起来像这样,

    @interface UIWebView (JavaScriptAlert) 
    
    - (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame;
    
    @end
    
    @implementation UIWebView (JavaScriptAlert)
    
    - (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
        UIAlertView* dialogue = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"Okay" otherButtonTitles:nil];
        [dialogue show];
        [dialogue autorelease];
    }
    
    @end
    

    【讨论】:

    • 我同意这个解决方案更好。似乎这就是PhoneGap使用的。有了这个,你可以在你的 javascript 中调用 alert('message') ,你可以在页面加载时做任何你喜欢的调用。
    【解决方案3】:

    如果您所说的“包含 Flash”是指您正在加载到 Web 视图中的页面中包含 Adob​​e Flash 影片,那么恐怕您就不走运了。移动版 Safari 不支持 Flash,而且很可能永远不会。

    在一般情况下,如果您希望在 Web 视图中运行的 JavaScript 与托管它的本机应用程序通信,您可以加载虚假 URL(例如:“myapp://alert?The+text+of+the+警报+去+这里。”)。这将触发webView:shouldStartLoadWithRequest:navigationType: 委托方法。在该方法中,检查请求,如果正在加载的 URL 是这些内部通信之一,则在您的应用中触发适当的操作,并返回 NO

    【讨论】:

    • 谢谢。这是我需要的方式。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 1970-01-01
    • 1970-01-01
    • 2015-10-03
    • 2022-07-01
    相关资源
    最近更新 更多