Wednesday, February 7, 2018

Detecting Cordova Webview Visibility Changes (e.g. detecting when an AdMob ad is running on top of the webview)

I've not posted in awhile, but recently worked through a challenge that I think needs to be recorded for future reference.

Running a Cordova AdMob interstitial ad on top of a Cordova webview that already has an AdMob banner ad (bottom positioned) is breaking the viewport height calculation in iOS (except iPhone X) for me once the interstitial is closed. In order to address this, the banner ad needs to be removed when the interstitial is shown (easy with showInterstitial callback), but the banner ad needs to be added back once the interstitial is closed (hard without any callback).

Sorting through lots of ideas online, all of which were hacks or not quite what I need (pause and resume cordova events don't fire in this case), I was left trying to find anything about the DOM that changed when the interstitial was on top. Traditional element visibility checks yielded the same results regardless of whether the interstitial was open or closed. What to do?

HTML5 Page Visibility API to the rescue! Listening for 'visibilitychange' and then checking document.hidden is exactly what I was looking for.

            document.addEventListener('visibilitychange',function(){
                if (document.hidden) {
                    // remove the ad
                } else {
                    // show the ad
                }
            },false);


While this may seem simple, it is not insignificant. While Cordova handles pause and resume states, when the app has a plugin sitting on top of the webview (oAuth SDKs, ads, etc), we sometimes need the webview to be aware of that and the page visibility API gives us that ability.

No comments:

Post a Comment