简体   繁体   中英

Control back button url in asp.net

I want to be able to control history for back button. If there are any postbacks on a page the back button counts these actions in history but what I want it to do is simply return to the previous page instead. Is there a method to be able to do this? I did look into history.replaceState(), would this work? I did try using the onhashchange event to capture the back button being clicked but seemed to ignore it completely in chrome??

Well first of all you need to know about whether you are coding on HTML5 standards, since history object can be manipulated only in HTML5. Since you are coding ASP.NET it is valulale to know are you going to support old versions of IE and by old I mean previous to version 9.

Depending again by control , since you cannot control a web browser. Remember that Web is an open platform and user can navigate to wherever she desires to. Capturing the browser back button is not a trivial solution, it is hacky. There are too many browsers each with their click event, my suggestion is that start thinking in web scenario not a .NET application (I am coming from a .NET background myself).

I personally would either go for pushState or replaceState depending on the case. They are methods implemented across all browsers and will not be tricky to implement them. See this amazing MDN post Manipulating the Browser History . You can push a new state, create a new state and navigate to a certain point in user's browser experience, really easily and it is part of the HTML standard, so you are not hacking anything as simple as the following code:

window.history.back(); // Go back in history
window.history.forward(); //Go forward in history

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");  //Push your new desired state in URL

var stateObj = { foo: "bar" };
history.replaceState(stateObj, "page 2", "bar.html"); // Will use the current object
//insteadof creating another one 

UPDATE : In case you want to force navigation to a HTML, just use the pushState or replaceState like the followings:

var enforcedPageToVisit = "
var stateObj = { pageName: "test" };
history.pushState(stateObj, "Page to visit evertime when you click back", enforcedPageToVisit);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM