.net-coreblazorprogressive-web-appsblazor-webassemblyblazor-pwa

Blazor wasm pwa - on opening after being inactive for some time


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.


Solution

  • 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>