插入DOM时,视频不会在chrome上自动播放 [英] video will not autoplay on chrome when it is inserted into the DOM
问题描述
我有一个视频(出于背景目的),该视频已静音,我打算自动播放.如果我将以下代码放入html文件中:
I have a video (meant for background purposes), that is muted and I intend to auto-play. If I were to put the following code into an html file:
<video playsinline autoplay muted loop>
<source src="https://res.cloudinary.com/dthskrjhy/video/upload/v1545324364/ASR/Typenex_Dandelion_Break_-_Fade_To_Black.mp4">
</video>
在Chrome上运行正常.
It would work just fine on Chrome.
但是,如果我要使用DOM操作插入完全相同的视频,则我在Chrome上会遇到麻烦,但在其他浏览器(如Firefox)中会获得成功.
However, If I were to insert the exact same video using DOM manipulation, I would have trouble on Chrome but success in other browsers like Firefox.
<html>
<body>
</body>
<script>
function render() {
const video = document.createElement('video');
video.setAttribute('muted', true);
video.setAttribute('autoplay', true);
video.setAttribute('loop', true);
video.setAttribute('playsinline', true);
const source = document.createElement('source');
source.setAttribute('src', 'https://res.cloudinary.com/dthskrjhy/video/upload/v1545324364/ASR/Typenex_Dandelion_Break_-_Fade_To_Black.mp4');
video.appendChild(source);
document.body.appendChild(video);
}
render();
</script>
</html>
Chrome似乎因屏蔽而臭名昭著自动播放.通用解决方案要么被静音(我已经做过),要么使用dom操纵来调用播放(不起作用).将视频插入dom后,是否有办法使它正常工作.我关心的原因是因为我的实际网站要求呈现所有内容(我的网站在ember.js中).
Chrome appears notorious for blocking autoplay. The general solutions are either to be muted (which I already do), or to use dom manipulation to call play (which doesn't work). Is there a way to get this to work after inserting the video into the dom. The reason I care is because my actual website requires everything to be rendered (My site is in ember.js).
这是Chrome 71版.
This is in Chrome version 71.
谢谢!
推荐答案
这可能是一个错误(并非唯一使用此自动播放策略的错误...).
This is probably a bug (and not the only one with this autoplay policy...).
通过Element.setAttribute()
设置muted
属性时,该策略不会像应有的那样释放.
When you set the muted
attribute through Element.setAttribute()
, the policy is not unleashed like it should be.
要解决此问题,请通过Element的属性设置IDL属性:
To workaround that, set the IDL attribute through the Element's property:
function render() {
const video = document.createElement('video');
video.muted = true;
video.autoplay = true;
video.loop = true;
video.setAttribute('playsinline', true);
const source = document.createElement('source');
source.setAttribute('src', 'https://res.cloudinary.com/dthskrjhy/video/upload/v1545324364/ASR/Typenex_Dandelion_Break_-_Fade_To_Black.mp4');
video.appendChild(source);
document.body.appendChild(video);
}
render();
作为小提琴,因为始终需要从父页面请求点击事件的StackSnippet进行自动播放; -).
As a fiddle since StackSnippets requiring a click event form the parent page are anyway always allowed to autoplay ;-).
这篇关于插入DOM时,视频不会在chrome上自动播放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!