I'm creating a simple html page with one audio player inside an iframe. I need to enamble kind of autoplay for desktop and mobile.
The player is this one:
<div style="width: 100%"><iframe src="https://players.rcast.net/fixedbar1/66549" frameborder="0" scrolling="no" autoplay style="width: 100%"></iframe></div>
I put this block on the bottom of the html page:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready
setTimeout(function(){
document.querySelector('.play-btn').click();
},3000); //delay is in milliseconds
});
</script>
Using firefox console document.querySelector('.play-btn').click(); works fine, but on runtime i get:
Uncaught TypeError: document.querySelector(...) is null
Any ideas or best ways?
Thanks, Red
You can do whatever you want in the console but you would only be able to access iframe content programmatically if your iframe domain matches your current domain.
That being said, you can:
Select the iframe, then run query selector on the iframe (you don't even need jQuery for it):
const iframeElement = document.querySelector('iframe');
iframeElement.querySelector('.play-btn').click();
Tips:
You can also play the video/music directly by calling play() on
the media elements. So you can cut out stimulating click on
the button.
querySelector is slower than getElementById, you can assign an id attribute to your iframe/button/media element and find it directly.
It will also help you avoid bugs because querySelector returns the first match. So in case you have multiple iframe or multiple elements with the class .play-btn, it can lead to unexpected behaviour.
you should select iframe at first and get its content window to access all elements on it.
const myIframe = document.querySelector('#iframe_id')
const myIframeDocument =myIframe.contentWindow.document
const myElement = myIframeDocument.body.querySelector('#target_element')
it is noticeable that the iframe should be loaded completely before your process and also domain conflict
Hope this helps:
<iframe id="video1" width="450" height="280" src="http://www.youtube.com/embed/TJ2X4dFhAC0?enablejsapi" frameborder="0" allowtransparency="true" allowfullscreen></iframe>
<a href="#" id="playvideo">Play button</a>
<script>
$("#playvideo").click(function(){
$("#video1")[0].src += "?autoplay=1";
});
</script>
I found this on Grepper, but it was from another Stack Overflow post. If that doesn't help I found a different post that seems to be more related to the error.