Explain Codes LogoExplain Codes Logo

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

html
responsive-design
iframe
caching
Alex KataevbyAlex Kataev·Aug 6, 2024
TLDR

To bypass X-Frame-Options restrictions, use the YouTube embed URL when you're embedding a video in an iframe:

<!-- Not just a box. A magic video portal! --> <iframe src="https://www.youtube.com/embed/VIDEO_ID" width="560" height="315" frameborder="0" allowfullscreen></iframe>

Replace VIDEO_ID with your video's unique ID. Ensure /embed/ is part of your URL to respect cross-origin rules and prevent SAMEORIGIN errors.

What not to do when embedding YouTube videos

Faux pas: Incorrect video URL

Many users mistakenly attempt to embed a video using the direct watch URL, youtube.com/watch?v=VIDEO_ID. It's made for viewing, not embedding. Use /embed/ not /watch in your URL.

Misconceptions: Unnecessary parameters

Avoid appending &output=embed to the YouTube URL. It's redundant, can create confusion, and should be a relic of the past.

The younger sibling no one likes: v endpoint

Steer clear of the /v/ URL endpoint. Stick to its older, wiser sibling, /embed/, with all the inherent embedding permissions.

Strategically handling embedding: Expert tips

Embrace adaptive design

Design responsibly! Use CSS magic to make your YouTube videos responsive. With some CSS styling, your iframes can resize to match your layout. Simply wrap your iframe within a div.

<!-- This div is magic. It makes videos shrink and grow! --> <div style="width: 100%; padding-top: 56.25%; position: relative;"> <iframe src="//www.youtube.com/embed/VIDEO_ID" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: 0;"></iframe> </div>

Django, don't be a party pooper

For those using Django, remember it might be imposing iframe restrictions due to the X-Frame-Options middleware. You might need to apply @xframe_options_exempt or tweak your Content Security Policy.

Kick out common hiccups

  • For a 404 error inside the iframe, double-check the video ID.
  • Clear your browser cache to rule out sneaky caching troubles.
  • If video loading fails, you might be dealing with a CORS issue.