Emulate Javascript 'alert' blocking nature - javascript

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

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.

No, you can't (at least not in a browser). Javascript APIs are mostly async. alert/prompt are exceptions. However, it's not very hard to work with async prompts and callbacks.

A bit old, but in case it helps, I've found my solution with this:
var answer = confirm("are you sure?");
if(!answer)return;

Related

window.open affect web page

I have a link that opens a new window using window.open. The pop up works fine, however the normal web page stops loading objects (images, scripts, ajax scripts) and sometimes the page doesn't load at all.
Here is my code:
MyWindow=window.open('player.php','Player','width=500','height=300'); return false;
Is there anything I am doing wrong?
Thanks,
Peter
First of all, please be more specific: tell us more about your browser and which version, and possible your OS. It could be more related to the browser than to the web content.
Then on to the possible problem; you start with saying "I have a link that ...".
To me that sound like you use <a href="javascript:DoSomething()">. Or perhaps <a href="#" onclick="DoSomething()">.
I tried both in some modern browsers: Chrome v37, IE v11. Both browsers did not produce what you describe:
- Chrome v37 will happily keep on loading, even if I immediately click a "window.open()"-link on top of a (huge) webpage;
- IE v11 will someshow show "false", which is strange, but still not what you got.
In some cases I also got to deal with the popup blocker.
A general tip might be to NOT USE <a href> for things like this. Behaviour seems inconsistent across browsers, also these days there are better alternatives, such as <span onclick="">...</span> and <button onclick="">...<button> or by using JQuery or other frameworks (which I do not know much about).
Although this many not be a conclusive answer, maybe this can help you experiment on your own, and think about possible causes or alternative ways of doing things.
The behaviour you describe should definitely NOT normally happen. This is confirmed by robbmj's JSFiddle, that fails to reproduce the problem. That's evidence that something is going on in the main page that is not plain vanilla page loading, or your "link opening" has something unusual to it. Apart from the syntax error (you use four parameters, not three).
Since you do not supply information on either of these points (how do you load the main page? How do you trigger the popup-opening code?), we do not even know if the problem
might be browser-related; I'd start and try to test things in IE, Chrome and Mozilla to see
whether anything changes; this might provide some useful insights.
One possibility
A very strong possibility is that your inadvertent fourth parameter goes into the window.open() "replace" parameter, which is a boolean, and triggers undefined behaviour or simply an error that stops everything. You should have things somewhat working in IE and not working at all in Firefox.
You should also be able to see whether this is the case by using Firefox and the Firebug extension, or the Web Developer Console in Chrome.
Another possibility
A more esoteric possibility is that the way you define the link might make the browser believe you've actually moved on to another page, so that there's no point in continuing loading the current page. Depending on the browser, this might have to do with how the link is defined and could be remedied by defining it some other way.
For example it could conceivably happen if you had
...
which I suspect is what led user Tomzan to ask, "is the link something like javascript:...?"
So if this is the case, try with this instead (this works for me in IE9/Chrome/FF):
link
function openPopup() {
MyWindow = window.open('player.php', 'Player', 'width=500, height=300');
// Also try the following. You won't probably like the results (it should send the
// popup window behind), but if it works, it proves we're dealing with a browser
// issue there.
// Blur and refocus
// MyWindow.blur();
// window.focus();
// Just focus
// window.focus();
return false;
}
Workaround
A possibly acceptable workaround could be to disable the link altogether (or hide it via CSS), and only reactivate/show it upon main document being ready. This sidesteps the problem, even if user experience could be somewhat worse due to a longer wait.
But if it's so likely that a user clicks on the link before waiting for the whole page to load, I'd also consider not automatically loading the rest of the page at all, and reorganize information to provide a more streamlined navigation. Or maybe distribute it on two sequential pages. Again, unfortunately you did not supply enough information to do more than guess.
As you probably know, JavaScript is single threaded. Every event is queued until there is idle time for it to be executed.
In the case of window.open, both windows must share a single context to keep it thread-safe because the opened window can access to it's parent using window.opener.
I don't know how browsers implements it, but we can guess two possibilities:
Idle time is shared between the two windows. It means if the popup does many blocking statements, it can freeze the main window's events.
Only one of the two windows can be active, which depends on which one has the focus. In that case, all events may be paused in the main window when you're using the popup.
If you want a more precise answer, I need more details about your code.
document.addEventListener("DOMContentLoaded", function () {
//whatever the code
MyWindow=window.open('player.php','Player','width=500','height=300'); return false;
}, false);
Try to wrap the code in SetTimeout
setTimeout(function () {
window.open( .. )
}, 0);
Your document should be loaded first, then popup should be open, So write your javascript code in the scope of $(document).ready().
enter code here
$(document).ready(function(){
$("#clickme").click(function(e){
MyWindow=window.open('player.php','Player','width=500','height=300'); return false;
});
});

