17

I am using UIWebView to load a URL.

Inside the page of that URL, it uses alert("whatever msg") as JavaScript. My UIWebView will pop up a window and show that alert message.

Is there a way to disable this kind of popup window or JavaScript alert window?

Ben
  • 51,770
  • 36
  • 127
  • 149
Jack
  • 3,913
  • 8
  • 41
  • 66

4 Answers4

19

Add this after your web view has loaded its content

[MyWebView stringByEvaluatingJavaScriptFromString:@"window.alert=null;"];
pop850
  • 3,157
  • 3
  • 29
  • 34
  • 4
    Very helpful, it is working. I have mention that I have to put this message in webViewDidStartLoad delegate method, just for other people who may want to know – Jack Aug 03 '10 at 20:44
  • 1
    This did not work for me since the JS that shows the alert was executed before the rendering of the page completed. I ended up blocking it on the native level: http://stackoverflow.com/a/21698251/154915 – ABeanSits Feb 11 '14 at 09:48
  • Even put it in webViewDidStartLoad does not work, either – onmyway133 Feb 19 '14 at 07:13
13

You can bind window.alert to another function. So:

window.alert = function() {
  //does nothing so effectively "disables" alert
};

Make sure you do this before you call any alerts. The neat thing about this is you can customize the way you display messages to the user. So you could override window.alert to log to the console (for debugging purposes) or you can render it on the page (with a lightbox or something similar).

Vivin Paliath
  • 94,126
  • 40
  • 223
  • 295
  • No problem. pop850's answer is probably what you want to accept since it addresses your concern directly. – Vivin Paliath Aug 03 '10 at 20:46
  • 4
    From my point of view this answer addresses the issue more gracefully, as `var a = null; a();` is a JavaScript runtime error. – LordTwaroog Jan 18 '13 at 15:25
1

Since a UIWebView translates all Javascript alerts into native UIAlertViews it is fairly simple to block it on the native end. Looking into UIAlertView.h there is only one public method for showing an alert which is conveniently called: - (void)show;.

@interface UIAlertView (Blocker)
@end

#import "UIAlertView+Blocker.h"

@implementation UIAlertView (Blocker)

- (void)show {
   return;
}
@end

You can find the answer here: https://stackoverflow.com/a/21698251/2377378

Community
  • 1
  • 1
Tai Le Anh
  • 268
  • 3
  • 10
0
let script = """
                window.alert=window.confirm=window.prompt=function(n){},
                [].slice.apply(document.querySelectorAll('iframe')).forEach(function(n){if(n.contentWindow != window){n.contentWindow.alert=n.contentWindow.confirm=n.contentWindow.prompt=function(n){}}})
                """
    webView.evaluateJavaScript(script, completionHandler: nil)