preface

A recent demand, app embedded h5 need to do the task, but the task is in a native page, the requirements of the product if the user do the task, back into the h5, automatic identification to complete the mission, we this android will generally have some operation after the return of listening, but this time is special, need the front to do processing.

A new feature in H5 is the ability to listen for pages to be displayed and hidden

Document.hidden (read-only property) returns a Boolean value indicating whether the page is (true) or (false) hidden. (True indicates that the page is hidden, false indicates that it is displayed)

var hiddenProperty = 'hidden' in document ? 'hidden' : 'webkitHidden' in document ? 'webkitHidden' : 'mozHidden' in document ? 'mozHidden' : null;
console.log(hiddenProperty);

document.addEventListener('visibilitychange', () = > {if (document[hiddenProperty]) {
    // This will be triggered when you leave H5 and jump to the native page of the app
    console.log('Page hidden');
  } else {
    This is triggered when H5 is returned after a series of actions from the native page user
    console.log('Page shows'); }});Copy the code

This event can be triggered on the PC by toggling TAB

MDN correlation parsing

What can you do with this feature?

  • If the current H5 has a countdown, the user leaves the current App and comes back later, you will find that the countdown has been confused. You can use this property here, the page is hidden first turn off the timer, the page shows the start of the countdown

  • Or sometimes you need to control the pause and playback of video or audio in H5 (some videos and audio are still playing after leaving H5).