I’m working on a Flask application and trying to display YouTube videos from an external data source. The video URLs I receive look like this: https://www.youtube.com/watch?v=B7YVX8K2M5p
When I try to embed these directly in an iframe, I get this error message:
I attempted to fix this by replacing watch with embed in the URL, which made the YouTube player appear, but the video won’t load and shows an error instead.
I’ve been searching for solutions and tried adding &output=embed parameter to the URL, but that didn’t work either. What’s the correct way to embed YouTube videos in iframes without running into these frame restrictions?
had this exact same issue last week! you probly need to use youtube’s embed api instead of just changing the url. try adding ?enablejsapi=1 to your embed url - worked for me when regular embed wasnt loading properly.
YouTube restricts the use of standard watch URLs for iframe embedding due to X-Frame-Options. To resolve this, you’ll need to convert the watch URL to the proper embed format. For example, change https://www.youtube.com/watch?v=B7YVX8K2M5p to https://www.youtube.com/embed/B7YVX8K2M5p. You can create a function in your Flask application to automate this URL conversion, which will help you avoid the embedding issue.
The X-Frame-Options SAMEORIGIN error occurs because YouTube’s regular watch pages are designed to prevent embedding on external sites. However, there’s a specific process for proper YouTube iframe embedding that goes beyond just changing the URL structure. You need to extract the video ID from your source URL and construct the embed URL correctly. The video ID in your example is the part after ‘v=’ which is ‘B7YVX8K2M5p’. Then construct the embed URL as ‘https://www.youtube-nocookie.com/embed/B7YVX8K2M5p’ - notice I’m using youtube-nocookie.com which provides enhanced privacy protection. Additionally, make sure your iframe includes proper attributes like frameborder=“0” and allow=“accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture” for full functionality. This approach has worked reliably in my Flask projects without any frame restriction issues.