Search code examples
iosuiwebviewuiwebviewdelegate

Possible for UIWebView to detect when a Javascript dialog is about to be shown?


I'm new to iOS development. I come from an Android background.

I'd like to know whether it's possible for a UIWebView to detect when a Javascript alert/confirm/prompt dialog is about to be shown? (Similar to how the shouldStartLoadWithRequest method of UIWebViewDelegate is called before a web view begins loading a frame.)

The Android equivalent of what I'm looking for is WebChromeClient's onJSAlert(...), onJsConfirm(...) and onJsPrompt(...) methods, and by means of these methods the application can decide whether to show a given dialog or to block it.


Solution

  • UIWebView does not have a method that is called when a Javascript alert is about to be shown. However you can use shouldStartLoadWithRequest: to inform the UIWebView about the alert and then decide whether to display it or not:

    In your Javascript when you want to invoke an alert do this:

    window.location.href = "alert://MESSAGE_TEXT";
    

    In your UIWebView's delegate you can intercept that request and decide if you want to invoke the alert via javascript:

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
       switch (navigationType) {
          case UIWebViewNavigationTypeOther:
             if ([[request.URL scheme] isEqualToString:@"alert"]) {
                NSString *message = [request.URL host];
                if (SHOULD_SHOW_ALERT) {
                   // the alert should be shown
                   [webView stringByEvaluatingJavaScriptFromString:@"showAlert()"];
                } else {
                  // don't show the alert
                  // just do nothing
                }
    
                return NO;
             }
             break;
          default:
            //ignore
       }
       return YES;
    }
    

    I don't know if you need to send the message text to the UIWebView but I included it so that you can see how you can send parameters to the UIWebView. You could add more parameters in the URL's path.

    Obviously you have to exchange SHOULD_SHOW_ALERT with your own if clause that's determines whether to show the alert or not and you have to add the showAlert() function to your Javascript.