How to play live video on page load?

I have a javascript code that checks whether there are some people connected to a room in Twilio Programmable Video. If there are any participants, the javascript adds their remote video to the webpage.

    // A function that adds a remote participant audio & video to the current web page.
    function AddParticipantAudioAndVideo(participant) {     
        participant.tracks.forEach(publication => {
            if (publication.track) {
                document.getElementById("some html item").appendChild(track.attach());
                console.log("track subscribed");                    
            }
        });
        
        participant.on('trackSubscribed', track => {
            document.getElementById("some html item").appendChild(track.attach());
            console.log('track subscribed');        
        });     
    }

    
    function InitializeRoom() {
        // room is defined somewhere else           
        room.on('participantConnected', participant => {            
          console.log('A remote Participant connected : ' + participant.identity);       

          AddParticipantAudioAndVideo(participant);       
        });
        
        // Loop over all the participants already connected to the room
        room.participants.forEach(participant => {AddParticipantAudioAndVideo(participant)});
    } 

If I call this code from a button click for example, it works and live video plays properly :

    <div onclick="InitializeRoom()">My Button</div>

However if I call the exact same code from the page load event handler (before any manual interaction with the page), it doesn’t work and the video tag is not added to the html document.

    window.addEventListener("load",function(event){ 
        InitializeRoom();
    });

I know that Chrome doesn’t like videos with audio and autoplay = true. So I was wondering if this problem is due to the same reason and if there is any solution to that.

Thanks Cheers,

Answer

I know that Chrome doesn’t like videos with audio and autoplay = true. So I was wondering if this problem is due to the same reason and if there is any solution to that.

Yes, exactly.

Based on your other questions, I assume you’re wanting to do this in some automated context where you have control over the browser. If so, you can add a flag to the Chrome/Chromium command line:

chrome.exe --autoplay-policy=no-user-gesture-required

See also: https://developer.chrome.com/blog/autoplay/#developer-switches