我能在UIWebViewDelegate中处理警报吗?

4
<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中处理它。


当警报被调用时,您想做其他事情吗? - Xinus
如何处理?使用JavaScript,您可以重新定义alert()函数以执行您想要的任何操作,例如调用您自己的函数;这是您所询问的吗? - Piskvor left the building
3个回答

15

解决这个问题的更好方法是为UIWebView创建一个方法的类别(Category)

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'),并且在页面加载时可以进行任何调用。 - jake_hetfield

4
这似乎可以解决问题:
- (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上进行了测试。

3
如果你说的“包含flash”是指你在加载到web view中的页面中有Adobe Flash电影,恐怕你就没戏了。移动Safari不支持Flash,很可能永远都不会支持。
一般情况下,如果你想让在web view中运行的JavaScript与托管它的本地应用程序通信,你可以加载假的URL(例如:“myapp://alert?The+text+of+the+alert+goes+here.”)。这将触发webView:shouldStartLoadWithRequest:navigationType:委托方法。在该方法中,检查请求,如果正在加载的URL是这些内部通信之一,则在应用程序中触发相应的操作,并返回NO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接