How to maintain states of selection on back button - javascript

I am using HTML and JavaScript to write Android APP, but I have a problem that when go back from current page to the previous page, the page is reloaded and the selection and setting when I made in the first goes to default.
For example: On the first page user can select country and city and then navigate to second page.
If user clicks on back button (which calls window.history.back(); or href="javascript:history.back(-1);")
, then all the selection he made are lost and default selections are shown.
It works fine in native browser of Android.
How to maintain state of selection?
Thanks in advance!

You need to make dummy history to disable history back button.
var originalHash = document.hash || "#dummyMain"
location.assign("#dummyBack")
location.assign(originalHash)
window.addEventListener("popstate",function(){
if(location.hash == "#dummyBack"){
window.history.pushState(null,null,originalHash)
}else{
originalHash = location.hash
}
});
The code above create dummy page history and checks if page transitions are occurred via history back button or not and if so,force page move to current page again to stop history back action.
Since You didn't put any code in the question,It's hardly possible to say it will work or not but I guess once you load this code,it should disable all page back action.
If you are using PC/Mac to use this site,please try to open developper tools/firebug javascript console and copy/paste the code and press history back button to see how it works.

I find a good way to maintain the data of previous page, which use localStorage store the data as key value before leaving this page and again when come back to this page you can get your data again from localStorage` and display it.
Because the data which is loaded by AJAX will be last on history back.
Hope this help someone may has this problem.

Related

How do you prevent a user from cancelling a page redirect?

I have a line of code:
location.href = 'payments/basic.php';
It works fine, but a user can simply press the Esc key to cancel the operation. I tried to use an event listener to prevent the Esc key from being pressed, but it only works while the user is on the initial page. As soon as they are being redirected, it stops working and they can quickly press the Esc key or the big X beside the address bar in their browser to cancel the redirect.
Is there a way I can completely prevent that?
Edit:
The reason I want to do this is that upon login, they are automatically sent to the index page. I have a flag in my DB which checks if a user has made payment. And then on the index page, I have a little script that queries the DB to check if the flag is true or false. If it's false, they are immediately notified that they are being redirected to make their payment. If at this point of redirection, they cancel, they will be able to remain on the Index page without payment.
I think the only way to prevent the Esc key from stopping navigation is to not navigate away from the original page at all. Instead of doing
location.href = 'payments/basic.php';
make an XHR or fetch request to basic.php, and populate the current document with the results, instead of loading an entirely new document - just like how a SPA works.
(You will almost certainly want to make some changes to basic.php - eg, have it return easily-parseable JSON containing the data to populate the page with instead of an HTML document)
Regarding the edit
upon login, they are automatically sent to the index page
If at this point of redirection, they cancel, they will be able to remain on the Index page without payment.
If you're trying to prevent access the the original page, then just don't serve the original page until you've checked the flag in the database. Don't serve the index page to begin with until you've validated the user's credentials. If they aren't authorized, redirect them in PHP (not in JS) to the payments page. No need to mess with the user's escape key.
Why not do it the other way around?
Default to the payment page, if payment is already made, then redirect to index. lol.

use javascript history to discard consecutive clicks on the same page

So, I'n NOT a frontend guy, please bear with me..
I have pages, where you submit forms (target and current urls are identical) a number of times, before you wan't to go back to the previous page.
The way the submits are processed, is that the form is posted, and then the user is redirected, so that a reload doesn't re-submit(POST) the form - I'm not sure if this is the optimal approach to achieve this..
The issue is that this will only take the user back to the same page, since if eg. a form on page A was submitted twice, the history will have:
page A (current)
page A (submit, yielding a redirect)
page A (previous load)
page A (submit, yielding a redirect)
page A (original load)
previous page
Now I'd like the back button to take the user back to the previous page (#6), and in order to do that I'm guessing I'd need to introduce code on each page (with forms at least) which:
checks if the referrer has identical url as the current one, and if so, does history.popState
on submitting any form, check if the target and current urls are identical does history.popState
Is this a sound strategy, or is there are better way to achieve this?
Html
<a href="index.html"
onclick="handleClick(this);">Click</a>
Javascript
const handleClick = (e) =>{
locaiton.replace(e.href);
return false;
}
This doesn't seem possible, so I took another route, where I'd avoid using the back button, but rather offer links to the previous page, based on the context.

How to remove a value from localStorage after reboot?

1) Enter text in the search
2) it is saved in localStorage
3) press "search", and the page is reloaded,
4) the text entered there in the search bar.
It is working correctly.
But if I start to click on other pages of the website, the search bar is still populated with a value from localStorage.
How can it be removed at the next reboot?
What should I use (not localStorage)?
In your comment you've clarified you want to do:
enter data
press "Enter"
reload page
data entered in the search bar
the next reloading of the data should be deleted
It sounds to me, then, like you don't want to use localStorage or sessionStorage at all. Instead, when sending the data to the server at #2 above (I'm assuming that's what pressing Enter does), return the search bar data when the page reloads at #3 above; use that to populate the search bar. Subsequent refreshes of the page won't have that data (because you won't have sent it, so you won't have echoed it back).
A less reliable solution would be to save the data in web storage (either localStorage or sessionStorage) at #2 above, then on page load see if the data is there, use it if so, and delete it. Then it won't be there on subsequent page loads. I say that's less reliable because if for some reason your page doesn't reload at #3, or while the data is being sent the user opens another page on your site with this search bar thing, they could see search data. That's why including it in the response to the search makes sense.

Browser Back button changes dynamic url Parameters

I am working on a website, where url parameter gets updated based on user action, according to which I update the webpage without refreshing.
Consider the scenario of E-commerce where url changes when user clicks on filters and then updated products gets displayed.
Now the problem is, when user clicks on Browsers's back button the browser goes back to previous url-parameter, but page did not gets changed. I want to change the page also based on url parameter that gets changed after back button clicked.
I have tried this solution:
$($window).on('popstate', function (e) {
// Update the page also
});
The problem with this code is, this gets fired as url changes, means it does not care about if browser back button is clicked, or url is changing using the jQuery. So if I am changing url based on user interaction, the popstate callback will be called and my custom function also. To update the page I am using https requests, so http api gets called two times.
Is there any way to check if only "Back button" is clicked?
I would recommend you to change your design a litle bit and trigger all content updates (the product list in your case) by listening to url changes, not only url changes caused by the back button. So instead of triggering any re-rendering on click events, let these buttons be regular link to the url that represent your content and trigger the functionality from the popstate event.
This is how all MVVM-frameworks like Angular.js, Backbone etc are designed and meant to be used.
By doing this it will also be so much easier for you to maintain the application in the long run.
Good luck!
You can do this with sessionStorage! Below is the relevant part of an answer I always refer to for stuff like this https://stackoverflow.com/a/45408832
sessionStorage is a storage type like localStorage but it only saves your data for the current tab.
Session storage can be used like this.
sessionStorage.setItem('key', 'value'); //saves the value
sessionStorage.getItem('key'); //gets the saved value
performance.navigation.type is the browser is the variable that hold users navigation info.
if(performance.navigation.type == 2){
//User is coming with back button
}
So to put it all together, you can set/update a sessionStorage item as part of the callback of the click event for your filter, then performance.navigation.type to check if they used the back button to load the page and apply the data!

Javascript: Making divs hold state of display='block' when user clicks BACK button in browser

I have a few divs on a form that are hidden by default (style="display:none;"). When the user clicks a certain radio button, an onclick event executes and exposes the divs. The user is then taken to a review page upon form submit that shows him any errors. If there are any, he clicks the BACK button on his browser to go back to the form and correct them. Caching is enabled so that all of his form contents are there. The problem is, since the form is looking for an onclick event, all of the previously exposed divs are hidden again. Is there any way to make sure they stay exposed when the user clicks back to the form from the review page? I thought a document.ready function would do it, but no joy.
As Yair mentioned, you can use cookies. It cannot be done with pure JS. However, you can also use PHP.
Before the user is transferred to the second page, have JS scan the divs in question, and find which ones are visible. (I'm assuming they all have individual IDs). Store these IDs in a comma-delimited string, or array, and send it as a _POST or _GET to the new page.
Have PHP store it as a hidden value somewhere. You could use a hidden input, or a data-x on something ... as long as it's there.
Have JS on that page that watches for the back click, stops it, and then redirects the user to the previous page, and sends the string or array back to it. Have PHP on that page print it as a JS value, and have JS on pageload show all divs with matching IDs.
Cookies or localStorage if you aim for only modern browsers:
localStorage
Is there any way to make sure they stay exposed when the user clicks
back to the form from the review page? I thought a document.ready
function would do it, but no joy.
You can use cookies in order to manage state in a web-browser. Cookies will help you save the desired user's state.
All javascript code is reinitialized on browser reload. You cannot identify whether the user comes back through the browser.
You can use cookies or local storage to save a value when initial display happens and show/hide the div later on document.ready.

Categories

Resources