Browser Back Button on ajax call - javascript

When I log into my application the url of the application is localhost/#.
And then I made an search in my application where it goes with ajax call and after I get the results the url still remains same.
So, when I click on back button of browser my application is going back to the login page of my application. So I just need to restrict the page not to go to login page.
I am trying to do it this way:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.history.go(1);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
window.history.go(-1);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
But when I click on back button in my home page then the back button is getting disabled, instead I need to get the search results which I have performed earlier.

Related

how to refresh the page with original URL when URL has been changed via history.pushState()

I have used history.pushState() and now if the user refreshes the page then it is refreshing current URL which is not an original URL.
I tried detecting refresh page with a cookie, hidden filed but it is not working.
window.onload = function() {
document.cookie="PR=0";
var read_cookies = document.cookie;
var s = read_cookies;
s = s.substring(0, s.indexOf(';'));
if( s.includes("1"))
{
window.location.href = "https://www.google.com";
}
else{
document.cookie="PR=1";
}
loadURL();
};
function loadURL()
{
document.cookie="PR=1";
document.getElementById("visited").value="1";
var str="abc/b cd";
str=str.replace(/ /g, "-");
history.pushState({},"",str);
}
when user is refreshing the page I need original URL on that time.
This might be helpful. But you need control over the pushed url.
// this goes to your 'original' url
window.addEventListener('beforeunload', function (event) {
sessionStorage.setItem('lastPage', window.location.href)
}
// page with your pushed url
if (sessionStorage.getItem('lastPage') === 'PAGE_YOU_DONT_WANT_TO_BE_REACHABLE_DIRECTLY') {
window.location = 'PAGE_YOU_WANT'
}
I'm interested what the use case for this is. As far as my knowledge goes you can't suppress the refresh event completely.

Navigate stop only when going to another website

I am using following code to trigger the are you sure leaving website alert but for some reason its not recognising my if else condition in it and only works if I only put return true in window.onbeforeunload = function() { return true } . Is there a way I can trigger this alert only when user is navigating away from my website cause at the moment without if else condition its asking if user tries to navigate in the same website as well?
window.onbeforeunload = function() {
var location = window.document.activeElement.href;
if (typeof location != 'undefined')
{
console.log(location);
} else { reutn true; }
};
You can set a flag and toggle that flagged based on host of links that are clicked
var host = location.hostname,
allowNavigate = false;
window.onbeforeunload = function() {
if (!allowNavigate) {
return 'Message string';// not what actually gets displayed in most browsers these days
}
//don't return anything
return;
};
window.onload = function() {
document.querySelectorAll('a').forEach(function(a) {
a.addEventListener('click', function(e) {
allowNavigate = this.hostname === host;
});
});
};
The hostname on this page for example is "stackoverflow.com"
DEMO
You can add the "window.onbeforeunload" dynamically for the links you want to see the prompt message
and remove the "window.onbeforeunload" for the links you don't want prompt
<a onClick="a(true)" href="https://www.w3schools.com">Click here to get promt before navigate</a>
<br>
<a onClick="a(false)" href="https://jsfiddle.net/">Click here to navigate without promt </a>
<script>
function a(showPrompt){
window.onbeforeunload = showPrompt ? function(e) {return '';}: null;
}
</script>
https://jsfiddle.net/vqsnmamy/1/

Detect if the user clicked the “back” button - Mobile Browsers

I have very weird requirement.
Requirement says: On Product detail page,when product image is opened in lightbox then on pressing back button on browser in mobile, product detail page shall be shown, not previous page i.e. product grid page
So, i thought of searching that how to handle back button in cross browsers. Some solutions worked in Desktop browsers but none worked in Mobile Browsers
I tried below solution:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
};
Also tried this:
if (window.history && window.history.pushState) {
$(window).on('popstate', function() {
var hashLocation = location.hash;
var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];
if (hashName !== '') {
var hash = window.location.hash;
if (hash === '') {
alert('Back button was pressed.');
}
}
});
Tried this as well
window.onbeforeunload = function (e) {
var e = e || window.event;
var msg = ""
$("#blueimp-gallery").hide();
// For IE and Firefox
if (e) {
e.returnValue = msg;
}
// For Safari / chrome
return msg;
};
As you've no doubt learned, onbeforeunload provides a way to simply cancel the navigation event (see this answer for a good place to start), but it doesn't always work the way you want in all browsers (many just show a confirmation popup no matter what you do, for security reasons). Give this a shot first if you haven't already; I don't see any attempts at cancellation in your current code example, just history manipulation.
Failing that, using hash routing might help with this - preferably via a library that manages the URL hash as unique view routes (baked into Angular, React, etc) and pushes changes to the history for you. Giving the modal state a unique URL (which typically wouldn't be done in my experience) means that going 'back' would just close the modal instead of reloading the page.

Popstate event not triggered after pushing twice to history using history.pushState()

I’m working on an eshop where items are opened on top of a page in iframes. I’m using
history.pushState(stateObj, "page 2", http://localhost:8888/product-category/tyger/vara-tyger/?view=product&item=test-4);
in order to let customers copy the current url and use it to go to the current page with the item opened in an iframe. In addition, I’m using
window.addEventListener('popstate', manageHistory);
function manageHistory(event) {
if (!has_gone_back) {
var iframeOpen = false;
has_gone_back = true;
}
else {
var iframeOpen = true;
has_gone_back = false;
}
}
in order to let customers use their browser’s back and forward buttons for navigation (closing and opening the iframe).
However, when opening one product (calling history.pushState once), using the browser’s back button, and opening another product (calling history.pushState again), and going back again, manageHistory() is not called. The customer is taken to the first opened product but if pressing back again, manageHistory() is called.
I want manageHistory() to be called when pressing back on the product page opened second in order to add code to redirect customers to the category's start page when pressing back.
I’ve tried both adding Event Listeners for both opened products and also for only the first one. Any ideas what the problem may be?
From https://developer.mozilla.org/en-US/docs/Web/Events/popstate
Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript).
You can overwrite popState and replaceState, but what is generally a better idea is to create a wrapper which sets the url and then triggers your handler function.
Something like this...
function urlChangeHandler() {
var url = window.location.href;
// Whatever you want to do...
}
// Handle initial url:
urlChangeHandler();
window.addEventListener('popstate', urlChangeHandler);
var urlState = {
push: function(url) {
window.history.pushState(null, null, url);
urlChangeHandler();
},
replace: function(url) {
window.history.replaceState(null, null, url);
urlChangeHandler();
}
}
I have a similar file in one of my projects which updates the datastore based on the #hash...
import tree from './state'
// No need for react-router for such a simple application.
function hashChangeHandler(commit) {
return () => {
const hash = window.location.hash.substr(1);
const cursor = tree.select('activeContactIndex');
const createCursor = tree.select('createNewContact');
cursor.set(null);
createCursor.set(false);
(() => {
if(!hash.length) {
// Clean up the url (remove the hash if there is nothing after it):
window.history.replaceState(null, null, window.location.pathname);
return;
}
if(hash === 'new') {
createCursor.set(true);
return;
}
const index = parseInt(hash, 10);
if(!isNaN(index)) {
cursor.set(index);
}
})();
commit && tree.commit();
}
}
// Handle initial url:
hashChangeHandler(true)();
// Handle manual changes of the hash in the url:
window.addEventListener('hashchange', hashChangeHandler(true));
function createHash(location) {
return (location !== null) ? `#${location}` : window.location.pathname;
}
module.exports = {
push: (location, commit=true) => {
window.history.pushState(null, null, createHash(location));
hashChangeHandler(commit)();
},
replace: (location, commit=true) => {
window.history.replaceState(null, null, createHash(location));
hashChangeHandler(commit)();
}
}

Not load content of previous state in History.js to know when the back button was pressed

I have implemented State Aware URL on ajax call using history.js(using pushState method). Now when I click back button of any browser, it should load content of previous state using my ajax method.For this I have done following:
$(function () {
History.Adapter.bind(window, 'statechange', function () {
if (typeof (manualStateChange) !== 'undefined' && manualStateChange == true) {
var State = History.getState();
callingAjax(State.data.loadUrl);
}
manualStateChange = true;
});
});
Any time I change the state programmatically, set the bool to false:
function pushfun(stateUrl) {
manualStateChange = false;
History.pushState({ loadUrl: stateUrl, rand: Math.random() }, document.title, stateUrl);
}
But this is not work when I go to another page and then click on browser's back button & again click browser's back button. It only removes browser url and not replacing content of previous state.

Categories