Link to home
Start Free TrialLog in
Avatar of Simon Leung
Simon Leung

asked on

Override JavaScript alert window

Can we create our own alert window to override the existing "alert(" xxx") in JavaScript ?
Avatar of Sam Jacobs
Sam Jacobs
Flag of United States of America image

Yes … just redefine it.  Example:
<script type="text/javascript">
   alert = function(msg) {
	console.log(msg);
   }

   alert('Replaced alert with console msg!');
</script>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
While you can easily replace the vanilla "alert" display mechanism, as mentioned above, keep in mind that the in-built "alert" functionality also pauses (suspends) execution of the underlying  JavaScript.

So when using any replacement you need to take the fact that execution of your underlying script will continue while the "alert" is displayed.

For instance, the JQuery plug-in above will give you a CSS styled "alert" message, but execution is continuing while the message is up.  So if you had multiple "alert" messages in your underlying script, they overlay each other.
The only alert you cannot modify for security reason are the one created/hardcoded by the browser
for example beforeunload event