我可以在 UIWebViewDelegate 中处理警报吗?

IT技术 javascript iphone uiwebview
2021-03-04 04:55:55
<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 中处理它。

3个回答

更好的解决这个问题的方法是为方法创建一个 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'),你可以在页面加载时做任何你喜欢的调用。
2021-05-18 04:55:55

这似乎做到了:

- (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 上测试。

如果“包含 Flash”是指您加载到 Web 视图中的页面中包含 Adob​​e Flash 电影,恐怕您就走运了。Mobile Safari 不支持 Flash,而且很可能永远不会。

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

谢谢你。这就是我需要的方式。)
2021-05-10 04:55:55