3

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Adil Hussain
  • 30,049
  • 21
  • 112
  • 147
  • How and where do you invoke the alerts? And what do you intend to do that the UIWebView should know about the Alert? – joern Apr 10 '14 at 14:30
  • joern, it's invoked by the content/page in my `UIWebView`. – Adil Hussain Apr 10 '14 at 14:34
  • [This article](http://blog.impathic.com/post/64171814244/true-javascript-uiwebview-integration-in-ios7) might be useful to you. – 67cherries Apr 10 '14 at 14:38
  • I didnt understand what exactly you want to do but you cant detect it, but you can request and take an answer like stringOrWhateverIsYourReturnOnObjectiveC=[yourUIWebView stringByEvaluatingJavaScriptFromString:@"YourJavascriptFunction"]; – Yucel Bayram Apr 10 '14 at 14:53

1 Answers1

2

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.

joern
  • 27,354
  • 7
  • 90
  • 105