In actual applications, we often need to implement the need to click the return, back, previous page and other buttons in mobile apps and browsers to close the page, adjust to the specified page or perform some other operations. So how to monitor events when clicking the return button of apps such as WeChat, Alipay, Baidu Nuomi, Baidu Wallet, etc. or the browser's previous page or back button.
I believe that many friends are like me, who have searched in Baidu and Sogou for a long time but have not found a method.
Here is how to monitor:
First of all, we need to understand the history of the browser.
As you know, we can use javascript window history on the page and back to the previous page. However, due to security reasons, javascript does not allow modifying the existing url link in history, but you can use the pushState method to add url links to the history, and provide popstate event monitoring to pop up the url from the history stack. Since popstate event monitoring is provided, we can monitor it.
Click the button to listen to the implementation code for the return, back, and previous page button:
window.addEventListener("popstate", function(e) { alert("I heard the browser's return button event");//Implement your own function according to your own needs}, false);Although we listened to the back event, the page will still return to the previous page, so we need to use pushState to add a url of this page to represent this page. Everyone knows very well that it is #
function pushHistory() { var state = { title: "title", url: "#" }; window.history.pushState(state, "title", "#"); }When entering this page, we press a local connection to this history. When clicking on the operations of return, back and previous page, listen and implement your own operations in the listening code.
Here is the complete code:
$(function(){ pushHistory(); window.addEventListener("popstate", function(e) { alert("I heard the browser's return button event");//Implement your own functions according to your needs}, false); function pushHistory() { var state = { title: "title", url: "#" }; window.history.pushState(state, "title", "#"); } });The above content is just the core code listed by the editor for everyone. You can add, modify and delete the code according to your needs. If you find any questions during the process of referring to this code, please leave me a message and the editor will reply to everyone in time!