1

I have build a blazor wasm app with pwa support. Is it possible to trigger some code when it is reopened after being inactive? I would like to fetch the most recent information from the server without having the user manual refresh the page.

My issue is on ios when closed but still in the list of inactive apps, but it is most likely also an issue for android.

9
  • That's not a mobile app, it's a browser app and behaves the same (more or less) in all browsers. It gets updated by the PWA's service worker script the second time the site is loaded. The first time the browser detect the new version and downloads it but doesn't interrupt the user. To change that you'll have to change the service worker script but even then, the user will have to start the app or go to the site. Commented Apr 9, 2024 at 11:19
  • That is not an answer to my question. I want to fetch data from the server on opening the app, not loading a new version of the PWA. Commented Apr 9, 2024 at 12:42
  • It's a comment, not an answer. In fact, what's the question? You can do whatever you want when the browser app starts, nothing outside the browser. You haven't created a native/store app, you created something hosted and managed by the browser. This isn't about Blazor or WASM, all PWAs have the same restrictions Commented Apr 9, 2024 at 12:44
  • I know what a PWA is. I would like to run code to fetch data from the server when the app comes out of hibernation. Commented Apr 9, 2024 at 12:46
  • User opens the app - swipes it away an does other stuff on his phone - reopens the app (the next day), the app is still on the same page, no initialization is running. Commented Apr 9, 2024 at 12:47

1 Answer 1

1

I solved this with js.

In Mainlayout:

var dotNetHelper = DotNetObjectReference.Create(this); await JsRuntime.InvokeVoidAsync("AddVisibilityWatcher", dotNetHelper); 
 [JSInvokable] public async Task VisibilityChange(string newState) { // Code to handle visibility change } 

In wwwroot add a js file:

let dotNetHelper; let queuedUpCalls = []; let timerId; function AddVisibilityWatcher(dotNet) { dotNetHelper = dotNet; document.addEventListener('visibilitychange', (event) => { if (document.visibilityState === "visible") { this.EventQueue(document.visibilityState); } }); } function EventQueue(eventName) { if (queuedUpCalls.indexOf(eventName) != -1) { return; } queuedUpCalls.push(eventName); if (timerId) { return; } timerId = setInterval(function () { if (!queuedUpCalls.length) { clearInterval(timerId); timerId = null; return; } let nextCallArg = queuedUpCalls.shift(); dotNetHelper.invokeMethodAsync('VisibilityChange', nextCallArg); }, 1000); } 

In index.html add the script

<script src="js/VisibilityWatcher.js"></script> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.