Unable to change HTML iframe source with Javascript - javascript

I'm trying to have a 'video of the day' on my website. I currently have most of this working, and here's how I plan to have it working in the end:
Have a Python script run once every 24 hours to pick the random YouTube video of the day
Write the embedded video URL to a text file
Use Javascript to access the text file and grab the video URL, and use it as the iframe source on my webpage
As I mentioned above, this plan is currently working for the most part. My script is able to pick the random video, and write it to a text file. My web page is then able to pull the video URL from the text file, and write it to the webpage in text form. However, I'm having some troubles having it write the video URL to my iframe.
I did some searching, and people suggested trying the following code:
<iframe id="mainvideo" width="720" height="480" frameborder="0" src="" allowfullscreen></iframe>
<script>
document.getElementById("mainvideo").src =
finalresult + ReturnURL();
</script>
So earlier in my code, I declared the variable 'finalresult' to be the following value: //www.youtube.com/embed/WJDnJ0vXUgw
When I have Javascript write 'finalresult' to my webpage, it will write the video URL as text to the webpage as expected. However, when I try and declare it as the source for the iframe, I end up with a blank iframe on the page.
Does anyone know what the problem is with my code for it not showing this video in my iframe? Any help would be appreciated.

You must be changing the src after any particular event is fired. So try this way,
HTML :
<iframe id="mainvideo" width="720" height="480" frameborder="0" src="http://www.bing.com/" allowfullscreen></iframe>
<button id="changeSrc">Change iFrame</button>
javaScript :
var iframe = document.getElementById("mainvideo");
changeSrc.onclick = function(){
iframe.src = "http://www.w3schools.com/";
};
jsFiddle
Update 1 :
If you want to change the iframe src attribute after page load then go with this way,
window.onload = function(){
var iframe = document.getElementById("mainvideo");
iframe.src = "http://www.w3schools.com/";
};
jsFiddle

If myframe.src does not work for you, then try out myframe.contentWindow.location.href like in this pen.

Related

Changing an iframe SRC dynamically

What I have and I need to do it work properly is when I'm in a "start page" and I click a button like this:
PAGE-1
Point A
It should send me to "another page" where I load dinamically an iframe taking each variable (shopID, type, max-levels and point) from the URL and print it like an iframe this way:
PAGE-2
<iframe id="frame" src="http://myappwebsite/resourcesiframe?shopId=3366&type=image&point=A" width=“XXX" height=“XXX"></iframe>
I've used this javascript snippet but anyway, I can't make it work properly at all.
$(".map-button").click(function (e) {
e.preventDefault();
$("#frame").attr("src", $(this).attr('data - iframe - src'));
});
I only need to get the variables from the data-iframe-src and use them in the iframe, but I'm not able... The problem is that I load elements in different pages, so I don't know how this affect to the URL variables.
I've founded a simple solution for my problem here and it works for me.
First of all I put this simple iframe in my PAGE-2:
<iframe id="frame" src="" width="100%" height="auto" frameborder="0" scrolling="yes"></iframe>
Then in PAGE-1 I've used this type of links:
https://myappwebsite/page-2?shopId=1234&type=image&max-levels=1&point=A
So now my PAGE-2 loads properly with these params in the URL. Then I've used this simple snippet in Javascript to fill my iframe in PAGE-2:
<script type="text/javascript">
$( document ).ready(function() {
$("#frame").attr("src", "https://myappwebsite/resourcesiframe" + window.location.search);
});
</script>
And it works! Now I can go to PAGE-2 with all my params, pick them and use them in SRC inside the blank iframe.
Thanks for getting me in the correct path!

How to get a Youtube embed livestream url using javascript without third party plugins or API?

