Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What methods are blocking in Javascript?

I'm trying to override the standard confirm() method in Javascript (make a nice UI and stuff). I've read a 100 posts that it "can't be done", but I don't want to give up until I have given it a fair shot. :)

So, the real problem is of course that the confirm() method must block all javascript execution until the user selects an option. So, what are the methods in Javascript that have blocking behavior? I've been able to come up with 5:

  • alert() - does not suit me, because it displays an unwanted UI of its own;
  • confirm() - the same problem as alert();
  • infinite loop - even modern browsers will eat away CPU like crazy and display a "stop javascript?" prompt after a few seconds;
  • XmlHttpRequest in synchronous mode - sort of, but it involves server...
  • showModalDialog() - nice, but I need a specific design, plus there are some browser compatibility requirements...

The best approach I have so far is to create an <iframe> with the prompt (which then gets its own javascript execution thread) and block with XmlHttpRequest until the user has selected an option in the <iframe>. Unfortunately this involves passing the result forth and back between the server, and I'd like to make this 100% client-side. Also, it ties up a server thread while the dialog is opened, and there might be some browser-specific ajax-timeouts that apply.

Can anyone think of any other Javascript methods that block execution which might be (ab)used to achieve the desired effect?

like image 923
Vilx- Avatar asked Jun 05 '13 08:06

Vilx-


1 Answers

No, it can't be done for a good reason. The arbitrary, custom-styled user interaction in the page is always asynchronous (event-based), and therefore does not work with any type of blocking behaviour (the event that would stop the infinite loop would only occur after the infinite loop has finished).

All those blocking methods that you mentioned do their user interaction in a different environment than the page - the alert/confirm/prompt popups controlled by the browser, the different page loaded by the showModalDialog - and that environment would need be able to gain focus while the first is frozen.

Creating a setup like this reliable is difficult enough. However, you could try almost every javascript functionality (that does not involve async callbacks), as all JS operations are synchronous by default. If you want to further experiment, I would suggest to look at those methods that deal with different DOM environments (window.open, document.write, iframe.contentWindow cross-frame-access) to see whether you can get any of these to spawn a second environment which runs in parallel reliably.

like image 86
Bergi Avatar answered Sep 27 '22 15:09

Bergi