Window.OnBeforeUnload - javascript

I am trying to create a customisation to our existing software, which launches on this event. I need to be able to catch the window.onbeforeunload again once the user has made their choice.
I have tried wrapping the functions but can't seem to be able to overwrite the one which is loaded first. Does anyone have any ideas about how I can approach this, or force the newly assigned function to overwrite the old one.

You can not cancel the unload depending on which button the user presses, and you can not invoke this event manually. It's not even a standard event. Think of the vulnerabilities that could be used for malicious purposes if the event had the capabilities you want it to have.
This is about all you can do...
window.onbeforeunload = function() {
alert("one"); // First time, choose to stay on page
window.onbeforeunload = function() {
alert("two"); // Second time
}
}

Related

Use lodash or some other library to throttle a default click event listener on html tag

My intent is to throttle the click listener on some links and form submit buttons. The main idea was something like:
Click
<script>
window.onload = function() {
tags = document.findElementsByClassName("throttled-click");
for (let tag of tags) {
tag.onclick = _.throttle(tag.click, 1000, { 'trailing': false });
// Clearly doesn't work
}
}
</script>
The code above doesn't really work since no matter what I do, the default click event listener won't get throttled. If I pass in some other function (e.g. console.log("Throttled")), it will be throttled but the default click event listener won't.
Other than attempting to write my own throttling function, I'm out of ideas.
Note that I'm not a js dev so I may be missing something obvious.
EDIT: The goal of throttling the default click event listener is to prevent users from submitting too many forms when something hangs. Granted, form submissions usually entail a redirection which implicates that it's enough to simply disable the HTML click event after the first click.
My idea was to implement a throttle for cases when the page won't refresh or some edge case occurs where the request never reaches the server and the user actually has to click the submit button again.
I was able to do it with a custom implementation, I don't think there's a way to do it with existing standard libraries which I find kind of strange.

Stop browser from sending certain JavaScript events

There is a website which fires a function on when the tab is blurred. I don't want that to happen.
Is there a way I can stop javascript from firing window.onBlur event?
From initial search, I have come to the conclusion that I need to override the default function of javascript, which can be done using userscript managers like Greesemonkey.
I tried the following script in Greesemonkey:
window.onblur = null
This doesn't seem to have any effect and the webpage behaves same as previously.
Have look at Event.preventDefault() and Event.stopPropagation() if it helps your case.
If you would like to override the function which is called on the event, you can simply redefine it and insert it using a script manager. For example:
var originalCallbackFunction = callbackFuntion;
callbackFunction = function() { // Redefinition
/* Do something else */
}

Should I remove event listeners in jQuery?

My site works on jQuery + AJAX and has the only javascript file, which loads once when a user opens any page, so I'm used to add event listeners to all elements like: $(document).on(...).
In a while I'd noticed that there are too many .on(...) in the code, and I got afraid. I'd taken 9 pills and forced it to delete useless listeners every time when a user click on a link / back button.
function page_reload(){
if(c.r == 'http://example.com/page1'){
$(document).on('click', '#send', func.send);
$(document).on({mouseenter: func.me, mouseleave: func.ml}, '#chan');
}else{
$(document).off('click', '#send');
$(document).off('*', '#chan');
}
}
So is there any sense? Maybe a big number of listeners do some bad thing I don't know about?
When you attach a listener to an event, it does take memory and it can (if totally unchecked) cause memory related issues. In my experience, it is best to employ cleanup methods in your objects that, when a certain event fires, you use your .off() methods to unregister your event listeners.
The particular logic to these types of methods will vary depending on your project but something of the form:
var MyApp = {
cleanup: function cleanMyApp(event) {
this.off('#myId1', myMethod1);
this.off('#myId2', myMethod2);
}
}
$('document').on('ready', function() {
$(document).on('importantEvent', function(event) {
event.preventDefault(); // if you need to
MyApp.cleanup();
});
// or
$('#elem').on('something', MyApp.cleanup);
});
So yes, having too many listeners registered at a time can cause issues but you can monitor memory usage with your browser's dev tools and the like. In particular you can run out of stack (and heap?) memory and possibly crash the browser.
There is also a great answer here on dealing with these kinds of issues.

Different actions with onbeforeunload

I am working on a simple chat script using Ajax and want to indicate when a user leaves the page. Have read several docs and found this works:
window.onbeforeunload = leaveChat;
function leaveChat(){
... my code
return 'Dont go...';
}
Unfortunately (and logically), if they cancel the exit, my code is still executed and they are flagged as leaving even though they are still on the page? It should only execute if the confirm leaving the page. Any suggestions?
I would use onunload, but it doesn't seem to work in any of my browsers (Chrome, IE).
First, you should add the event handler using:
window.addEventListener('beforeunload', function() {
// Confirmation code here
});
window.addEventListener('unload', function() {
// fire pixel tag to exit chat on server here
// UI interactions are not possible in this event
});
For further research:
unload event reference
beforeunload event reference
Window.onunload reference

Javascript and onbeforeunload?

I have
<span class="cssButton"> <img src="http://uber-upload.com/img/icons/up_16.png" alt=""/> Uber-Upload! </span>
And i want to make it so that if you press that button, it also sets a variable that makes it so that if you try to leave the page, it will pop up one of those "Are you sure you want to leave this page" alerts to prevent people from accidently leaving while there is an upload going on.
Dont worry about unsetting the variable after the upload finishes, i'll add that, i just need one of you smart coders to make me a framework.
Thanks!
Add this declaration to the page:
var upcount = 0;
Change your onclick to:
onclick="++upcount; swfu.startUpload();"
If the swfu gives you some kind of event when it's done uploading, put this on it:
--upcount;
And add this handler:
window.onbeforeunload = function() {
if (upcount > 0) {
return "The upload is still in progress, leaving the page will cancel it.";
}
}
Where browsers respect the onbeforeunload, that'll work. And most of them do, most of the time. Where they don't, well, you tried. Note that by using a counter, you're allowing for multiple uploads.
You might consider attachEvent (IE) or addEventListener (standard) (or a library like Prototype or jQuery that evens out the differences for you) for attaching your events rather than using attributes. Using attributes (aka DOM0 handlers) is fairly old-fashioned and a bit limiting (only one handler per event per element). But it does still work.
function warnUser()
{
if(dataIsDirty)
{
return "You have made changes. They will be lost if you continue.";
}
else
{
// Reset the flag to its default value.
dataIsDirty = false;
}
}
function isDirty()
{
dataIsDirty = true;
}
function isClean()
{
dataIsDirty = false;
}
Then you use it just like on the onbeforeunload event.
window.onbeforeunload = warnUser;
dataIsDirty = false; //Or true, depending on if you want it to show up even if they dont' make changes)
Then to use it, just use the 'isClean' function to anything you don't want to trigger it(Save, for instance), or you can attach 'isDirty' to any event you want to trigger it before they leave (say, editing a form field).
Relying on onbeforeunload is sketchy at best. Because spammers have abused the behavior in the same way you're suggesting the ability for people to do this has been basically removed.
You can now only respond to onbeforeunload if the close event was fired from activating a button or such.

Categories

Resources