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 ?
JavaScriptjQuery

Avatar of undefined
Last Comment
lenamtl

8/22/2022 - Mon
Sam Jacobs

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
leakim971

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Graham N.

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

The only alert you cannot modify for security reason are the one created/hardcoded by the browser
for example beforeunload event
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy