Developers sometimes wish to detect if a video is about to be played in a webview and, if so, intercept the video URL so that the application can play the video using an external third party video player instead of the webview's built-in video support. 3D WebView doesn't have an API specifically for intercepting video playback, but an application can use IWebView.PageLoadScripts or ExecuteJavaScript() to add JavaScript to the page that detects if a video is played and, if so, sends a message to the application's C# to indicate the video URL. Here's an example:
using UnityEngine;
using Vuplex.WebView;
class InterceptVideo : MonoBehaviour {
// Set this field to your WebViewPrefab or CanvasWebViewPrefab via the Editor's inspector.
public BaseWebViewPrefab webViewPrefab;
async void Start() {
// Wait for the WebViewPrefab.WebView property to be ready.
// https://developer.vuplex.com/webview/WebViewPrefab#WaitUntilInitialized
await webViewPrefab.WaitUntilInitialized();
// Add JavaScript to PageLoadScripts.
// https://developer.vuplex.com/webview/IWebView#PageLoadScripts
webViewPrefab.WebView.PageLoadScripts.Add(@"
// Use setInterval() to run this code every 250 ms.
setInterval(() => {
// Detect <video> tags that don't have our custom 'overridden' attribute
// and update them to add the 'overridden' attribute and send the video
// URL to the app's C# via window.vuplex.postMessage() when the video is played.
const newVideos = document.querySelectorAll('video:not([overridden])');
for (const video of newVideos) {
video.setAttribute('overridden', true);
if (!video.paused) {
pauseVideoAndNotifyUrl(video);
} else {
video.addEventListener('play', () => pauseVideoAndNotifyUrl(video));
}
}
function pauseVideoAndNotifyUrl(video) {
video.pause();
window.vuplex.postMessage('video:' + video.currentSrc);
}
}, 250);
");
// Listen for messages from JavaScript.
// https://support.vuplex.com/articles/how-to-send-messages-from-javascript-to-c-sharp
webViewPrefab.WebView.MessageEmitted += (sender, eventArgs) => {
var message = eventArgs.Value;
var prefix = "video:";
if (message.StartsWith(prefix)) {
var videoUrl = message.Substring(prefix.Length);
// TODO: Use your third party player to play the video using the video URL.
Debug.Log("Video URL: " + videoUrl);
}
};
}
}
Please note that this approach only works for videos that are played via http, https, or file URLs. If the <video> element's source is set to a blob: URL or a MediaSource object, then a third party video player is unable to access the video content.