"Triggering a Javascript event upon re-launch of a mobile browser or waking up the

Hello everyone, I am in search of a Javascript event that can detect when a mobile browser window regains focus. This could happen when a user closes or minimizes their browser to switch back to the home screen or another app, or when the device resumes from sleep mode due to user powering it off or screen timeout.

I would prefer to find a single event that works universally, but I understand that might be difficult! The 'pageshow' event seems to work for iOS devices, but is not very reliable for everything else. I have tried using 'focus' and 'DOMActivate', but they do not produce the desired outcome.

It's important to note that the page may not always contain form elements, and I want the event to trigger without requiring the user to interact with the page again.

This need for such an event arises from our code regularly checking for new content through XHR requests. These requests are not made while the browser is asleep, leading to issues with receiving updated content and restarting timeouts.

Thank you in advance for any assistance you can offer!

Answer №1

We encountered a similar issue and addressed it with the following approach:

let lastSyncTime = 0;
const syncInterval = 60000; //sync every minute

function synchronizePage() {
  lastSyncTime = new Date().getTime(); //set last synchronization time to now
  updatePage(); //perform necessary actions
}

setInterval(function() {
  const currentTime = new Date().getTime();
  if ((currentTime - lastSyncTime) > syncInterval ) {
    synchronizePage();
  }
}, 5000); //check every 5 seconds for elapsed time since last sync reaching one minute

This method ensures synchronization occurs every minute when the page is active. If the browser is idle for over a minute, synchronization will occur within 5 seconds of reopening the browser. It's important to consider battery usage when adjusting the timings to suit your specific requirements.

Answer №2

Instead of using an interval, consider implementing a window blur listener and a window focus listener. When the window loses focus, record the current time. When it regains focus, check if the user is still logged in or synced.

This method achieves the same result but only runs when necessary, preventing your page from slowing down unnecessarily with an interval.

Enhancement

var $window = $(window),
  $window.__INACTIVITY_THRESHOLD = 60000;

$window.add(document.body);  //needed for mobile browsers

$window.declareActivity = function () { $window.__lastEvent = new Date(); };

$window.blur($window.declareActivity);
$window.focus(function(){
  var diff = (new Date()) - $window.__lastEvent;
  if (diff > $window.__INACTIVITY_THRESHOLD) { 
     $window.trigger("inactivity"); 
  }
});

$window.on("inactivity", "", null, function () {
  //your inactivity code
});

The use of the blur event may not be reliable on all devices, so including events like click, scroll, and keyup can improve accuracy in detecting user activity. Adjust the event list based on your site's needs, or include $window.declareActivity(); in existing scripts that respond to user inputs.

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

Is there a different method to retrieve language bundles with next-i18next instead of using a customized Node server?

Currently, I am developing a Next.js application that will utilize i18next translations organized in the recommended file structure for bundles. For example: static/locales/en/common.js static/locales/de/common.js You can refer to this article: https://m ...

RxJS equivalent of a 'finally' callback for Promises

In my component, I have a process that retrieves data from an API. To indicate whether the data is being loaded or not, I use a member variable called loading. Once the data retrieval process is complete, I set loading to false to hide the loading icon. Th ...

Having difficulty requesting an API in Next.js that relies on a backend cookie

