I want to use onbeforeunload to give a message to users before leaving certain pages.
Is it possible to know which url they are supposed to jump to at the onbeforeunload event?
Thanks
Is it possible to know which url they are supposed to jump to at the onbeforeunload event?
No, definitely not. The onbeforeunload event tells you only that the page is about to be unloaded, but not why.
It depends on how the user is leaving the page.
If they are typing an url in the address bar - then you're out of luck. As far a I know there's no way to capture the url of an address bar jump.
If they are clicking on a link contained somewhere on the page - that you can use the click event to capture the url and then decide how you want to handle things.
I posed a similar question
How can i get the destination url of a link on the web page in the javascript onbeforeunload event?
because I had a project to fix a wholesale order form. During the process of filling out an order my client's customers would go back to the catalog to check on a product's detail page and loose the current information on their order form.
By using the code below (which uses JQuery though I'm sure you could create the same thing in pure Javascript if you had to) I could tell when the user clicked a link that would leave the order form and then give them the option of opening the link in a new window/tab or loading the url in the current window and loosing their form data, or just returning to the form. This code works with all of the major browsers, at least their more recent versions.
$('body a').click(function(e) {
//if link references a page element
if ($(this).attr('href').charAt(0)=="#") {
return;
}
//check if link is to same window
var pathname = window.location.pathname;
var pathname2 = $(this).attr('href');
pathname2 = pathname2.replace(/^.+\.\//, '');
if (pathname.indexOf(pathname2) >= 0) {
//link clicked is contained on same page
//prevent page from getting reloaded & losing data
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
return;
}
//link clicked on is another page
if (hasMerchandise) { //var to indicate user has items on order form
//give user options: leave page, open link in other page, stay, etc.
// $('.popupForm-handleExitRequest').click(); //roll your own code
//prevent page from getting reloaded & losing data
//in case user wants to cancel page change or open link in another window
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
} else {
//load new page
$(this).removeAttr('target');
}
});
Related
Without clicking/touching on anywhere inside page when click browser back button, navigation should be disable.
Below implementation only work when click inside page.
history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () =>{ // not getting activate without clicking inside page
console.warn('DISABLE BROWSER NAVIGATION');
history.forward();
}
one of the best way is to open your application in a popup without controls but again depending upon your requirement this may not be applicable. Hope this helps. Something like below
function openPopup(){
var pathname = (window.location.pathname);
window.open(pathname+'openpagePopup.html','','width=800,height=450,toolbar=no, menubar=no,scrollbars=no,resizable=no,dependent,screenx=80,screeny=80,left=80,top=20,scrollbars=no');
return false;
}
The otherways are not trustworthy like you can show user an alert, but can not disable the back button, as per my knowledge. If you do the below make sure you check browser compatibility.
window.onbeforeunload = function() {
return "Write something here";
};
Update : I found there is a way to handle the page history. Incase that works, I have never tried, here is a link
JS - window.history - Delete a state
Scenario: I want to set some variable in my localstorage whenever user leaves the page.
Using window.onbeforeunload I get the event that user is about to leave the page. But I want to set different variable value when user refreshes and different on page navigation
var someVar;
//when refresh someVar = 1;
//When user clicks on any link which is not the same page, someVar =2
Is this possible to detect if user is refreshing or about to leave page?
Based on your comment I am updating my answer. You can't detect navigation type on beforeunload event or with any other method because it is browser dependent. But I can provide you a way to detect back or refresh after the page loaded. I hope it will be useful.
Please check performance navigation
if (performance.navigation.type == PerformanceNavigation.TYPE_RELOAD){
//Reload
}
if (performance.navigation.type == PerformanceNavigation.TYPE_BACK_FORWARD){
//Back Button
}
I have research this topic through the community, although I cannot find an answer. I am using Bronto's direct add feature (attempting to use it), The documentation isn't that great.
In summary, the href link subscribes the user on the email list. The only problem is that this link opens a new page. When I want the user to stay on the same page. I though about doing a redirect, when clicking the link, though I am not sure if that would work.
I have tried this:
//Html
<a id="subscription" href="http://example.com">Subscribe</a>
// Jquery
$("#emailsubscribe").click(function(e){
e.preventDefault();//this will prevent the link trying to navigate to another page
//do the update
var href = "http://example.com";
//when update has finished, navigate to the other page
window.location = "href";
});
The goal is that I am trying to make it where the user clicks on the link, it subscribes them to the email list, but immediately redirects them back, without opening another window.
You're looking for AJAX. This allows you to make requests without actually navigating to a page. Since you're using jQuery
$("#emailSubscribe").click(function (e) {
e.preventDefault();
$.get("http://www.myurl.com", function (data) {
//All done!
});
});
You have 3 options:
Do an AJAX request to subscribe the user
$('#emailsubscribe').on('click', function () {
$.get('/email-subscribe/' + USER_ID, function () {
// redirect goes here
window.location = 'REDIRECT_URL';
});
});
Use an iframe and when the iframe has loaded close the iframe (ugly, hacky, not recommended)
Have the subscribe page redirect the user back. Aka do the common messages of "You have been subscribed. Redirecting back in 5seconds...". You would need to pass the redirect link to the subscribe page, aka
window.location = '/subscribe/USER_ID?redirect_to=/my-redirect-page'
You need to refer the var, instead of typing another string to redirect.
//Html
<a id="subscription" href="http://example.com">Subscribe</a>
// Jquery
$("#emailsubscribe").click(function(e){
e.preventDefault();//this will prevent the link trying to navigate to another page
//do the update
var href = "http://example.com";
//when update has finished, navigate to the other page
window.location = href; //<<<< change this.
});
Is it possible to capture what link on the web page the user clicked on?
Not talking about if they manually entered an url in the address bar or if they clicked on the back button - but an existing link or menu item on the current page.
This is for a commercial web page that has a standard header & footer containing links to other pages on the company's web site.
They have a complicated order form where it's not practical to try saving & restoring the state of the form.
If in the process of filling out an order the customer needs to visit another page on the web site - to review product, etc.. Ideally I would be able offer the option of opening the link in another browser window or tab instead of leaving the page so that the user doesn't loose the work they've put into the order.
I know that I could have a different set of headers & footers that are written to open their links in another window/tab but to simplify maintenance & updating I'm trying to minimize the number of variations used. Also it is possible that the user wants to abandon the order form and may get confused if in trying to do so that another window opens instead.
I am using JQuery & Javascript.
Instead of having a completely different set of headers/footers you could replace all links in certain areas with links that open in a new window like so:
$('#header a, #footer a').each(function() {
$(this).attr('target', '_blank');
});
This is what I came up with to handle this and it is working for me.
Detects when user clicks on a page link then evaluates link to determine how to handle appropriately. It does not work for links typed in the browser address bar.
I use jquery magnific-popup (http://dimsemenov.com/plugins/magnific-popup/) to create a popup window (.popupForm-handleExitRequest in my code) that offers the user the option of opening link in same window (and losing their order data), in new window or returning to order form.
$('body a').click(function(e) {
//if link is reference to page element
if ($(this).attr('href').charAt(0)=="#") {
return;
}
//check if link is to same window
var pathname = window.location.pathname;
var pathname2 = $(this).attr('href');
pathname2 = pathname2.replace(/^.+\.\//, '');
if (pathname.indexOf(pathname2) >= 0) {
//link clicked is contained on same page
//prevent page from getting reloaded & losing data
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
return;
}
//link clicked on is another page
if (hasMerchandise) { //var to indicate user has items on order form
//give user options: leave page, open link in other page, stay, etc.
// $('.popupForm-handleExitRequest').click(); //roll your own code
//prevent page from getting reloaded & losing data
//in case user wants to cancel page change or open link in another window
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
} else {
//load new page
$(this).removeAttr('target');
}
});
I am trying to handle browser back button event but i could not find any solution.
I want to ask user if he clicks on browser back button using "confirm box" if he chooses ok i have to allow back button action else i have to stop back button action.
Can any one help me in implementing this.
Warn/confirm User if Back button is Pressed is as below.
window.onbeforeunload = function() { return "Your work will be lost."; };
You can get more information using below mentioned links.
Disable Back Button in Browser using JavaScript
I hope this will help to you.
You can also add hash when page is loading:
location.hash = "noBack";
Then just handle location hash change to add another hash:
$(window).on('hashchange', function() {
location.hash = "noBack";
});
That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.