Generally, the default behavior of webView is **window.history.go(-1)**. However, in actual demand scenarios, simple page rollback cannot meet the requirements, so H5 page needs to listen to the Android physical back key to customize the processing method.
The implementation code
// androidback.js (function (PKG) {var _android_back_handles = []; Var handlePopstate = function () {var handle = _android_back_handles. Pop (); handle && handle(); }; Var listen = function (handle) {_android_back_handles. Push (handle); }; Var push = function (state, handle) {if (handle) {// Add a history, History. pushState(state, null, location.href); handle && _android_back_handles.push(handle); }}; // Remove a history by calling the remove method and hsitory. Back (). var remove = function () { _android_back_handles.pop(); window.history.back(); }; Const init = function () {// Listen for popState when the Android physical return key is clicked, The event window.addEventListener(' popState ', handlePopstate) is raised; this.listen = listen; this.push = push; this.remove = remove; }; init.call(window[pkg] = window[pkg] || {}); })('AndroidBack');Copy the code
use
/ / to monitor Android physical return key, custom processing method window. AndroidBack. Listen (() = > {the console. The log (" back "); }); // Add Android physical back key listening event, use scenario, such as: Push ('close_modal', () => {// close the popup window console.log('close_modal'); }); // Delete the added handler and call history.back() to delete the history. window.AndroidBack.remove()Copy the code
Realize the principle of
HTML 5 new API
history.pushState(state, title, url); Add a history without refreshing the page
The event
PopState event: Triggered when history changes. This event is not triggered by calls to history.pushState() or history.replacEstate ()
window.addEventListener('popstate', handlePopstate);
window.addEventListener('hashchange', handleHashChange);
Copy the code
scenario
On the H5 page of your Android phone, when you bring up the popup, execute the following code:
Window. androidback. push('close_modal', () => {// close popup console.log('close_modal'); });Copy the code
This code window.addEventListener(‘ popState ‘, handlePopstate) captures the android return key event when the user clicks on the android return key. The console.log(‘close_modal’) method body is executed and a previously added history (history.pushState(state, null, location.href) is skipped, but the interface is not refreshed.
The final effect is to close the popup box and forbid returning to the previous page…
When a user clicks a bounced off button, the need to use Windows. AndroidBack. Remove () to clean up before adding function and history…