Detect hide/leave event of mobile phone browser

2.2k Views Asked by At

I've surveyed most of the questions on the web but this still gets me confused....

My question is, how to detect hide/leave event of a website tab in mobile phone browser, my situation is NOT about closing the tab(like pressing the X button at the up-right or up-left corner), and also NOT about closing the whole mobile browser app directly.

(Previously, I have a webpage with a websocket connected to receive the encoded audio content, and then use AudioContext to play the sound)

Below are the two situations I've encountered.

  1. When I press the HOME button and the mobile browser app hides.

  2. When I click a url in the Messenger app or Facebook app of my iPhone, and press the Back button to go back.

the url link is opened in the in-app browser which made by Facebook directly, and when I press the back button on the left-up corner, the view jumps back to the Messenger window or the Facebook timeline.

In these two cases, I have listened beforeunload (and also pagehide event for iOS), but neither one is catched. And I have found that the websocket connection is still connecting and the audio is still playing. It seems like the whole page is still running somewhere(but you cannot see). I also tried listening to a div :visible, but it is still giving me true when I pressed the home button or leave the facebook in-app browser.

Is there still any way to detect these two kinds of situation? I want to turn off the streaming sound and also close the websocket connection.

1

There are 1 best solutions below

0
Hui-Yu Lee On BEST ANSWER

Just found the answer....

Page Visibility API https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API