[Fixed] YouTube Video Autoplay not working

What I’m trying to do:
Make a youtube video play automatically when either shown in a form or shown in an alert.

What I’ve tried and what’s not working:
I have tried setting the the autoplay option to True from the Component properties as well as in code but nothing seems to work. I have also tried using the play() method from a form show but that does not work either. Have tried it with a few different videos from the one in the example as well.

It looks like it tries to do something but doesn’t actually start the video.

Any help is appreciated.

Code Sample:

# this is a formatted code snippet.
# paste your code between ``` 

Clone link:
share a copy of your app

Example Link

Thanks @rickhurlbatt this is a case of browser standards changing over time, we’ll get that fixed.

For now here’s a hack you can include in a startup form/module

from anvil import YouTubeVideo
from anvil.js import get_dom_node

old_init = YouTubeVideo.__init__

def yt_init(self, *args, **kws):
    el = get_dom_node(self)
    el.querySelector("iframe").setAttribute("allow", "autoplay")
    return old_init(self, *args, **kws)

YouTubeVideo.__init__ = yt_init

You’ll find that trying to autplay a video on first load might still not work because browsers these days don’t tend to play videos until a page has a high enough user interaction score.

The play in the form show event will likely be subject to the same user interaction score.
I have found that if I set the video to mute and call the .play() method in the form_show event it works.
But this may change in the future.
And may differ across browsers.

1 Like

Ok Great, Thanks for the detailed explanation and hack.
Much appreciated

@rickhurlbatt that should now be fixed.

You also should no longer need the form_show event to call .play() so long as you set mute to be True with autoplay.
(at least on chrome)

2 Likes