2009-10-14 39 views
4
<script language="javascript"> 
    alert("Hell! UIWebView!"); 
</script> 

我可以看到警報消息我一個UIWebView內,但我可以處理這種情況呢?我可以處理UIWebViewDelegate內部的警報嗎?

更新:

我加載一個網頁到我的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中處理它。

+1

咦測試?請詳細說明。 – Jacco 2009-10-14 09:05:37

+0

當警報被調用時,你想做其他事情嗎? – Xinus 2009-10-14 09:08:32

+0

如何處理?使用JavaScript,您可以重新定義alert()函數以執行您想要的任何操作,例如調用你自己的功能;你在問什麼? – Piskvor 2009-10-14 09:08:52

回答

3

如果通過「包含閃光燈」,您的意思是您正在加載到您的網頁視圖中的頁面中有Adobe Flash影片,恐怕您運氣不佳。移動Safari不支持Flash,很可能永遠不會。

在一般情況下,如果您希望在Web視圖中運行JavaScript以與託管它的本地應用程序進行通信,則可以加載僞造的URL(例如:「myapp:// alert?+ the + text + of + the +警告+雲+這裏。「)。這將觸發代理方法webView:shouldStartLoadWithRequest:navigationType:。在該方法中,檢查請求,並且如果正在加載的URL是這些內部通信之一,請在您的應用中觸發相應的操作,並返回NO

+0

謝謝。這是我需要的方式。) – 2009-10-15 13:04:54

15

較好地解決了這個問題,爲方法創建一個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 
+0

我同意這個解決方案更好。看起來像這是PhoneGap使用的。有了這個,你可以在javascript中調用alert('message'),你可以在頁面加載時做任何你喜歡的調用。 – 2012-01-17 13:05:50

+2

我在哪裏可以找到WebFrame所屬的框架? – Troy 2014-01-17 03:28:47

+2

@Boog我找不到runJavaScriptAlertPanelWithMessage !!! – onmyway133 2014-02-19 08:02:58

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

+0

它的工作很棒,非常感謝 – smoothumut 2016-04-27 12:20:05