Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can mute audio from iframe?

Tags:

html

iframe

I'm creating a tribute page (for freecodecamp.com) about Elon Musk and I wanted to include his game into my page via attribute. Is it possible to mute the autoplay audio? My page url: https://codepen.io/auginis/full/BdwBZW/ The game: https://blastar-1984.appspot.com/ Here is the code for it:

<iframe src="https://blastar-1984.appspot.com/" width="1000px" height="1000px">
  <p>Sorry, your browser does not support this game</p>
</iframe>
like image 434
Auginis Avatar asked Dec 06 '25 17:12

Auginis


1 Answers

If you can use Sachin's solution, go for it, but I'm pretty sure it only works for media elements, which are just audio and video elements, last I checked (spec). But things change fast, so maybe you're in luck.

If you can't change it at the iframe level, then you're going to run into cross origin issues. If you can control the headers of the app you're embedding, X-Frame-Origins is your friend. If you use that header to loosen your restrictions on the game's original page, your javascript will need only to look something like this:

var iframe = document.querySelector('iframe[src="https://blastar-1984.appspot.com/"]');
// This code could probably be tidied up, depending on how familiar you are with the game code
iframe.contentDocument.getElementById("muted").checked = true;
iframe.contentWindow.speaker[0].muted = true
iframe.contentWindow.speaker[1].muted = true

If, however, you're not so lucky, then the same origin policy might have you beat. In that case, I'd just suggest making a div and replacing it with the iframe when the click "play" (excuse the lazy CSS in the snippet): example. That gives you the added bonus of not loading up content before the user wants it (which is good for performance / mobile browsers).

Good luck!

like image 150
smeltedcode Avatar answered Dec 08 '25 05:12

smeltedcode



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!