Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView: Can I disable the javascript alert() inside any web page?

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?

like image 817
Jack Avatar asked Aug 03 '10 20:08

Jack


People also ask

Should I use JavaScript alert?

Alerts should never be used for debugging unless you intend for it to stop the execution of the code for a purpose. Otherwise, you should be using console. log because alert can actually change the result of your code if your code involves asynchronous logic.

What does JavaScript alert mean?

The JavaScript alert() function is a function available on the global window object. It commands the browser to display a modal dialog with a message and an "OK" button.


2 Answers

Add this after your web view has loaded its content

[MyWebView stringByEvaluatingJavaScriptFromString:@"window.alert=null;"];
like image 61
pop850 Avatar answered Oct 06 '22 03:10

pop850


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).

like image 35
Vivin Paliath Avatar answered Oct 06 '22 03:10

Vivin Paliath