最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to Extract YouTube Video URL When Playing Suggested Video in WebView? - Stack Overflow

programmeradmin6浏览0评论

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)
            }
        }
    )}
发布评论

评论列表(0)

  1. 暂无评论