History of JavaScript dialogs
JavaScript was introduced in 1995, and in the very first version of JavaScript
were methods on the window object namedalert()
,confirm()
,
and prompt()
.
While they fit into the JavaScript of the time, their synchronous API is problematic for modern browsers. Because the JavaScript engine needs to pause until a user response is obtained, the JavaScript dialogs are app-modal. And because the dialogs are app-modal, they commonly (and unfortunately) are used toharmourusers.
Because of this, the Chromium team highly recommends that you not use JavaScript dialogs.
Alternatives
There are many options for dialog replacement.
There are several choices for alert()/confirm()/prompt()
. For notifying the
user of events (e.g. calendaring sites), theNotifications API
should be used. For obtaining user input, theHTML <dialog> element
should be used. For XSS proofs-of-concept, devtool’s
console.log(document.origin)
can be used.
As for onbeforeunload
, it should be noted that it is already unreliable. As
Ilya Grigorik points out,
“You cannot rely on pagehide
, beforeunload
, and unload
events to fire on
mobile platforms.” If you need to save state, you should use the
Page Visibility API.
Changes
The ability for a page to specify the onbeforeunload
string wasremoved in Chrome 51.
(It was also removed by Safari starting with Safari 9.1 and in Firefox 4.)
It is planned that alert()/confirm()/prompt()
dialogs will not be app-modal,
but rather will be dismissed when their tab is switched from.
(Safari 9.1 already does this.)
We are investigating the possibility ofgating alert()/confirm()/prompt()/onbeforeunload
dialogs on site engagement,
so if the user isn’t engaging with the page, the page’s dialogs will not be
shown. Details have yet to be ironed out.
Because of these changes, if your site uses dialogs, it is highly recommended that you move to using the earlier-mentioned alternatives so that this will not affect you.