Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't my Youtu.be URL work for video embedding?

Tags:

html

youtube

I want to embed a YouTube video link in my web page with something like url://youtu.be. It's not appearing when I embed that in my web page. The below code, however, is working well (url://youtube without the dot).

<iframe width="420" height="315" src="https://www.youtube.com/embed/4pXUcxWLA7g" frameborder="0" allowfullscreen></iframe>

Why does using a "youtu.be" link not embed properly?

like image 672
asb14690 Avatar asked Aug 31 '25 05:08

asb14690


2 Answers

Because youtu.be is a URL shortening service. So when you go to a you.be URL, all it does is Redirect you to the full URL for a video.

Edit, actually that's not the complete end of the story. What happens when you do that is yes, it redirects you, but then the browser gives an error:

"Refused to display (video url) in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'."

So, this could work with redirection, but it doesn't because youtube sends down this response

header: x-frame-options:SAMEORIGIN

And so the browser refuses to display it because it's not the same origin (that is, it's not being served from the same domain). Why does youtube do this? That I don't know. But, basically, it appears you MUST you the youtube.com/embed style URL for iframe. If you have URLs in the youtu.be format (maybe in your database or something), then you will need to hit the youtu.be link and then see where it wants to redirect you to, and then use THAT link for your iframe.

like image 52
aquinas Avatar answered Sep 02 '25 18:09

aquinas


In case you use JavaScript simply use string replace function to replace the youtu.be part to youtube.com/embed like in comments

let youtubelink = 'youtu.be/video_link_path';
youtubelink = youtubelink.replace('youtu.be', 'youtube.com/embed');

in case of php the script is slightly different you can run the above statement in PHP like

$youtubelink = 'youtu.be/video_link_path';
$youtubelink = str_replace("youtu.be","youtube.com/embed", $youtubelink);
like image 32
M.I.A Avatar answered Sep 02 '25 20:09

M.I.A