Reputation: 281
I am trying to create a feature wherein an image with play icon is shown and when the user clicks on the icon, we load the video in an iframe in a popup. According to this link , iframe should be allowed to autoplay if user interacted with the website using allow='autoplay' attribute. But this doesnt seem to work in our case on Chrome mobile browser v.66. Since we are loading the video only after the user clicks on play, it should be a legitimate case of user interaction I suppose.Is there something that I am missing out ?
Upvotes: 0
Views: 349
Reputation: 136638
It seems that Chrome for Mobile still requires that you handle this from the user-gesture event itself (just like Safari btw).
The time your iframe loads, your user-gesture approval will have expired, and you wont be able to auto-play nor programmatically play your <video>
with sound.
One way around though, if your iframe doc is on the same domain, is to load an other <video>
element from the main document, inside the user-gesture event, to mark it as user approved (by calling MediaElement.play()), and once your iframe has loaded to replace your iframe's element with this user-approved one in the iframe's doc.
btn.onclick = e => { // we must have an user-gesture event
const iframe = document.createElement('iframe'); // your iframe
const frameContent = `<html>
<body>
<video src="https://upload.wikimedia.org/wikipedia/commons/transcoded/2/22/Volcano_Lava_Sample.webm/Volcano_Lava_Sample.webm.360p.webm"></video>
</body>
</html>`;
const url = URL.createObjectURL(new Blob([frameContent], {type: "text/html"}));
// Our user-approved <video>
const vid = document.createElement('video');
vid.play().catch(e => null); // mark it as 'user-approved'
vid.autoplay = true;
iframe.onload = e => { // once our iframe have loaded
// swap both elements
const i_vid = iframe.contentDocument.querySelector('video');
i_vid.replaceWith(vid);
vid.src = i_vid.currentSrc;
};
iframe.src = url;
document.body.append(iframe);
};
StackSnippet's over- protected iframes won't allow us to manipulate this inner frame, so here is a live jsfiddle.
Upvotes: 1