1

I have a page that is created through a CMS that currently looks like this:

<!DOCTYPE html>
 <html>
 <head>
 </head>
 <body>
 <p><iframe src="//www.youtube.com/embed/id?start=1" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"  allow="autoplay"></iframe></p>
 </body>
 </html>

I've seen something similar to what I need but is there specifically a way that I can use a JS block so that anytime I have an iframe with a youtube url, I can add "&autoplay=1&mute=1" to the source URL to get:

<!DOCTYPE html>
 <html>
 <head>
 </head>
 <body>
 <p><iframe src="//www.youtube.com/embed/id?start=1&autoplay=1&mute=1" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"  allow="autoplay"></iframe></p>
 </body>
 </html>

2 Answers 2

2

In your script get your iframe elelment and then use .setAttribute()

let myFrame = document.getElementById('idOfMYFrame')
myFrame.setAttribute('mute': '1')
myFrame.setAttribute('autoplay' : '1')

You will probably need to do this within window.onload event.

Sign up to request clarification or add additional context in comments.

Comments

1

Yeah, this is possible. First, let's filter out all the iframes on your page by those we think have YouTube content. For that, we'll use a RegEx on the URL. (See also: Regex for youtube URL)

// RegEx Source:  https://stackoverflow.com/a/37704433/362536
const youtubeUrlPattern = /^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/;

Next, we'll query for all the iframes, actually do the filtering. Then, we'll edit the URL.

[...document.querySelectorAll('iframe')].filter((iframeEl) => {
  // Filter to iframes loading YouTube URLs only.
    return iframeEl.src.match(youtubeUrlPattern);
}).forEach((iframeEl) => {
  const a = document.createElement('a');
  a.href = iframeEl.src;
  a.search = a.search || '?'; // Ensure we have a minimal query string
  a.search += '&autoplay=1&mute=1'; // Naively concatenate our extra params.  (You may want to do more here, to see if they already exist.)
  iframeEl.src = a.href;
});

Note that I'm using an a element to do some of this URL parsing work for me. (See also: https://stackoverflow.com/a/4497576/362536).

I put up an example for you on a JSFiddle: https://jsfiddle.net/3y251ued/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.