1: When a user logs in, I generate a refresh token and create a cookie using 'cookie-parser'. This cookie is then sent to the path '/user/refresh-token' res.cookie('refreshtoken', refreshtoken, { httpOnly: true, ...

My Discord.JS bot seems to be moving at a snail's pace, and I can

Apologies for the lackluster title, I'm struggling to come up with something better. I'm currently running a self-bot (I understand it goes against the terms of service but I'm experimenting) that needs to download new files (specifically i ...

Implementing a rate limit on the login API that is specific to individual IP addresses rather than being

I have successfully implemented the [email protected] module, but I am facing an issue where it is blocking the API globally instead of for a specific API that is receiving hits. This is my current code: const limiter = new RateLimit({ windo ...

Delete the initial frame image from the UIImageView prior to starting the video on the MPMoviePlayerController

Currently, I am facing an issue with a video that is played in a MPMoviePlayerController. The background color of the MPMoviePlayerController has been set to clearColor. To display the first frame of the video, I am using an UIImageView below the MPMovieP ...

What are the essential Angular 2 observables for me to utilize?

I have created a form input for conducting searches. Upon user input into the search bar, I want to trigger calls to two separate APIs simultaneously. Here is my current attempt: myInput: new FormControl(); listOne: Observable<string[]>; listTwo: Ob ...

Troubleshooting Puppeteer compatibility issues when using TypeScript and esModuleInterop

When attempting to use puppeteer with TypeScript and setting esModuleInterop=true in tsconfig.json, an error occurs stating puppeteer.launch is not a function If I try to import puppeteer using import * as puppeteer from "puppeteer" My questi ...

Is a streamlined jQuery version of the Slider control designed specifically for mobile devices on the horizon?

Currently, I am developing a mobile web app and would like to incorporate the JQuery Slider control. http://docs.jquery.com/UI/Slider However, in order to do so, it seems that the entire JQuery core (29kb compressed & gzipped) is needed. My question ...

Will cancelling a fetch request on the frontend also cancel the corresponding function on the backend?

In my application, I have integrated Google Maps which triggers a call to the backend every time there is a zoom change or a change in map boundaries. With a database of 3 million records, querying them with filters and clustering on the NodeJS backend con ...

Issue with Xcode6 Compiler

After launching my project, I encounter an error in Xcode 6.4 that reads: Interface Builder Storyboard Compiler Error Line 4140:StartTag:invalid element name When I attempt to open the xib or storyboard file, Xcode immediately crashes. ...

Tips for passing JSON data using Intent's putExtra method on an Android device

Recently, in my website server, I have been utilizing the AsyncTask function to access JSON data. String strData = ""; @Override protected void onPostExecute(String result) { super.onPostExecute(result); final ArrayAdapter<String> adapter = ne ...

What methods are available to apply a class to an element in an array when hovering over it?

Is there a way to add a class to an element when hovering over it in an array of elements? ...

I'm looking to use gulp-inject to dynamically add the contents of a file into my index.html - how can I achieve

Here are the steps I followed: gulp.task('watch-index-html', function () { gulp.watch(files, function (file) { return gulp.src('index/index.html') .pipe(inject(gulp.src(['index/base3.html']), { ...

Using JavaScript to implement Gzip compression

As I develop a Web application that must save JSON data in a limited server-side cache using AJAX, I am facing the challenge of reducing the stored data size to comply with server quotas. Since I lack control over the server environment, my goal is to gzip ...

Steps to replicate the contact list UITableView design on an iPhone

After being inspired by the sleek design of iPhone's default contacts list input tables, I am eager to recreate a similar input page for my v2 app. My v1 app used a mix of text fields on the screen, but this new implementation appears to be more user- ...

Upon submission, the select input in Vue.js and PHP fails to persist

My situation revolves around a lack of knowledge. I have an HTML form where I am using Vue.js to populate a v-select input with PHP data: <div id="app"> <form> <v-select name="user2_id" placeholder="Select User" :options="[{!! $ ...

Certifications and product profile management for a variety of goods

I have recently finished development on an iOS app at my workplace and now we are gearing up for a new project. Before diving in, I would like some clarification on certificates, profiles, and build environments: Q1: Is it true that an Apple account can ...

Sending an array of strings from an ajax call to an MVC controller

I'm encountering an issue where I have an array that I build up when a row is selected in my bootstrap data table. The problem arises when I try to pass this array from my view to the controller, which is supposed to fire up a partial view. Strangely, ...

Apple device users may encounter a problem where multiple push notifications do not appear in the

I am looking to have the ability to display multiple push notifications in the notification tray within an iOS application. Under normal circumstances, when my data is on and a push notification is sent through APNS, only the latest one is received if I a ...