在 iframe 中向 YouTube URL 添加查询字符串参数

Add querystring parameters to YouTube URL in iframe

我有一个通过 CMS 创建的页面,目前看起来像这样:

<!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>

我看到了一些与我需要的类似的东西,但是有没有一种方法可以使用 JS 块,这样只要我有一个带有 YouTube 的 iframe url,我就可以添加“&autoplay= 1&mute=1" 到源 URL 得到:

<!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>

在您的脚本中获取您的 iframe 元素,然后使用 .setAttribute()

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

您可能需要在 window.onload 活动中完成此操作。

是的,这是可能的。首先,让我们根据我们认为具有 YouTube 内容的内容过滤掉您网页上的所有 iframe。为此,我们将在 URL 上使用 RegEx。 (另请参阅:Regex for youtube URL

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

接下来,我们将查询所有的 iframe,实际进行过滤。然后,我们将编辑 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;
});

请注意,我正在使用 a 元素为我完成一些 URL 解析工作。 (另请参阅:)。

我在 JSFiddle 上为您举了一个例子:https://jsfiddle.net/3y251ued/