无法在Windows.Forms.WebBrowser控件中播放YouTube视频

时间:2016-04-25 15:47:51

标签: winforms youtube-api webbrowser-control youtube-iframe-api

我尝试简化将以下getting started HTML code分配给DocumentText控件的WebBrowser属性。

<!DOCTYPE html>
<html>
  <body>
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <div id="player"></div>

    <script>
      // 2. This code loads the IFrame Player API code asynchronously.
      var tag = document.createElement('script');

      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

      // 3. This function creates an <iframe> (and YouTube player)
      //    after the API code downloads.
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
      }

      // 4. The API will call this function when the video player is ready.
      function onPlayerReady(event) {
        event.target.playVideo();
      }

      // 5. The API calls this function when the player's state changes.
      //    The function indicates that when playing a video (state=1),
      //    the player should play for six seconds and then stop.
      var done = false;
      function onPlayerStateChange(event) {
        if (event.data == YT.PlayerState.PLAYING && !done) {
          setTimeout(stopVideo, 6000);
          done = true;
        }
      }
      function stopVideo() {
        player.stopVideo();
      }
    </script>
  </body>
</html>

这在运行时给出了以下脚本错误:

JavaScript Error

事实证明,即使是以下简化代码也会产生相同的错误:

webBrowser1.DocumentText = "<!DOCTYPE html><html><body><script src='https://www.youtube.com/iframe_api'></script></body></html>";

因此看起来WebBrowser控件无法加载iframe-API。这可能是什么问题?或者我怎样才能进一步调查此错误?

1 个答案:

答案 0 :(得分:1)

我找到了WebBrowser的解决方案。首先,我们必须强制WebBrowser运行我们机器上的最新IE,如this。 其次,我必须通过ASP.NET Web API和Katana(如this)传输HTML,使用WebBrowser导航到http://localhost:xxxx/api/xxxx

设置DocumentText无法正常工作,因为在本地加载html时,WebBrowser有许多安全限制。

另一个简单的解决方案就是使用其他浏览器引擎,如Gecko或CefSharp。