我有一个通过当前看起来像这样的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时,我都可以添加"&amp; autoplay = 1&amp; 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 ellelment,然后使用.setAttribute((
let myFrame = document.getElementById('idOfMYFrame')
myFrame.setAttribute('mute': '1')
myFrame.setAttribute('autoplay' : '1')
您可能需要在Window.onload事件中进行此操作。
是的,这是可能的。首先,让我们通过我们认为具有YouTube内容的内容来过滤您页面上的所有iFrame。为此,我们将在URL上使用正直。(另请参见: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/