Waiting event before closing window using onbeforeunload

Context :
I have developped an application which require authentification. This application uses events for dialoging with a server. When the server answer, some events are send to the client (UI).
Problem :
When the user close the page, it is necessary to make a logout on the server. With my architecture, it's easy to call a method which perform this logout. But i would like that the user show the logout progress before closing the webpage. In fact, i would like to close the webpage only when a specific event (for example : disconnection_success), is well received.
Moreover, it's verry important to not launcg another webpage because event is received on the first webpage when the logout is successfull. (Because dialog is done throw XMLHttpRequest)
Test :
I already do some test using onbeforeunload but it seems that is difficult to customize the popup.
Do you have some ideas to resolve the problem ?
BR
There are some issues with this, but you're on the right track. You're right in that you should use onbeforeunload because it is the only event that you can have triggered upon the closing of the browser window. (I know you can use onunload but at that point you have no time to do anything.) The issue here is how much code do you want to execute. The onbeforeunload doesn't allow you much time before it starts to unload the page.
BTW, there are two different scenarios with onbeforeunload:
If you return a string inside the onbeforeunload event, it creates the pop-up that you were referring to. The issue here is that with the pop-up, you won't have enough time to execute code
The other option is not returning anything. Instead, call your logout methods. This should give your code enough time to execute before closing
I actually had a question very similar to this and ended up solving it myself: How to logout during onbeforeunload/onunload using Javascript
In your question you state that you want to have a progress bar displayed when they log-out. This is impossible to do when the user closes the browser. At the moment they close their window, you have lost all control, except for in the onbeforeunload (and onunload but don't use this), and that is why your code needs to be executed there. With that being said, you could anchor your logout button (I'm assuming you have one on your application) and have it display the progress bar.
Just think about what could happen if you actually did have that kind of control - where you could pop up windows and progress bars when the user is trying to close their browser window. You could pop up anything and restrict the user from having any reliable functionality. That is why it was programmed that the onbeforeunload (and unload) events are the only ones possible to access the closing of a browser. These events have some pretty strict guidelines to them that prevent any kind of possible mis-use. I understand the problem you're having, I was there and it stinks, but I think that is your only option if you were going to use onbeforeunload.

Preventing web browser from closing until AJAX response is returned [duplicate]

This question already has answers here:
JavaScript, browsers, window close - send an AJAX request or run a script on window closing
(9 answers)
Closed 6 years ago.
I've got a game that runs in the web browser (as a plugin) and what I'm trying to do is:
Detect if the user has decided to close the browser (Alt+F4, hitting the 'X' button etc)
Prevent the browser from closing whilst we fire a call to our web services to log that the user has closed the browser
Once we receive the response from the web services, release the lock and allow the browser to close as requested.
The main reason we want to do this is we're having some concurrency problems and going through our logs we want to isolate people logging out / closing the browser from genuine instances where the plugin has crashed.
I looked into doing this with JQuery (for X-Browser compatability - Opera won't work but we don't have any users on Opera anyway thankfully):
$(window).bind('beforeunload', function(e) {
e.preventDefault();
// make AJAX call
});
The problem is that this displays a confirmation dialog to the user ('Are you sure you want to leave this page') which the user might confirm before the AJAX call is sent.
So the question is, is there a way of preventing the browser from closing until the response is received? Also 'beforeunload' fires when the page is changed as well - is there a way of distinguishing clicking on a link from actually clicking close?
Grateful for any help wrt to this!
Its tricky business to avoid the browser window from beeing closed. Actually, there is no way to do that, beside returning a non-undefined value from the onbeforeunload event, like you described.
There is one possible suggestion I can make, that is creating a synchronized ajax request within the onbeforeunload event. For instance
window.onbeforeunload = function() {
$.ajax({
url: '/foo',
type: 'GET',
async: false,
timeout: 4000
});
};
In theory, this will block the browser for a maximum of 4 seconds. In reality, browsers will treat this differently. For instance, Firefox (I tested it on 9), will indeed not close the window immediately, but it also does not respect the timeout value there. I guess there is an internal maximum of like 2 seconds before the request is canceled and the window/tab gets closed. However, that should be enough in most cases I guess.
Your other question (how to distinguish between clicking a link), is fairly simple. As described above, onbeforeunload looks what is getting returned from its event handlers. So lets assume we have a variable which is global for our application, we could do something like
var globalIndicator = true;
// ... lots of code
window.onbeforeunload = function() {
return globalIndicator;
};
At this point, we would always receive a confirmation dialog when the window/tab is about to get closed. If we want to avoid that for any anchor-click, we could patch it like
$( 'a[href^=http]' ).on('click', function() {
globalIndicator = undefined;
});
As for the first part of your question, there is no reliable way of preventing the browser from closing other than using window.onbeforeunload. The browser is there to serve the user and if the user chooses to close his browser then it will do so.
For your second question, it is reasonably easy to distinguish a click on a link from other events triggering an onbeforeunload event by jQuery:
$('a').click(function(e) {...});
You could use this, for example, to make sure a click will not trigger unbeforeunload:
$('a').click(function(e) {window.onbeforeunload = null});
You can use below code to prevent the browser from getting closed:-
window.onbeforeunload = function() {
//Your code goes here.
return "";
}
Now when user closes the browser then he gets the confirmation dialogue because of return ""; & waits for user's confirmation & this waiting time makes the request to reach the server.
I'm pretty sure that what you want isn't possible using JavaScript. But since you have a browser plugin, shouldn't you be able to check whether your plugin object was cleaned up correctly? I'm not sure if you're using ActiveX, NPAPI or something like Firebreath, but these frameworks all have lifecycle methods that will be called on your plugin in the event of a normal shutdown, so you should be able to write something to the logs at this point. If the plugin crashes, these won't be called.

