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>