The pagehide event fails to trigger when imminent tab switching occurs on an iPad running Mobile Safari

Everyone knows that Mobile Safari pauses Javascript execution on a webpage when

  1. you move to a different browser tab
  2. switch to another iOS app (for example, when you receive an incoming call in the phone app)

To detect impending suspension and restoration of Javascript, you can listen for the window's "pagehide" and "pageshow" events.

The issue is that these events do not trigger when tab-switching (1.) in iPad's Mobile Safari. On iPhone's Mobile Safari, everything works as expected.

This problem can be easily demonstrated:

<!DOCTYPE html>
<html>
<head>
    <script>
        window.addEventListener("pagehide", function(evt){
            var log = document.getElementById('log_id');
            log.innerText = log.innerText + " pagehide fired!";
        }, false);
    </script>
</head>
<body>
<div id="log_id"></div>
</body>
</html>

On iPads (iOS5 and iOS6 Preview3), this event only triggers with app-switching (2.) and not with tab-switching (1.). All iPhones work correctly.

Has anyone found a way to detect an impending tab switch in the iPad browser?

The re-activation of Javascript when the tab becomes active again can be detected using a heartbeat loop as discussed in this related thread.

Answer №1

Experiment with checking focus and blur events on the document.

What is the significance of utilizing the Page Visibility API?

  1. Utilize the storage event to communicate with other active pages.
  2. Employ timers (such as setInterval) to monitor the time since the last timer fire. If it exceeds the expected duration, it indicates that the page was hidden, as most browsers pause timers when a page is not visible.

Answer №2

Agreeing with Pinal's suggestion, I recommend using focus/blur events! Instead of attaching them to the document, consider registering them on the window object. This way, you can handle your functionality in a cleaner manner.

According to http://caniuse.com/#feat=pagevisibility, the feature you are looking to utilize may not be fully supported across all browsers. (Update: After testing in a small demo, it seems to work on iOS 5/6 despite what caniuse.com claims)

If you're considering using timers, give requestAnimationFrame a try as an alternative to setInterval function.

Answer №3

Resolved by Apple with the release of iOS7. (Just tested on the iPad Simulator)

Answer №4

Building on Sebastian's response, current page visibility functionality has significantly improved from 2013 to 2021. For more information on how to subscribe to 'visibilitychange' for hidden/visible states, refer to https://www.w3.org/TR/page-visibility/#example-1-visibility-aware-video-playback.

In today's context, page visibility offers more advantages compared to focus/blur techniques, especially when dealing with visible-but-not-selected windows in multi-window operating systems.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying the appearance of one specific element within a loop

This may seem confusing, but it's a serious question. I am using PHP to loop through table rows and display them inside a table tag using AJAX. Each row has an ID called productTableRow. What I want to achieve is when a specific row in this table i ...

Is it possible to implement a context menu that appears when the user right clicks within the threejs

In my angular project, I am using threeJs for a 3D representation. I am trying to implement a context menu that appears on right-click within the scene. Currently, I have the following code but I keep getting an error stating 'menu does not exist&apos ...

What are the advantages of using the fat arrow instead of straight assignment?

Here we have a code snippet sourced from the 30 seconds of code website. This example, intended for beginners, has left me feeling stumped. The question arises: const currentURL = () => window.location.href; Why complicate things when you could just ...

Error in React Native JS: Cannot call the `map` function on variable `l`

Recently diving into the world of Js and React, I am tasked with creating an application for Macronutrients in my second semester project. The challenge I'm facing is incorporating a Pie Chart that displays the values from my state. To implement the ...

I am encountering an issue where the data retrieved from a Django POST request using Javascript fetch is successfully displayed, but I am receiving an error message stating "Expecting value: line 1 column 1 (char

I've been encountering an issue while attempting to transmit data using Javascript fetch. The error message I keep getting is: "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" Within index.js: fetch('save_user_post/&apos ...

Display TMX Map on Three.js Plane

Updated question with new code I'm currently working on a WebGL shader that is designed to render a TMX Layer exported from the Tiled editor. My approach involves using THREE.js to create a Plane mesh and setting the material as ShaderMaterial to dra ...

What could be the cause of a JSON string only returning the final object when evaluated?

Does anyone have insight into why only the last object in my json string is returned when I use the eval function? ...

Obtaining hyperlinks to encircle the sound button

Code 1: If you notice, after clicking on the image, the audio button appears and plays without any surrounding links. How can I enable the links around the audio button in Code 1? https://jsfiddle.net/7ux1s23j/29/ https://i.sstatic.net/75wlN.png < ...

Tips on hiding specific table rows in two separate tables based on the chosen option from a dropdown menu

How do I hide table rows based on dropdown selection? The first table has a dropdown with two options: Current State and Future State. If I select Current State, I want to show or hide specific rows in the 2nd and 3rd tables. I am using IDs for these row ...

React hook issue: useEffect not updating socket.io-client

Although I am attempting to receive updated values of react hooks inside the socket on function, unfortunately, it seems that the values are not being updated. Even if I edit the react hook values, the changes are not being reflected inside the socket. Her ...

useEffect is triggered despite there being no change in the state

const [urlList, setUrlList] = useState(0); const callDayList = () => { console.log(urlList); Axios.post('http://localhost:3001/api/get', { passNum: urlList, }); }; useEffect(callDayList, [urlList]); <td> <Link ...

What is the most efficient way to transmit an HTML document element from a client to a server in Node JS

I am attempting to capture a snapshot of my client-side document object and send it to the Node.js server. However, when I try to convert it into a string using: JSON.stringify(document.documentElement) I encounter an issue where it becomes an empty obje ...

"Concealing tooltip boxes in Vue: A step-by-step guide

I am trying to achieve a functionality where a tooltip box appears on each incorrect or empty input field when the 'Save' button is pressed. I have been able to display the tooltip boxes upon clicking the 'Save' button, but the issue ar ...

Navigating through directory paths in JavaScript can be a daunting task for many

In my app.js file, I've included the following code: app.use(multer({dest:'./uploads'})) What does './uploads' refer to here? It is located in the same directory as app.js. In what way does it differ from simply using uploads? I ...

Failed to load NIB in CocoaPods bundle

I recently added PSCarouselView from cocoapods to my project. However, upon trying to use this library, I encountered a runtime error stating that the nib file could not be loaded. Upon investigating, I confirmed that the nib file was registered correctly ...

Display icons within each table cell row

Objective: I want to implement a feature where icons appear when the cursor is inside a td row, allowing users to click on them. These icons will contain links. When the cursor moves to a new td row, the previous row should return to its default state a ...

Axios Instance class request cancellation

In my Redux-saga project, I am working on implementing a polling function where I need to make a request every second. If there is no response from the endpoint, I want to cancel the previous request and initiate a new one using Axios client. I have organi ...

Needing to utilize the provide() function individually for every service in RC4

In Beta, my bootstrapping code was running smoothly as shown below: bootstrap(App, [ provide(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, helperService: HelperService, authProvider: AuthProvider) => new CustomHt ...

Having trouble setting up react-i18n with hooks and encountering a TypeError: Cannot read property '0' of undefined?

Encountering an error while setting up the react-i18n with hooks: TypeError: Cannot read property '0' of undefined Here's the content of i18n.js: import i18n from 'i18next'; import { initReactI18next } from 'react-i18next/h ...

Issue with MongoDB find() function not retrieving any results (Assignment)

I am currently working on an assignment that requires the use of noSQL databases. Although I understand most of the queries we have to perform in mongoDb, every query I execute seems to return a blank result. Initially, we are required to create a collect ...