I am trying to extract the YouTube video URL in an Android app when the user clicks on a suggested video inside a WebView. The WebView is displaying a YouTube video, and I want to capture the video URL when the video changes (such as when the user clicks on a suggested video).
Here's what I have so far: I am using a WebView in Android and loading a YouTube video. I have set up a JavaScript interface to communicate with Kotlin. Initially, when the page loads, I can capture the video URL using JavaScript. However, when a user clicks on a suggested video, the video changes, but I can't seem to extract the new video URL.
fun YouTubePlayer(url: String) {
val context = LocalContext.current
val isLoading = remember { mutableStateOf(true) }
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { context ->
WebView(context).apply {
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
addJavascriptInterface(object : Any() {
@JavascriptInterface
fun onVideoUrlFetched(videoId: String) {
Log.i("YtVideoInfo", "Video ID Fetched: $videoId")
Toast.makeText(context, "Video ID: $videoId", Toast.LENGTH_SHORT).show()
}
}, "Android")
webViewClient = object : WebViewClient() {
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
isLoading.value = true
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
isLoading.value = false
}
}
webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
isLoading.value = newProgress != 100
}
}
// Inject JavaScript to track YouTube Player state
evaluateJavascript(
"""
(function() {
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
var currentVideoUrl = player.getVideoUrl();
var videoId = currentVideoUrl.split('v=')[1];
window.Android.onVideoUrlFetched(videoId);
}
}
var script = document.createElement('script');
script.src = '';
document.head.appendChild(script);
script.onload = function() {
onYouTubeIframeAPIReady();
};
})();
""".trimIndent(), null
)
loadUrl(url)
}
}
)}