Using winalert.js to handle window.alert in IFrame

As you may have already heard by now that Google Chrome is effectively stopping the usage of alert, prompt and confirm messages for pages loaded inside Iframe.

You can find more information Chrome update – Feature: Remove alert(), confirm(), and prompt for cross origin iframes

A warning message is displayed when a page is trying to display alert in Chrome

winalert.js, is a small library which encapsulates the window.alert function, to raise a custom event winalert on the window object.

winalert.js event arguments

winalert.js will raise a custom event winalert, with the following event arguments

  • detail – Contains the actual message passed to the window.alert
  • getMessage() – helper function which will return the actual message passed to the window.alert

NOTE: The winalert event is only raised when the page is hosted inside an Iframe

Usage

Download the winalert.js file from Github – winalertjs

Add a reference to the downloaded JS file

<script href=”http://path-to-winalertjs-javascript-file.js”>%lt;/script&gt;

Activate winalertjs

winalertjs.activate();

By default, winalert events will be raised only for pages which are loaded inside Iframe only.
If you want to raise the winalert for pages which are not loaded in Iframe also.

winalertjs.activate(true);

Create an eventhandler which will handle( 🙂 )the winalert event

// Use the event arguments for 'winalert', to get the message from the original ```window.alert``` invocation
window.addEventListener('winalert', function(earg) {

  // write the alert messages to the console logger
  console.log('winalert event handler ::: ' + earg.getMessage());

});

You can even use custom JS libraries to display a nice looking alerts, but topic is beyond the scope of our topic here 🙂

Leave a comment