1

我有一个通过 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 url 的 iframe 时,我都可以将“&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>
4

2 回答 2

2

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

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

您可能需要在 window.onload 事件中执行此操作。

于 2019-05-01T16:33:17.793 回答
1

是的,这是可能的。首先,让我们根据我们认为具有 YouTube 内容的内容过滤掉您网页上的所有 iframe。为此,我们将在 URL 上使用 RegEx。(另请参阅: 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+)?$/;

接下来,我们将查询所有 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 解析工作。(另见: https ://stackoverflow.com/a/4497576/362536 )。

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

于 2019-05-01T16:45:04.343 回答