1, the preface


Now h5 new features, new tags, new specifications, and so on many, and is constantly improving, the major browser vendors support them, is quite powerful. As front-end programmers, I think we still need to be proactive and brave enough to practice. I’m going to share with you a very useful new h5 feature (not so new yet) that makes it easy to listen to the back button of any App, including the physical back button on Android, for further development needs.

2, the cause of


About half a year ago, I received the requirement of PM 1, and realized multi-audio playback, pause and continue with pure H5. The page was put into the App of Kaobadian, and there was no interaction with the client, so js related to the client did not need to be referenced. This seems like a pretty simple requirement, although I haven’t done this before. No matter what, roll up your sleeves is dry. I started my learning journey.

3. I’ll focus on how I listen for the back button in any App and the physical back button on android.


So why am I listening in? I need to stress and stress. On aN iPhone, whether it’s wechat, QQ, App, or browser, when audio or video is involved, the system will automatically pause the current playback if you go back to the previous page, but not on all Android phones. So we have to customize our own listening. Many friends may be the first idea is Baidu, and then the answer is nothing more than this

pushHistory(); Window. addEventListener(" popState ", function(e) {alert(" I am listening to the browser return button event "); }, false); function pushHistory() { var state = { title: "title", url: "#" }; window.history.pushState(state, "title", "#"); }Copy the code

Does that look familiar? However, the key requirements could not be perfectly implemented, and I was racking my brains at that time for the purpose of this code. Until, after the guidance of god friends, copied this code

var hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : 'mozHidden' in document ? 'mozHidden' : null; var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange'); var onVisibilityChange = function(){ if (! Document [hiddenProperty]) {console.log(' page not active '); } else {the console. The log (' page activation ')}} to the document. The addEventListener (visibilityChangeEvent onVisibilityChange);Copy the code

All problems solved. My personal understanding of the principle of this code is to judge whether the user is browsing the current page, so as to carry out relevant operations. This is the MDN relevant link: developer.mozilla.org… .

It is not really possible to monitor the built-in return key in App or even android’s physical return key through JS, but to quickly realize the requirements by changing ideas. Hopefully this feature will help you.