Override JavaScript alert window

Simon Leung
Simon Leung used Ask the Experts™
Can we create our own alert window to override the existing "alert(" xxx") in JavaScript ?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Sam JacobsDirector of Technology Development, IPM

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

   alert('Replaced alert with console msg!');

Open in new window

Top Expert 2014
using this plugin : https://gist.github.com/andreasvirkus/5775d57375a48e2a3e21b3432742e53a

test page : https://jsfiddle.net/t19krfdm/

<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/jAlert@4.9.1/src/jAlert.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jAlert@4.9.1/dist/jAlert.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jAlert@4.9.1/dist/jAlert-functions.min.js"></script>
jQuery(function() {

Open in new window

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

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial