Search code examples
javascriptreactjscordovahybrid-mobile-app

Cordova do something when the app has been open in the background for more than 30 minutes


I am building a Hybrid app using react and Cordova. I need to render a specific component after 30 minutes of the app being closed in the background.

I have two event listeners

  1. "pause" which detects if the app is open in the background. Here I set localStorage with the current date/time.

  2. "resume" when the app has been opened after being open in the background. Here I get the current time, the time from localstorage and check if the time between the both is 30mins. Here's where my problem is, it always returns false. My problem is more javascript related as apposed to react/cordova. Can someone explain what i'm doing wrong?

// when the app is open in the backgroud 
document.addEventListener("pause", () => {
    localStorage.setItem("appTimeout", Date.now());
},false);

// when you reopen the app
document.addEventListener("resume", () => {
    setTimeout(() => {
        const minutes = 1000 * 30 * 60;
        const closeTime = localStorage.getItem("appTimeout");
        if(Date.now() - Number(closeTime) >= minutes){
            //render component
        }
    }, 0);
},false);

Solution

  • After alot of headaches with this I ended up using react-idle-timer for this. https://www.npmjs.com/package/react-idle-timer