How do you know when a download has started from JavaScript?

Basically, I would like to wait for the IE save dialog box to open up, and then run the next line of JavaScript.
Something like:
`window.open(URL,"_self",...);`
window.alert("save dialog started");
Can this be done? Thanks
Grae
I came up with this:
var iframe = document.getElementById("dFrameID");
if(iframe.readyState=='complete')
window.close();
else
wait and call this again.
Seems to work fine.
This is IE solution only. Good luck with FF.
Javascript and the browser do not interact on this level.
I haven't tested this, but you may be able to use setTimeout(...) to get there. I have used it (only in IE) to wait until a print preview dialog had been closed.
The trick would be to wait in a loop (say five times) with enough time between those five loops to guarantee that the save dialog would have appeared. Once the dialog appears, all javascript processing should freeze. Then, when the box is closed, the javascript would start up again, and your setTimeout handler would execute.
Again, I have no idea whether this will actually work, and it would probably be different based on the browser you're using. It is also complicated by the likelyhood that your download window and alert window would be separate.

Jquery Effect Onunload

I would like to use the jquery slideUp effect when the user navigates away from the page just to make the page look cool as it closes.
I assume that I should use the onunload event but how can I delay the page closing long enough for the effect to run to completion.
One of the options that came to mind is effectively hijacking the page closing function, storing it in some variable and then executing it once I had run my effect but I have no idea how I would do that.
Any suggestions or alternative ideas are more than welcome
what you're looking for is the onbeforeunload event.
just a warning though... it should be really quick... or your visitors are probably going to hate it no matter how cool it looks
as to preventing the page from navigating away before the animation is done, that's a bigger problem... any animation is going to rely on setTimeout/setInterval and the page won't wait for those to complete before leaving.
Doing anything but closing the window when the users ask to is breaking a contract with the user. The browser window is not yours, it's the users, and no matter how cool the effect, it will inevitably annoy most of your users.
The onbeforeunload event is very restricted in what it can do. It must return a string, which is then used to prompt the user for a confirmation about leaving the page. It won't work for cool animations.
As far as I know, the only way to stop a user from leaving a page is the onbeforeunload event, which isn't cancelable. Instead, you return a string from that method, the browser prompts the user with a Yes/No dialog, life goes on. 276660 has more info about this.
I don't think you're going to have much luck with this one.
why not, instead of making a "cool" effect when a user simple want to go away from your website (even if the user closes the browser/tab the unload event will be fired) and annoying the simple user with that ... preventing him/her to return again...
...do that "cool" effect when a user reaches your website for the first time? as a normal intro effect?
I did that as a simple idea, you can see it here: http://www.balexandre.com/jmfc
I would agree 100% with Jonathan Fingland's answer, and add this.
In IE, (I'm not sure what versions support this, I know IE6 did) you can use some propriety meta tags to achieve fades etc when leaving the page. However, this is limited in browsers (IE only), so you're stuck for cross browser use.
You may find loading new content via AJAX would give you better control of effects and transitions, as well as reducing the annoyance factor to the user which can result from trying to hijack the browser actions in such a manner.
I would look at using a form of slider as mentioned above (see for instance http://webdesignledger.com/tutorials/13-super-useful-jquery-content-slider-scripts-and-tutorials),
or simply loading content panes in response to user clicks.
The only way I've found for delaying the window to close, is using an alert. If this is an acceptable compromise for your case, it will really delay the window destruction in memory, and allow your page timers to execute (of course, if user does not close the alert popup earlier than your animations finalize).
I recently used this approach so i could call a flex method through FABridge (which would otherwise be destroyed before the flex method call finishes). I'd like to hear your comments on this.

Categories

Resources