I am embedding a youtube video using the iframe tag, but am unsuccessful at accessing the object's play functionality. Here is how I am loading the object:
<iframe id="player" type="text/html" width="640" height="390"
src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1&origin=http://example.com"
frameborder="0">
I've referenced the APIs, but I don't really understand how to access the play/pause functionality. I have tried using jquery as follows, but the captured object doesn't have the desired attributes:
vid = $('#player')
vid.playVideo() // doesn't work
I have also tried using the swfsobject as follows:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<script type="text/javascript">
var params = { allowScriptAccess: "always" };
var atts = { id: "myytplayer" };
swfobject.embedSWF("http://www.youtube.com/embed/ngf03kCRw3s",
"ytapiplayer", "425", "356", "8", null, null, params, atts);
</script>
However, nothing appears on the page (and there are no errors in the console). Help is appreciated, Thanks,
A simple way to play an embedded YouTube video with jQuery (and JS) is by appending the parameter "autoplay=1" to the src attribute of the iframe.
In your case, the code would be something like this:
$("#player")[0].src += "&autoplay=1";
Another example by Martin Wolf:
$(document).ready(function() {
$('#play-video').on('click', function(ev) {
$("#video")[0].src += "&autoplay=1";
ev.preventDefault();
});
});
body {
padding: 30px;
}
a {
display: inline-block;
margin-bottom: 20px;
color: #000;
font-family: Arial, sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="play-video" href="#">Play Video</a><br />
<iframe id="video" width="420" height="315" src="//www.youtube.com/embed/9B7te184ZpQ?rel=0" frameborder="0" allowfullscreen></iframe>
And that's it. The video will start to play.
If someone needs the solution in Vanilla JS please leave a comment and I'll come back to update the answer when I have some extra time.
Related
I'm trying to add the sightmap embed script (below) into a pug file. I've come up with this, but it is breaking the page:
script(src="https://sightmap.com/embed/api.js")
iframe( id="sightmap" width="100%" height="700px" style="border: 1px solid #cccccc;" src="https://sightmap.com/embed/sightmaphere?enable_api=1&origin=https://www.propertydomain.com/" frameborder="0")
script.
var embed = new SightMap.Embed('sightmap');
embed.on('ready', function() {
}
embed.on('outbound.thriveKnock.click', function(event) {
knockDoorway.openScheduling();
}
Here is the original script for the iframe:
<!-- Engrain/Knock Map/CTA -->
<script src="https://sightmap.com/embed/api.js"></script>
<iframe id="sightmap" width="100%" height="700px" style="border: 1px solid #cccccc;" src="CURRENT-SIGHTMAP-URL-HERE?enable_api=1&origin=https://propertydomain.com" frameborder="0"></iframe>
<script type="text/javascript">
// Create a new embed instance, providing the IFrame id value
var embed = new SightMap.Embed('sightmap');
embed.on('ready', function() {
});
// Outbound Link API
embed.on('outbound.thriveKnock.click', function(event) {
// Open Knock Scheduler
knockDoorway.openScheduling();
});
</script>
<!-- End Engrain/Knock Map/CTA -->
Thanks very much.
I have a video that I want to show to users on the website, I created a button where they click and it shows a youtube video in popup, but when I close it, it still shows "Playing audio" in the tab and you can hear the video still. How can I achieve when they click X or anywhere else(they can closing it too by clicking anywhere) to actually stops the video and its audio.
$(document).ready(function() {
$('#headerVideoLink').magnificPopup({
type:'inline',
midClick: true // Allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source in href.
});
});
#headerPopup{
width:75%;
margin:0 auto;
}
#headerPopup iframe{
width:100%;
margin:0 auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/magnific-popup.min.css" rel="stylesheet"/>
<span class="icon-play mr-2"></span>Watch Video</p>
<div id="headerPopup" class="mfp-hide embed-responsive embed-responsive-21by9">
<iframe class="embed-responsive-item" width="854" height="480" src="https://www.youtube.com/embed/qN3OueBm9F4?autoplay=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
Any help will mean a lot, thanks!
What if you use the iframe content type of the MagnificPopup plugin?
So it would look something like this:
$(document).ready(function () {
$('#headerVideoLink').magnificPopup({
type: 'iframe',
midClick: true,
items: {
// HTML markup of popup, `mfp-close` will be replaced by the close button
markup: '<div class="mfp-iframe-scaler">' +
'<div id="headerPopup" class="mfp-hide embed-responsive embed-responsive-21by9">' +
'<iframe class="embed-responsive-item" width="854" height="480" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>' +
'</div>',
patterns: {
youtube: {
// URL that will be set as a source for iframe.
src: 'https://www.youtube.com/embed/qN3OueBm9F4?autoplay=1'
}
},
// Templating object key. First part defines CSS selector, second attribute.
// "iframe_src" means: find "iframe" and set attribute "src".
srcAction: 'iframe_src',
}
});
});
https://dimsemenov.com/plugins/magnific-popup/documentation.html#iframe-type
Or try to clear the iframe source using your original Javascript:
$(document).ready(function () {
$('#headerVideoLink').magnificPopup({
type: 'inline',
midClick: true,
callbacks: {
open: function () {
// Will fire when this exact popup is opened
// this - is Magnific Popup object
},
close: function () {
// Will fire when popup is closed
$('#headerPopup > iframe').attr('src', '');
}
}
});
});
I'm working on a modal window which allows user to either 1.) paste a video url or 2.) select a file from local drive then get a preview using html5's <video>tag.
Option 2.) Selecting a video file locally work perfectly. However, when I paste a youtube video url on input text field, the video player shows a loading indicator then stops. You can't play the video and doesn't seem to load successfully.
I checked Google Chrome's inspector and get this message
Cross-Origin Read Blocking (CORB) blocked cross-origin response
https://www.youtube.com/... with MIME type text/html.
I suspect the problem is in this line.
$('#modalInput_pasteURL').on('input',function(e){
var videoUrl = $('#modalInput_pasteURL').val().trim();
$(".video").attr("src", videoUrl);
});
I read while doing research that <iframe> must be used to contain or play a youtube video from a url. In this case, I'd like to use just <video> tag so that I only have one video container.
What am I missing? Any suggestions?
Below is are the code snippets.
HTML file
<label>Paste Url here</label>
<input type="text" class="modal_inputbox" id="modalInput_pasteURL"/><br>
<label>Select Video</label>
<input type="file" class="modalbtn_browseFiles" id="modalBtn_choose_video_file" value="Browse Video" accept="video/*"/><br>
<label>Video Preview</label>
<div class="modalContainer_filePreview" id="modalContainer_videoPreview">
<video controls class="video" width="510" height="200">
</video >
</div>
JS file
$('#modalInput_pasteURL').on('input',function(e){
var videoUrl = $('#modalInput_pasteURL').val().trim();
$(".video").attr("src", videoUrl);
});
$("#modalBtn_choose_video_file").on('change',function(event){
var fileInput = document.getElementById('modalBtn_choose_video_file');
var fileUrl = window.URL.createObjectURL(fileInput.files[0]);
$(".video").attr("src", fileUrl);
});
Thank you.
After doing some research and also taking the comment of zer00ne and Adam McGurk into consideration, I realized that the best way to load the youtube video url is through <iframe> then the problem of isolating or obtaining the youtube video's id came up.
Then, I ended up finding a related resource and answer here in SO which solved my problem.
function getYoutubeVideoId(url) {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
return match[2];
} else {
return 'error';
}
}
$('#modalInput_pasteURL').on('input',function(e){
var videoUrl = $('#modalInput_pasteURL').val().trim();
var videoId = getYoutubeVideoId(videoUrl);
$('#modalContainer_videoPreview').html('<iframe width="510" height="200" src="//www.youtube.com/embed/' + videoId + '" frameborder="0" allowfullscreen></iframe>');
});
This should serve as reference to others who are trying to accomplish the same effect when pasting a youtube url in a text field and loading it to a container such as an <iframe> which works best.
YouTube videos can be embedded into a webpage by either using a <div> or an <iframe> tag and loading YouTube IFrame Player API. The following Demo is a modification of the OP code. It can play either a standard video or a YT video. The Stack Snippet cannot play YouTube videos on SO site, so to properly test it, you either copy and paste the entire code elsewhere or go to this Plunker.
Note: There is some code commented out that is included should you want to load the YT API in order to control the YT player programmatically.
Plunker
Demo
Details commented in Demo
The YouTube video will not play on SO due to sandbox, go to Plunker for a fully functional Demo
/* If you want programattic control over the YT Player uncomment
|| the following block and the block after the next block
*/
/*/ Load YouTube IFrame Player API
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
*/
// Reference video tag
var vid = document.getElementById('vid');
/*/ Declare YT Player
var ytv;
// Define YT Player
function onYouTubeIframeAPIReady() {
ytv = new YT.Player('ytv');
}
*/
// Seup switch behavior
$('.switchBtn').on('click', function(e) {
$('.switchBtn').removeClass('act');
$(e.target).addClass('act');
});
// Delegate input event to #pasteURL
$('#pasteURL').on('input', function(e) {
// Get the url string
var videoUrl = $('#pasteURL').val().trim();
// if the "Standard Video" switch is active...
if ($('.v').is('.act')) {
// ...enable controls on vid...
vid.controls = true;
// ...set src to url string...
vid.src = videoUrl;
// ...reset vid so it cues new url
vid.load();
// ...otherwise...
} else {
// ...pause vid...
vid.pause();
// ...reset vid...
vid.currentTime = 0;
// ...remove vid controls...
vid.controls = false;
// ...set ytv src to new url
$('#ytv').attr('src', videoUrl);
}
});
$("#file").on('change', function(event) {
var fileInput = $('#file')[0];
var fileUrl = window.URL.createObjectURL(fileInput.files[0]);
$("#vid").attr("src", fileUrl).prop("controls", true);
});
input,
label {
display: inline-block;
font: inherit;
margin: 10px 0 0 0;
}
input[type=text] {
width: 350px;
}
.group {
pointer-events: none;
opacity: 0.4;
}
.switchBtn {
width: 110px;
height: 18px;
margin: 15px -2px 10px -2px;
border: 3px outset grey;
padding: 2px 3px 0;
cursor: pointer;
}
.switchBtn.act {
background: tomato;
color: #fff
}
.switchBtn.act~.group {
pointer-events: auto;
opacity: 1;
}
.switchBtn.v {
border-top-left-radius: 12px;
border-bottom-left-radius: 12px;
text-align: right;
}
.switchBtn.y {
border-top-right-radius: 12px;
border-bottom-right-radius: 12px;
}
.switch {
display: none
}
.switch:checked+* {
height: 405px;
transition: 1s;
}
<!DOCTYPE html>
<html>
<head>
<!--<link rel="stylesheet" href="style.css">-->
</head>
<body>
<label for='vidURL' class='switchBtn v'>Standard Video</label>
<label for='ytvURL' class='switchBtn y'>You Tube Video</label>
<br>
<fieldset class='group'>
<label>Test Std URL: </label>
<input type='text' readonly value='https://ia800209.us.archive.org/24/items/WildlifeSampleVideo/Wildlife.mp4'>
<br>
<label>Test YT URL: </label>
<input type='text' readonly value='https://www.youtube.com/embed/Ch5MEJk5ZCQ?enablejsapi=1'>
<br>
<label>Paste Url here </label>
<input type="text" id="pasteURL" />
</fieldset>
<label>Select Video </label>
<input type="file" id="file" value="Browse Video" accept="video/*" />
<br>
<label>Video Preview</label>
<figure class="filePreview">
<input id='vidURL' type='radio' name='switch' class='switch'>
<video id="vid" width="100%" height="0"></video>
<input id='ytvURL' type='radio' name='switch' class='switch'>
<iframe id="ytv" type="text/html" width="100%" height="0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</figure>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--<script src="script.js"></script>-->
</body>
</html>
There are a couple of problems here, and it doesn't even necessarily have to do with your code. I didn't even look at your code here, because it's unimportant.
You will not be able to take a YouTube URL and paste it into the src attribute of the video tag and have it play. That just isn't how YouTube works.
YouTube doesn't serve it's videos by plain URLs. Imagine if they did that, anybody could get into the inspect tool and download the video straight from YouTube.
So how do they serve their videos? Through BLOBs:
Here's a pretty good explanation of what a BLOB is: https://developer.mozilla.org/en-US/docs/Web/API/Blob
So you won't be able to just take the URL, it's just not how YouTube works. And so the way I would frame your code would be to have a control statement that detects if there is an iframe tag or not, and if there is, insert just the iFrame, but if there is not, insert your video URL.
Obviously there are many security holes there, but that is out of the scope of this answer. If you want to go more of the route that I outlined a little bit, do some research, ask another question, and we'd be glad to help you out!
I have two iframes in one page.
<iframe id="video" width="420" height="315" src="//www.youtube.com/embed/9B7te184ZpQ?rel=0" frameborder="0" allowfullscreen></iframe>
<iframe id="video1" width="420" height="315" src="//www.youtube.com/embed/9B7te184ZpQ?rel=0" frameborder="0" allowfullscreen></iframe>
I want to access onplay() event of iframe, then i can able to stop second video(#Video1) while playing first one(#Video) and Stop first video(#Video) when playing Second(#Video1).
It is possible using YoutubeAPI but i do not want to use that because i have other url videos not Youtube videos(here i put youtube links instead orignal links to avoid copyright). Is there another way except YoutubeAPI. YoutubeAPI is not working on another link resources. Please Suggest.
It has two <iframe>. First, you need switch between iframe.
Is there a way to change context to iframe in javascript console?
After, here my code how to access to event onPlay() of <iframe>
<script src="https://www.youtube.com/iframe_api"></script>
<div class="module module-home-video">
<span class="module-strip">Latest Product Video</span>
<div id="video"></div>
</div>
<script>
var player, playing = false;
function onYouTubeIframeAPIReady() {
player = new YT.Player('video', {
height: '360',
width: '640',
videoId: 'xmhtV4270NU',
events: {
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerStateChange(event) {
if(!playing){
alert('onPlay is clicked');
playing = true;
}
}
</script>
I have an iframe that I would like to automatically refresh itself without doing a whole page refresh. I would prefer to use javascript or jquery. This is what I have been trying unsuccessfully.
<div class="Widget"><!--DARK SKY-->
<div class="WidgetHeader">
<img src = "images/WidgetHeaders/DarkSky.png"></div>
<div id="DarkSky" style="width: auto; height: 245px; padding: 5px; background-color: hsla(0,0%,100%,.9);">
<iframe id="forecast_embed" type="text/html" frameborder="0" height="245" width="100%" src="http://forecast.io/embed/#lat=38.269571&lon=-85.487420&name=Louisville&units=us&color=#4c7cba"> </iframe>
</div>
</div>
<script type = "text/javascript">
window.onload = function() {
setInterval(function refreshDarkSky() {
document.getElementById("#forecast_embed").src ="http://forecast.io/embed/#lat=38.269571&lon=-85.487420&name=Louisville&units=us&color=#4c7cba"
}, 90000);
}
</script>
if iframe is not from different domain, you can use:
document.getElementById('forecast_embed').contentDocument.location.reload(true);
for cross domain,
var iframe = document.getElementById('forecast_embed');
iframe.src = iframe.src;
try this code
$(document).ready(function () {
setInterval(function refreshDarkSky() {
$("#forecast_embed").attr("src","http://forecast.io/embed/#lat=38.269571&lon=-85.487420&name=Louisville&units=us&color=#4c7cba");
}, 90000);
});
Use this:
$('#forecast_embed',window.parent.document).attr('src',
$('#forecast_embed',window.parent.document).attr('src'));
It has to untie your issue.
try this
window.top.location.reload();