In practical applications, we often need to implement in mobile app and browser Click Back, back, previous page and so on button to achieve their own close the page, adjust to the specified page or perform some other operation requirements, that in the code how to monitor when the click of Micro-letter, Alipay, Baidu glutinous rice, Baidu Wallet, etc. app's return button or browser's previous page or Back button event.
I believe many friends like me, in Baidu, Sogou search for a long time did not find a way.
Here's how to listen:
First we need to understand the history of the browser.
We know that in the page we can use JavaScript window historyto go back to the previous page, but for security reasons JavaScript does not allow you to modify the URL links that are already in the history. However, you can use the Pushstate method to add URL links to the history and provide popstate event monitoring to pop-up URLs from the history stack. Now that we have popstate event monitoring, we can monitor it.
Back, back, prev button click on the Monitor implementation code:
Window.addeventlistener ("Popstate", function (e) {
alert ("I'm listening to the browser's Return button event");
Although we have heard the back of the event, but the page will return to the previous page, so we need to use pushstate to add a URL to this page, on behalf of this page, everyone is very clear is
function Pushhistory () {
var state = {
title: "title",
URL: "#"
};
Window.history.pushState (state, "title", "#");
}
When we enter the page, we press the history into a local connection. When you click Back, back, and on the previous page of the operation, the listener, in the listening code to implement their own operations.
Here's the complete code:
$ (function () {
pushhistory ();
Window.addeventlistener ("Popstate", function (e) {
alert ("I have heard the browser's Return button event");//implement your own functions according to your requirements
}, false);
function Pushhistory () {
var state = {
title: "title",
URL: "#"
};
Window.history.pushState (state, "title", "#");
}
The above content is only small make up to everybody listed core code, everybody according to the demand appropriate add, modify, delete code. If you are in the process of referencing the code to find any questions welcome to my message, small series will promptly reply to everyone!