Page is not jumping if window.onhashchange is used - javascript

I am using hashchange event to ask a confirmation dialog box saying that the data in the current page will be lost, if moved.
I've implemented like this:
window.onhashchange = function() {
if(window.confirm("Do you really want to close?")){
}
};
This event is triggered correctly. But the page is not changing if the user clicks yes. What do I need in the {...}?

Please try
window.onhashchange = function() {
if (window.confirm("Do you really want to navigate?")) {
location.hash = location.hash; // or set the hash elsewhere and change here
}
};

Related

Reload Page on Focus

I have a Progressive Web App that I need to refresh every time the user opens it.
To achieve this I have tried:
1) First Option
window.onblur = function() {
window.onfocus= function () {
window.location = self.location;
}
};
2) Second Option
var blurred = false;
window.onblur = function() {
blurred = true;
};
window.onfocus = function() {
blurred && (window.location = self.location);
};
Credit of Option 1: https://stackoverflow.com/a/16406350/11843328
Credit of Option 2: https://stackoverflow.com/a/11313719/11843328
This work well but the problem is that sometimes whenever you click something, it reloads again. It basically reloads like 4 times in a row with some action. Other times it works as expected, just reloading once, but most of the times is like 4 or 5 times in a row.
I need it to reload just once when opened (on focus). Is there any alternatives I could try or any advice would be appreciated!
Make sure you're using window focus event. As others have pointed out, there is no need to use the blur event, as focus will only fire if the window focus was blurred.
You can use the window.location.reload method to reload the window as well.
window.addEventListener("focus", e => window.location.reload());
<p>Look for a flicker</p>
You don't need the onblur event. Using just the onfocus event will do the work.

Set variable on back button click

I have a function I dont want to run if the broswer back button was clicked. I am attempting to use something like the below:
var backButtonClicked = false;
window.onpopstate = function() {
alert("Back clicked");
backButtonClicked = true;
};
then later I am trying to use the variable like:
if(!backButtonClicked) {
//run function if not back button clicked
}
However with the code above the alert is not getting fired when I hit the back button.
window.onpopstate = function() {
alert("back clicked");
backButtonClicked = true;
};
history.pushState({}, '');
With the code above the alert gets fired when I click the back button, however the browser doesnt navigate back to the previous page unless I click the back button for the second time. Is there something I am doing incorrect here or is there a better approach to achieve what I am trying to do?
My coding skills are not very good when I have very little time to type. But maybe an eventlistener would be another approach to the problem you can maybe consider?
For examples and reference from an excellent source:
http://www.w3schools.com/js/js_htmldom_eventlistener.asp
Hope this helps, and good luck!

How to prevent navigation by browser buttons but not by links?

I want warn users if they leave the page by closing the browser or using the history buttons of the browser using the following javascript:
window.onbeforeunload = function(e) {
return 'Ask user a page leaving question here';
};
But my links and buttons on my website should work regardless of this. How can I achieve that?
The first way that comes to mind is to set a variable that tells you whether a link was clicked:
var linked = false;
window.onbeforeunload = function(e) {
if (!linked)
return 'Ask user a page leaving question here';
};
document.addEventListener('click', function(e) {
if (e.target.tagName === "A")
linked = true;
}, false);
That is, set a click event handler at the document level, that tests whether the clicked element was an anchor (or whatever else you want to allow) and if so sets the variable. (Obviously this assumes that you don't have other anchor element click handlers at a lower level that stop event propagation.)
var linkClicked = false;
window.onbeforeunload = function(e) {
if (!linkClicked){
linkClicked = false;
return 'Ask user a page leaving question here';
}
};
$(document).ready(function(){
$('a').click(function(e){
linkClicked = true;
});
});
Obviously this relies on JQuery to add the event handler to all links, but you could attach the handler with any other method, including adding onclick="linkClicked=true;" to every link on the page if you really have to.
Edit:
Just want to point out that if the user clicks a link that doesn't redirect them (e.g. a hashtag link to somewhere else on the page, or something that returns false / prevents the default action being executed) then this will set linkClicked to true and subsequently any browser based navigation won't be caught.
If you want to catch this, I would advise setting a timeout on the link click like so:
$(document).ready(function(){
$('a').click(function(e){
linkClicked = true;
setTimeout(function(){
linkClicked = false;
}, 500);
});
});
This will allow half a second for the window unload event to trigger before resetting the flag so that future navigation events are caught correctly. This still isn't perfect, but it probably doesn't need to be.
You can use the window.onbeforeunload event.
var check= false;
window.onbeforeunload = function () {
if (!check) {
return "Are you sure you want to leave this page?"
}
}
function CheckBackButton() {
check= true;
}
referenceElement.addEventListener('onClick', CheckBackButton(), false);
Us a confirmation prompt no?
like this? Intercept page exit event
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};
How to show the β€œAre you sure you want to navigate away from this page?” when changes committed? this may solve your problem How

Detecting form changes on beforeunload?

