cafedeichi
cafedeichi

Reputation: 765

How can i get the contents of javascript alert message on UIWebView?

i've been trying to get a message of "javascript alert" on UIWebView. although it's possible to get the one on Android WebView using by the "onJsAlert" event, UIWebView doesn't have a kind of the method... if anyone know the way to do it, please let me know.

Upvotes: 0

Views: 3814

Answers (1)

Horst
Horst

Reputation: 1739

You can't do it in simple way(ASAIK). Let's hack it! Try to re-define your alert function, remember to pass your alert message of the js alert in

I AM A SPECIAL URL FOR detecting

- (void) webViewDidFinishLoad: (UIWebView *) webView
{
    [webView stringByEvaluatingJavaScriptFromString:@"window.alert = function(message) { window.location = \"I AM A SPECIAL URL FOR detecting\"; }"];
}

And get what you want in the alert url:

- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL* url = request.URL;

    // look for our custom action to come through:
    if ( [url.host isEqualToString: @"I AM A SPECIAL URL FOR detecting"] )
    {
        // parsing the url and get the message, assume there is a '='for value, if you are passing multiple value, you might need to do more
        NSString* message = [[[[url query] componentsSeparatedByString: @"="] lastObject] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        // show our alert
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle: @"My Custom Title"
                                                     message: message
                                                    delegate: nil
                                           cancelButtonTitle: @"OK"
                                           otherButtonTitles: nil];

        [alertView show];

        return NO;
    }
    return YES;
}

Upvotes: 3

Related Questions