lostsource lostsource - 2 months ago 6
Javascript Question

Emulate Javascript 'alert' blocking nature

Is it possible to create a custom modal message which 'blocks' the execution of the script until a user input?

For example, how can you achieve this without using the native window alert / prompt functions?

setInterval(function(){
alert('Click OK to Continue'); // timing stops until user hits ok
},4000);


I know you could have your custom dialog invoke a callback function on user input, but I'm interested in being able to force this blocking behaviour

Answer

Is it possible to create a custom modal message which 'blocks' the execution of the script until a user input?

No. There is no way to block either execution or user interaction as effectively as a native popup (since with custom popups the user is always technically capable of using developer tools to get out of it).

However, as pst says in the comments on the question, asynchronous lightboxes are not onerous, and are almost as effective at blocking user interaction as popups, so I recommend finding a library that provides lightboxes you like and running with that.

For example, how can you achieve this without using the native window alert / prompt functions?

You can't use that code to do what you say it will even with native window alert / prompt functions (see this fiddle - wait 4 seconds before closing popup). You'd need the following:

function timeoutFunction() {
    alert('Click OK to Continue');  // timing ACTUALLY stops until user hits ok
    setTimeout(timeoutFunction, 4000);
}
setTimeout(timeoutFunction,4000);

Which is something that you can't implement (precisely - see above on lightboxes) without native popups.

Even while(true) loops won't generally block as well as a popup - firefox at least has a "stop script" message that pops up after it's been going too long, and I'm fairly sure other major browsers do too.