Reputation: 6616
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.
Upvotes: 2
Views: 2801
Reputation: 59
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
Upvotes: 1
Reputation: 66
This you can achieve using position absolute and top,left CSS properties for that div, no need to insert the div inside the Iframe.
Upvotes: 1