Search code examples
javascripthtmliframegetelementsbytagname

Creating a "Push-to-mute" button


I have a <video> object on a page that is inside of an <iframe>. I'd like essentially a "push-to-mute" button, that will mute the video while the button is clicked, then unmute as soon as the button is let go. The final project will be embedding a page I don't have access to yet, but it will be a page that simply has a <video> tag on it. I inserted a sample video that also has a <video> tag on the page to dev this out.

My HTML looks something like this, with a button that will trigger one function when the mouse goes down, and one that will trigger another function when the mouse comes back up.

<button onmousedown="mute()" onmouseup="unmute()">MUTE</button>

<iframe id="video_iframe" src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4" allowfullscreen width="100%" height="100%" frameborder=0 style="border:none;"></iframe>

Now my Javascript looks something like this:

  function mute(){
var video = document.getElementById('video_iframe').contentWindow.document.getElementsByTagName()('video')[0];
video.muted = true;
}

function unmute(){
var video = document.getElementById('video_iframe').contentWindow.document.getElementsByTagName()('video')[0];
video.muted = false;
}

I think I have to use "getElementsByTagName" because what will eventually be in that iFrame in the end will be a page that has a tag with an Id that will be changing. I'm trying to control the first (and only) video in that iFramed page, so I would imagine getting the element by tag name would be the way to go there.

I don't know why this currently doesn't work, so any help is appreciated!


Solution

  • Using an iframe will return a cross-origin error, as, browsers like chrome does not allow you to change the content of an iframe directly unless, both the video and your HTML page are on the same web address.

    There are two ways which I can suggest you:

    1. Download the page on your machine and then <iframe> it.

    2. If you remove the iframe and use the <video> directly then it will also work fine on your machine.

       <script language="javascript">
      
       function mute(){
       var video = document.getElementById('at');
       video.muted = true;
       }
      
       function unmute(){
       var video = document.getElementById('at');
       video.muted = false;
       }
       </script>
       <button onmousedown="mute()" onmouseup="unmute()">MUTE</button>
      
       <video id="at" src="https://www.learningcontainer.com/wp-content/uploads/2020/05/sample-mp4-file.mp4" allowfullscreen width="100%" height="100%" frameborder=0 style="border:none;">