1

I'm trying to add a div to a YouTube iframe element so that I can display things over the video. But this code:

<!DOCTYPE html>
<html>
  <body>
   <iframe id="player" width="854" height="480" src="https://www.youtube.com/embed/Jn9r0avp0fY" frameborder="0" allowfullscreen></iframe>

    <script>
var player = document.getElementById('player');

var div = document.createElement('div');
div.id = 'newDiv';
div.innerHTML = 'Hello, world!';

player.appendChild(div);
    </script>
  </body>
</html>

has completely no effect. I can use JavaScript to confirm that the div is indeed in document.getElementById('player').children, but when inspecting elements on the page it is nowhere to be found. Why is this happening?

UPDATE: So I found this website https://www.reembed.com/ which succesfully overlays their own elements above the YouTube embedded iframe player, but I don't know how they achieve it.

Zizheng Tai
  • 4,891
  • 12
  • 61

2 Answers2

1

This you can achieve using position absolute and top,left CSS properties for that div, no need to insert the div inside the Iframe.

  • Most things can be done this way but I can't get things over the video when the user enters fullscreen mode. In Chrome and Safari, assigning a maximum `z-index` to overlays works, but in Firefox the trick does not work. – Zizheng Tai Mar 18 '16 at 05:48
1

Here is the solution to append element in the iframe.

<!DOCTYPE html>
<html>

<body>
    <iframe id="player" width="854" height="480" src="https://www.youtube.com/embed/Jn9r0avp0fY" frameborder="0" allowfullscreen></iframe>


    <script>
        setTimeout(function() {
            var player = document.getElementById('player');
            var iframeDocument = player.contentDocument || player.contentWindow.document;

            var div = document.createElement('div');
            div.id = 'newDiv';
            div.style.fontSize = '50px';
            div.innerHTML = 'Hello, world!';

            if (iframeDocument) {
                var iframeContent = iframeDocument.getElementsByTagName('body');
                console.log(iframeContent);
                iframeContent[0].appendChild(div);
            }

        }, 100);
    </script>
</body>

</html>

But Make sure you are accessing iframe on the same origin otherwise you will get cross-origin security issue.

check cross origin security issue SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Community
  • 1
  • 1
Mahendra
  • 49
  • 7