Search code examples
javascriptiframeyoutubeonresize

Accessing iframe DOM


I want to stop YouTube playback onresize

i have an iframe

  <iframe id="tutube" class="youTubeVideo" frameborder="0" height="100%" width="100%" allowscriptaccess="always"
    src="https://youtube.com/embed/d3cRXJ6Ww44?showinfo=0&autohide=1&enablejsapi=1">
  </iframe>

and a function

function stopTheVideo(){
    var div = document.getElementById("tutube");
    var iframe = div.getElementsByTagName("iframe")[0].contentWindow;
    div.style.display = state == 'hide' ? 'none' : '';
    func = state == 'hide' ? 'pauseVideo' : 'playVideo';
    iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
            };

which I call

<body onresize="stopTheVideo();"

and I get

Uncaught TypeError: Cannot read property 'contentWindow' of undefinedindex10.html:198 toggleVideoindex10.html:206 resizeFunctionsindex10.html:31 onresize

Any ideas?


Solution

  • The issue is that your code expects that your <iframe> is wrapped inside another element with an id="tutube". getElementsByTagName() won't pick the element on which it has been called even if it matches.

    So you could either refactor your HTML so that it matches the expectations of your JS:

    <body onresize="stopTheVideo();">
      <div id="tutube">
        <iframe class="youTubeVideo" frameborder="0" height="100%" width="100%" allowscriptaccess="always"
          src="https://youtube.com/embed/d3cRXJ6Ww44?showinfo=0&autohide=1&enablejsapi=1">
        </iframe>
      </div>
      <script>
        var state= 'hide';
        function stopTheVideo(){
          var div = document.getElementById("tutube");
          var iframe = div.getElementsByTagName("iframe")[0].contentWindow;
          div.style.display = (state == 'hide') ? 'none' : '';
          func = (state == 'hide') ? 'pauseVideo' : 'playVideo';
          iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
        };
      </script>
    </body>
    

    Either rewrite your JS so that it works with your HTML:

    function stopTheVideo(){
      var iframe = document.getElementById("tutube").contentWindow;
      div.style.display = state == 'hide' ? 'none' : '';
      func = state == 'hide' ? 'pauseVideo' : 'playVideo';
      iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
    };