user1449565
user1449565

Reputation: 41

Why does visibilitychange event not fire for Android webview?

My app has multiple android web views, in site-wide JS, I have:

window.addEventListener('beforeunload', function() {console.log("beforeunload");});

// subscribe to visibility change events
document.addEventListener('visibilitychange', function() {
    console.log('visibility changed!!!');
}

Neither beforeunload nor visibilitychange fires when I (1) hit the "home" button to go to home screen or (2) invoke the task switcher to move on to different app.

To clarify, visibilitychange gets fired in Android Chrome correctly. What's different about webviews?

Upvotes: 3

Views: 4759

Answers (2)

taoliujun
taoliujun

Reputation: 131

Yes! It's not fired in Android5.1, i instead it with event focus and blur.

Upvotes: 0

Ian Wong
Ian Wong

Reputation: 1687

Visibility of webview is calculated as:

visible = !paused && (!attached to window || window visible)

In other words, the window visible state is ignored if webview is detached. This is because webview does not know the window visibility state when it is detached, and there are many apps that uses a detached webview when detached, so expects a detached webview to function normally as if it's visible.

Another "oddity" you didn't notice is page visibilityState has nothing to do with WebView.setVisibility

If you want to control page visibility from your app, use WebView.onPause/onResume.

Credit to Bo Liu. link

Upvotes: 1

Related Questions