I'm building a little web page that has an iframe that automatically plays a live stream from a youtube channel using the channel ID.
I need to be able to get the complete URL from that element
(Example Link) without any third party plugins/programs or the API, the purpose of this is to extract the Livestream ID and display the live chat using it.
Here is the relevant code snippet:
<div>
<iframe id="stream" width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=UCTXma6j0F0IMEdRd4CisrIQ&autoplay=1" frameborder="0" allowfullscreen></iframe>
</div>
<div>
<iframe id="adress" width="560" height="315" src=adress frameborder="0"></iframe>
</div>
<div>
<script>
function search_id()
{
var url = stream.src;
var videoID = url.match(/(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=|\/user\/\S+|\/ytscreeningroom\?v=))([\w\-]{10,12})\b/)[1];
var concat = "https://www.youtube.com/live_chat?v=" +videoID +"&embed_domain=127.0.0.1";
document.getElementById("adress").src = concat;
document.getElementById("test").innerHTML= concat;
}
</script>
<button onclick="search_id()">Get URL</button>
</div>
The var "URL" is the one that should contain the complete URL of the live stream, the current content is just a placeholder, the iframe "address" is the holder for the live chat.
The reason to avoid the API it's because I can't fully comprehend how to use it (I'm attaching it anyway: link), of course, understanding how to get the specific string I'm looking for would be great.

change iframe to script includes the iframe

I have this part of code:
<div class="embed"><iframe id="iframe" src="<?php echo DOMAIN_NAME; ?>demo?q=<?php echo $number;?>"><body></body></iframe></div>
and i want to make an asychronous script that includes this iframe. So in the end i will give in my clients the asynchronous script code instead of iframe. I want to do that for 1 main reason. In case my website is down i don't want to decrease the speed of the websites/portals that my clients have post my iframe.
when somebody clicks on embed div then an iframe given to my clients. i want to give an asychronous script instead of this iframe.
Is it possible?
Any ideas?
You mean something like
var cosnikFrame = document.createElement("iframe");
cosnikFrame.width=450;
cosnikFrame.height=300;
cosnikFrame.setAttribute("scrolling","no");
cosnikFrame.style.border=0;
document.body.appendChild(cosnikFrame);
cosnikFrame.src="http://example.com/demo.php?q=12aA1b35A4a";
or to defer to after load using for example jQuery:
$(function() {
$("body").append('<iframe width='450' height='300' scrolling="no" style="border:0" src="http://example.com/demo.php?q=12aA1b35A4a"></iframe>');
});

Embed Youtube video in AngularJS generates error when loading the page

The code snippet below is used to embed Youtube video in my page.
<div ng-if="videoUrl != ''" style="height:400px;">
<iframe width="100%" height="100%" src="{{videoUrl}}"></iframe>
</div>
In my controller, videoUrl is first set to an empty string, and updated once data is retrieved from server.
$scope.videoUrl = '';
videoService.getData().then(function(response) {
$scope.videoUrl = response.videoUrl;
});
The Youtube player works and the URL is correct, I can watch the video with the embeded player after the page is fully loaded. What bothers me is each time when loading the page, an error is returned. I can see from the browser console that it was trying to send a GET request to http://www.example.com/%7B%7BvideoUrl%7D%7D with its status as (canceled). This request is not something I want and it fails for sure.
How can I get rid of that weird GET request?
I modified my code based on RGraham's suggestion and the error is gone now.
First, change src to ng-src and the checking condition to ng-if="videoUrl".
<div ng-if="videoUrl" style="height:400px;">
<iframe width="100%" height="100%" ng-src="{{videoUrl}}"></iframe>
</div>
Second, I initialize videoUrl to undefined.
$scope.videoUrl = undefined;
Now the page loads without sending the previous weird GET request anymore.

Embedding youtube video "Refused to display document because display forbidden by X-Frame-Options"

I'm trying to embed a youtube video on to my page once the user gives the link to the video.
<iframe width=\'560\' height=\'315\' src='http://www.youtube.com/watch?v=<video id>&output=embed' frameborder=\'0\' allowfullscreen></iframe>
But when I try to add this I get this error. After inspecting the page in chrome, I see this error in the console tab
"Refused to display document because of the display is forbidden by X-Frame-Options"
I'm not able to see the video even in IE and Firefox also
I even tried adding the
header('X-Frame-Options:Allow-From http://www.youtube.com');
header('X-Frame-Options:GOFORIT);
&output=embed to the url
After reading certain solutions in other posts.
But I still get the same error.
I also see that the youtube has the method of object embedding to show the video, but already youtube has made that as old method of embedding the video. So I want to use the new iframe method of embedding the video on to my page.
Problem is seen in
Firefox 11
Chrome 18.0
IE 8
Anybody faced this problem?
The page you're setting as the source of the iframe (the Youtube /watch page) doesn't want to be embedded in your page. You cannot force it to let you do that.
The correct URL to embed is of the form:
https://www.youtube.com/embed/<video-id>
In your case
https://www.youtube.com/embed/oHg5SJYRHA0
When you copy a video link off YouTube: "https://www.youtube.com/watch?v=Fva3fgKmu3o"
Replace 'watch' with 'embed'
Remove '?v='
Final Example: "https://www.youtube.com/embed/Fva3fgKmu3o"
Replace the keyword watch?v= with embed and change the live URL something like this:-
$url_string="https://www.youtube.com/watch?v=H1pTkatn6sI";
$url= str_replace('watch?v=','embed/', $url_string);
And then embed it in the iframe
<iframe id="player" type="text/html" width="640" height="390" src="{{ $url }}" frameborder="0"></iframe>
Someone has mentioned the url should embed instead watch.
If someone looking for Javascript answer, we can fix this dynamically by using string.replace()
for example
const updateYoutubeUrl = (youtube_url = 'www.youtube.com/watch?v=H1pTkatn6sI') => {
youtube_url.replace('watch?v=', 'embed/')
return youtube_url
}
please refer #dhahn answer
TL;DR: You may need to delete your cookies.
If it still doesn't work with either /v or /embed, the issue may be on your client, because of malformatted cookies. You can also see this error because of a 400 HTTP ERROR on most or every YouTube pages.
To fix this issue you'll have to delete YouTube cookies:
In Chrome, enter chrome://settings/siteData in the address bar, and enter youtube in the Search cookies box.
Next, you will see two groups of cookies for youtube, you could remove all, OR if you click the little arrow, you will be able to see the individual cookie names, and could just delete specific ones like all the gsScrollPos-####.
Sources of this answer and more details can be found on this Reddit thread.
Check the official doc at Embed a video or playlist from support.google.com/youtube
<iframe width="560" height="315"
src="https://www.youtube.com/embed/videoseries?list=PLx0sYbCqOb8TBPRdmBHs5Iftvv9TPboYG"
frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
Check more tips, tricks about youtube
Add this to your HTML code
don't copy the exact video link but right click and copy embed code and paste in src" "
<div class="example">
src="<iframe width="853" height="480" src="https://www.youtube.com/embed/jH0Q8NOsIR8" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>" </iframe>
</div>
To get id from youtube link this is helped me for nuxtjs
<iframe
:src="`https://www.youtube.com/embed/${getIdFromURL(group.videoEmbedLink)}?rel=0`"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
loading="lazy"
/>
...
methods: {
getIdFromURL(url) {
const youtubeRegexp = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig
let id = url.replace(youtubeRegexp, '$1')
if (id.includes(';')) {
const pieces = id.split(';')
if (pieces[1].includes('%')) {
const uriComponent = decodeURIComponent(pieces[1])
id = `http://youtube.com${uriComponent}`.replace(youtubeRegexp, '$1')
} else {
id = pieces[0]
}
} else if (id.includes('#')) {
id = id.split('#')[0]
}
return id
}
}
You need to copy the embed url generate from the Share section, not the ordinary url.
Press the Share button:
Press the embed button:
Use the url inside the iframe (or use the entire iframe):
Source: https://support.google.com/youtube/answer/171780
just add embed instead of watch
example:-https://youtube.com/embed/OGGuw2dLBjk

Categories