简体   繁体   中英

How to receive online/offline events in Javascript that's executed inside WKWebView on iOS?

I have an iOS app that uses WKWebView to load in local HTML/JS file that contains online / offline event listeners but they aren't fired when user loses/regains connection. Same HTML/JS works on Android.

offline event - https://developer.mozilla.org/en-US/docs/Web/API/Window/offline_event online event - https://developer.mozilla.org/en-US/docs/Web/API/Window/online_event

Is there something specific I need to configure for it to trigger those events?

window.addEventListener('online', () => {
    console.log('Regained internet connection');
});

window.addEventListener('offline', () => {
    console.log('Lost internet connection');
});

Found what solved it for me. I had to wait for the page to load in before attaching the event listeners like below instead of adding them as soon as script executes.

window.addEventListener('load', async () => {

    window.addEventListener('online', () => {
        console.log('Regained internet connection');
    });

    window.addEventListener('offline', () => {
        console.log('Lost internet connection');
    });

)};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM