Search code examples
javascriptphpiframeyoutube

Getting YouTube embed videos to target an iframe on another url on my site


My Homepage has links on to youtube videos that open in an iframe on the Homepage when I click on the video thumbnail/link.

Page1 - Has an iframe named 'Main'.

I want the videos on the homepage, to target 'Main' on Page1 when I click on the thumbnail on the homepage.

So basically I want videos (which are listed on the homepage) to play in an iframe that exists on a different page.

Thanks for any help, Chris


Solution

  • If I got you right, you want the user to click a YouTube thumbnail on your homepage and then navigate to another page where there is an iframe inside which the YouTube video should be loaded, correct?

    home.html

    <a href="page1.html?yt=eokuVGX7oAI">
        <img src="https://img.youtube.com/vi/eokuVGX7oAI/3.jpg" alt="" />
    </a>
    
    <a href="page1.html?yt=pI0EpHD43Xo">
        <img src="https://img.youtube.com/vi/pI0EpHD43Xo/3.jpg" alt="" />
    </a>
    

    page1.html

    <iframe name="Main" id="Main" src="about:blank" width="640" height="320"></iframe>
    
    <script>
        const urlParams = new URLSearchParams(window.location.search);
        const ytId = urlParams.get('yt');
        const ytLink = 'https://www.youtube.com/embed/' + ytId + '?autoplay=1';
        document.getElementById('Main').src = ytLink;
    </script>
    

    Note: Even though it worked like a charm during my testing, autoplay might not work on all browsers / devices because of restrictions. There's no way around that limitation.

    page1.html (with default)

    <iframe width="560" height="315" src="about:blank" frameborder="0" allowfullscreen="" xmlns:xsi="w3.org/2001/XMLSchema-instance" name="main" id="main" ></iframe>   
    
    <script>
        const urlParams = new URLSearchParams(window.location.search);
        const ytId = urlParams.get('yt');
        if(ytId==null) {
            //Parameter empty, default to whatever video
            document.getElementById('main').src = 'https://www.youtube.com/embed/PS9EBbgf0dk?autoplay=1';
        } else {
            const ytLink = 'https://www.youtube.com/embed/' + ytId + '?autoplay=1';
            document.getElementById('main').src = ytLink;
        }
    </script>