JavaScript page visibility event isn’t being triggered in Python Selenium tests

My website has a feature that sends data when the page visibility changes to “hidden.” It works fine during manual testing but doesn’t trigger in automated testing with Python Selenium. I’ve also tried using the Page Lifecycle API with the same outcome.

Here’s the code snippet:

document.onvisibilitychange = () => {
    if (document.visibilityState === "hidden") {
        sendBeaconData();
    }
};

Is there a possibility to adjust the JavaScript code so it’s detected during automated testing, without making changes to the Selenium setup?

Note: pageunload and similar functions aren’t viable solutions, as they don’t work consistently on mobile devices.

I have tried Page Lifecycle API and pagehide event but it provides same result.

https://developer.chrome.com/docs/web-platform/page-lifecycle-api#advice-hidden