Skip to main content

Watch in WebView: Handling Click-to-Play Mode on iOS After Exiting Full Screen

Updated over 11 months ago

Due to the default WKWebView behavior, when the user exits Full Screen mode, they may see the player in Click-to-Play mode. There is a workaround to address this issue. This JavaScript snippet should be injected after loading the webpage:

// wkwebView setup
webView.navigationDelegate = self

// inside WKNavigationDelegate method
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let js =
"""
// for every player
anyclip.widgets.forEach(widget => {
// Add event listeners to observe changes in the video state
widget.player.on('play', () => checkVideoState(widget));
widget.player.on('pause', () => checkVideoState(widget));
widget.player.on('ended', () => checkVideoState(widget));
});

function checkVideoState(widget) {
if (widget.player.paused()) {
// Video is paused, Unsubscribe with delay
setTimeout(function() {
// While exiting fullscree WKWebView also pauses the player,
// but we need the onFullscreenStateChanged callback to play widget
// this is why we unsubscribe with delay
console.log('unsubscribe');
widget.unsubscribe(onFullscreenStateChanged, "playerFullscreen");
}, 500);
} else {
// Video is playing, Subscribe!
console.log('subscribe');
widget.subscribe(onFullscreenStateChanged, "playerFullscreen", widget);
}
}

function onFullscreenStateChanged(params) {
var player = this.player;

// if the player is exiting full screen, force the play state
if (!params.isFullScreen) {
var delayInMilliseconds = 450; // 0.45 second
setTimeout(function() {
console.log("Playing player after fullscreen exit");
player.play();
}, delayInMilliseconds);
}
}
"""
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
[weak self] in
self?.webView.evaluateJavaScript(js)
}
}

This code ensures that when a player exits Full Screen mode, it will automatically resume playing, addressing the Click-to-Play mode issue on iOS.

Did this answer your question?