Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

javascript - Embed Youtube video from URL

Im new in all this amazing thing called front end and i′m already working in a project but i need a little help with this:

So the thing is that the user could enter a youtube URL in a text box and a embed iframe video is automatically generated from it so he can preview it without reloading the page

How could i do that?

a have found 2 separated scripts that could help but i can′t make them work at the same time:

Extract YouTube video ID from URL:

[http://codepen.io/catmull/pen/cnpsK][1]

YouTube Embed Optimized with JavaScript:

[http://codepen.io/SitePoint/pen/CKFuh][1]

Any ideas? It will really help me if you answer with a live example :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

if you have youtube url https://www.youtube.com/watch?v=sGbxmsDFVnE, you can embed it by taking the video id off the end and putting at the end of youtube.com/embed/

you can get the video id using string.split()

var url = "https://www.youtube.com/watch?v=sGbxmsDFVnE";
var id = url.split("?v=")[1]; //sGbxmsDFVnE

var embedlink = "http://www.youtube.com/embed/" + id; //www.youtube.com/embed/sGbxmsDFVnE

then just make that embed link the source to an existing iframe on the page

document.getElementById("myIframe").src = embedLink;

example of an iframe

<iframe id="myIframe" width="560" height="315" frameborder="0" allowfullscreen></iframe>

working code here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...