This has already been asked, I know, but I don't understand why this isn't working for me.
http://jsfiddle.net/M9tnP/16/
Trying to detect form changes, and if the user tries to navigate away, I want them to confirm that they will lose their changes...
var dirty = false;
$("form#add_item :input").change(function() {
dirty = true;
});
$("window").on('beforeunload', function() {
if (dirty) {
return 'You have unsaved changes! If you leave this page, your changes will be lost.';
}
});​
You need to set the event handler for onbeforeunload directly on the window object:
var dirty = false;
$("form#add_item :input").change(function() {
//alert("form changed!")
dirty = true;
});
window.onbeforeunload = function() {
if (dirty) {
return 'You have unsaved changes! If you leave this page, your changes will be lost.';
}
};​
Working example: http://jsfiddle.net/M9tnP/20/
You need:
$(window).on('beforeunload', function() {...})
, not:
$("window").on('beforeunload', function() {...})
(no quotes around window). $(window) wraps the window javascript variable inside a jQuery object, where $("window") selects all <window> tags on the page, of which there are exactly 0.
(Most of the time. In fact you can do $('body').append('<window></window>'), and then $("window") matches that new tag - but don't do that.)

window.beforeunload called twice in Firefox - how to get around this?

I'm creating a popup window that has a beforeunload handler installed. When the "Close" file menu item is used to close the popup, the beforeunload handler is called twice, resulting in two "Are you sure you want to close this window?" messages appearing.
This is a bug with Firefox, and I've reported it here, but I still would like a way to prevent this from happening. Can you think of a sane way of detecting double beforeunload to prevent the double message problem? The problem is that Firefox doesn't tell me which button in the dialog the user elected to click - OK or cancel.
<script type="text/javascript">
var onBeforeUnloadFired = false;
window.onbeforeunload = function ()
{
if (!onBeforeUnloadFired) {
onBeforeUnloadFired = true;
event.returnValue = "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
window.setTimeout("ResetOnBeforeUnloadFired()", 10);
}
function ResetOnBeforeUnloadFired() {
onBeforeUnloadFired = false;
}
</script>
Set a variable in the handler to prevent the dialog coming up the second time. Use setTimeout to reset it afterwards.
This is definitely a FF bug. I've reported it at https://bugzilla.mozilla.org/show_bug.cgi?id=531199
The best solution I've found is to use a flag global variable that is reset after so many milliseconds, say 500 (this ensures that the function can be called again, but not immediately after its appearance).
See last code in:
http://social.msdn.microsoft.com/Forums/en/sharepointinfopath/thread/13000cd8-5c50-4260-a0d2-bc404764966d
I've found this problem in Chrome 21, Firefox 14, IE 7-9, Safari 5 (on PC).
The following works on all of these browsers. If one removes the window.onbeforeunload function during the event this will prevent the second call. The trick is to reset the window.onbeforeunload function if the user decides to stay on the page.
var window_on_before_unload = function(e) {
var msg;
// Do here what you ever you need to do
msg = "Message for user";
// Prevent next "window.onbeforeunload" from re-running this code.
// Ensure that if the user decides to stay on the page that
// this code is run the next time the user tries to leave the page.
window.onbeforeunload = set_on_before_unload;
// Prepare message for user
if (msg) {
if (/irefox\/([4-9]|1\d+)/.test(navigator.userAgent))
alert(msg
+ '\n\nThe next dialog will allow you to stay here or continue\nSee Firefox bug #588292');
(e = e || window.event).returnValue = msg;
return msg;
}
};
// Set window.onbeforeunload to the above handler.
// #uses window_on_before_unload
// #param {Event} e
var set_on_before_unload = function(e) {
// Initialize the handler for window.onbeforeunload.
window.onbeforeunload = window_on_before_unload;
}
// Initialize the handler for window.onbeforeunload.
set_on_before_unload();
Create a global variable that is set to true inside the handler. Only show the alert/popup when this variable is false.
I use the following snippet to track the exitcount
When the page loads the following variable exitCount is initialized
if (typeof(MTG) == 'undefined') MTG = {};
MTG.exitCount=0;
and in the Window unload event
$(window).bind("beforeunload", function(){
if (MTG.exitCount<=0)
{
//do your thing, save etc
}
MTG.exitCount++;
});
I've found that instead of doing your own call to confirm(), just do even.preventDefault(); within the beforeunload event. Firefox throws up its own confirm dialog.
I'm not sure if this is the correct/standard thing to do, but that's how they're doing it.
I have a document opening another popup window with window.open. In the original window I have registered (with jquery) a listener for "unload" event like this:
var popup_window = window.open(...)
$(popup_window).on('unload', function(event) ...
I have came across this page because the event was effectively triggering twice. What I have found is that it is not a bug, it triggers twice because it fires once for "about:blank" page being replaced by your page and another for your page being unloaded.
All I have to do is to filter the event that I am interested in by querying the original event:
function (event) {
var original_url = e.originalEvent.originalTarget.URL;
if (original_url != 'about:blank')
{
... do cool things ...
}
}
I don't know if this applies to the original question, because it is a special case of a window opening another, but I hope it helps.

Categories