I am trying to develop a javascript code that when a user clicks on the back button of a webpage, it can be redirected to another URL.
I have found these lines of co
Well if you want to use the browser back button I would push each page change into the History Api
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history http://www.sitepoint.com/javascript-history-pushstate/
what you would need to do is while the user navigates your page, whenever they do something that you feel should be put into their history you use
history.pushState({}, 'Title: Google', 'http://www.google.com/');
Now when the user clicks the back button the previous page will be google.com, though I'm sure you want it be a certain end point on your webpage.
I have found the answer in case someone else is looking for it.
Create a separate file called history-stealer.js with the following code:
(function(window, location) {
history.replaceState(null, document.title, location.pathname+"#!/history");
history.pushState(null, document.title, location.pathname);
window.addEventListener("popstate", function() {
if(location.hash === "#!/history") {
history.replaceState(null, document.title, location.pathname);
setTimeout(function(){
location.replace("http://www.url.com");
},10);
}
}, false);
}(window, location));
and then include this code in your HTML file:
<script src="history-stealer.js"></script>
so that it calls the history-stealer.js file