Onload iframe in Javascript wont work - javascript

<body style="margin:0px;padding:0px;overflow:hidden" onload="img.src='http://sjabbo.net/logo.png?'+(+new Date())">
<img id="img"
onload="iframe.src='http://sjabbo.net'"
onerror="iframe.src='offline.html'"
width="0px" height="0px">
<iframe width="100%" height="1000px"></iframe>
</body>
So, if the local user has an internet connection, then the iframe should change to "http://sjabbo.net" but if not, then "offline.html"
but it does not seem to work.

How about this:
<body style="margin:0px;padding:0px;overflow:hidden">
<img id="img" src="http://sjabbo.net/logo.png"
onload="document.getElementById('iframe').src='http://sjabbo.net'"/>
<iframe src="offline.html" id="iframe" width="100%" height="1000px"></iframe>
</body>
You could introduce "testing" page like this:
<body style="margin:0px;padding:0px;overflow:hidden">
<img id="img" src="http://sjabbo.net/logo.png"
onload="document.getElementById('iframe').src='http://sjabbo.net'"
onerror="document.getElementById('iframe').src='offline.html'"/>
<iframe src="testing.html" id="iframe" width="100%" height="1000px"></iframe>
</body>

First, you can't just use "img", because, to JavaScript, it's not defined anywhere globally. If you want to access the image by its ID, you need to do the following. Also, I'm guessing you want to have a timestamp instead of the long date. Put something like this in your onload:
document.getElementById('img').src = 'http://sjabbo.net/logo.png?' + (new Date()).getTime()
Do the same with your iframe (you'll have to assign it an ID first).

I don't think you've understood how web works.
You don't need to add an onload to every element that has a child. Each element is created one after another. So for now remove all your onloads.
You seem to want to wait to know if your image gets loaded correctly or not. Depending on this you want to activate your iframe.
You'll want to create a javascript tag ( or for good practice, create a js file ).
var img = document.getElementById('img'),
iframe = document.getElementById('iframe'); //add iframe as an id to your iframe
img.onload = function(){
//this is called when the image is finished loading.
iframe.src = 'http://sjabbo.net';
};
img.onerror = function(){
//this is called when the image wasn't able to load properly
iframe.src = 'offline.html'; //To be honest this doesn't make much sense
//You should instead just hide the iframe and the image
iframe.style.visibility = 'none';
img.style.visibility = 'none';
};
img.src = 'http://sjabbo.net/logo.png?' + (new Date()).getTime();
For future programming please try to seperate your js and css from your html. It is not good practice what you are currently doing.

Related

How to get iframe's refreshed src after interacting

I have an iframe tag that is linked with a Grafana graph, which supports interaction (zoom in/zoom out on x axis by clicking/double clicking on the iframe).
When I open the url of the iframe's src on a new tab I can interact with the graph and see that my browser's url params keeps refreshing with new from/to values (which indicates the range of the graph's x axis). Unfortunately when it is on an iframe I don't see any changes on the 'src' attribute, on any situation. I need the url parameters changes to apply on other graphs being displayed (sync them all).
How can I solve this situation?
My iframe on Angular's component.html:
<iframe [src]="url_grafana_primary" width="100%" height="300" frameborder="0"></iframe>
Iframe after being rendered:
<iframe _ngcontent-c8="" frameborder="0" height="300" width="100%" src="http://146.250.180.213/grafana/dashboard-solo/script/script_graph.js?scenario_id=rrc_succ_rate&cell_id=ESICAS23B_ESICAS23&refresh=5s&orgId=1&panelId=4&from=1555045266010&to=1555168469864&var-cell_id=ESICAS23B_ESICAS23&var-scenario_id=ESICAS23B_ESICAS23"></iframe>
Some screenshots:
Before changes: https://i.imgur.com/6M5JoHX.png
After changes: https://i.imgur.com/MN0KIha.png
You can see that src keep the same value on both situations.
The attribute of src is not changing, but the location object should behaves the same as it behaves when grafana is outside of the iframe.
You have 2 options,
if the frame of grafana & its parent are served from the same origin, you can access the location object with iframe.contentWindow.location.href.
if they are with different origins, you need to communicate between the frame and its parent, you can use postMessage for that.
check this example: https://robertnyman.com/html5/postMessage/postMessage.html
You can detect the onload event, but to get the URL, you will have to store a cookie or localStorage.
var firstTimeLoad = true; // Because the function will call on the initial page
function iframeLoad(iframe) {
if (firstTimeLoad) {
firstTimeLoad = false;
return;
}
alert("New page load");
}
<iframe width="400" height="244" src="https://wooden-utensil.github.io/linkingSite1/" onload="iframeLoad(this)" frameBorder="0"></iframe> <!-- linkingSite1 contains a link (a href) that links to linkingSite2, and vice versa -->
You just need to set the src of the iframe to the same old src. You may need to add a query string variable with random number like timestamp to avoid caching issues.
function refresh(){
var iframe = document.getElementById('myframe');
iframe.src = iframe.src;
}
iframe{
width:100%;
height:300px;
}
<p>
<button onclick="refresh()">Refresh</button>
</p>
<iframe id="myframe" src="https://www.chartjs.org/samples/latest/charts/line/basic.html" frameborder="0"></iframe>
In case when you are not the owner of the content in an iframe, you can't do much. The best you can do is to have a loop (setInterval), that will check the value against the last value you have seen.
<iframe #graph></iframe>
#ViewChild('graph', { static: true }) graph!: ElementRef<HTMLIFrameElement>;
private srcWatcher = new Observable(observer => {
const interval = setInterval(() => {
observer.next(this.graph && this.graph.nativeElement && this.graph.nativeElement.src);
}, 10);
return () => clearInterval(interval);
}).pipe(
distinctUntilChanged(),
);
having observable as this one, you can now react to any changes on it.
NOTE: I would also suggest that the observable should run outside of zoneJS if the interval timeout should be low. Otherwise Angular would run global change detection on every interval. By global I mean, that it would check the whole app any all of the subtrees, that uses the default change detection strategy.

Need to disable Javascript within an iFrame

I'm building a portfolio site; it's a one pager with a lightbox functionality. So, basically I am showing HTML5 ads I have built, which I am embedding in an iFrame. These ads have audio, so when I close out of the lightbox the audio continues to play. Now I have tried different methods but have been unsuccessful. I have tested one method which worked, where I removed the src of the iFrame (ONE iFrame which I assigned an ID). Like so:
**HTML:**
<iframe id="test" class="iframe-src" src="media/rogue-nation/300x250-progressive-post/index.html" width="300" height="250" style="border:none"></iframe>
**JavaScript:**
var test;
var lightbox;
test = document.getElementById('test');
lightbox = document.getElementById('lightbox');
lightbox.addEventListener("click", closeLightbox, false);
function closeLightbox() {
...
test.src = "none";
}
So...my questions are:
What is the "best" way to apply this method to each iFrame depending on which one was interacted with (tried, getElementsByClassName but was unsuccessful)
Is there a way to disable the scripts within an iFrame so I don't have to use this method, as I am not so crazy about it
Also, please don't post jQuery solutions or advise me to use jQuery, as it will not be helpful because I am writing plain JavaScript
Thanks in advance!
If your iframe content lives on the same domain it is easy. You could do something like this when your lightbox closes:
function closeLightbox() {
// get the iframe which is playing audio
var iframe = document.getElementById('iframe');
// make sure you can reference the audio element on the iframe
// e.g. with an id.
var sound = iframe.contentWindow.document.getElementById('sound');
sound.pause();
sound.currentTime = 0;
// then close the lightbox with some other code
// ...
}
JSBin Demo

how to remove delay in image loading in html?

I create a web page and put an img tag on this page. the img.src is the url of the image from the network IP camera. It works but the stream I get have delays. I understand this delay is because I load the image and loading image takes some time. my question is how can I minize these delay. I do the following;
<script language="Javascript">
x = document.getElementById("stream");
intervalID = setInterval(LoadImage, 0);
function LoadImage()
{
x = document.getElementById("stream");
x.src = "http://IP:PORT/jpg/image.jpg";
}
</script>
<img id="stream"
width="640" height="480"
alt="Press reload if no video displays"
border="0" style="cursor:crosshair; border:medium; border:thick" />
<button type="button" id="btnStartLive" onclick="onStartLiveBtnClick()">Start Live</button>
I've just found your question in the unanswered section and decided to give it a go. The following script creates an internal <img> tag (with new Image()), assigns the necessary attributes, then sets an onload "event handler" attribute, which checks when the image loaded. When that function is called, the #stream is replaced by the new internal image tag.
In case the #stream is not directly inside the body tag (i.e. inside another element like a <div>), edit streamParentElement to point to the image's parent element.
I added a ?nocache query parameter to the string, because while I was testing the code, I found out that the image tag was changing but the visible image stayed the same. I also added a loadDelay, because the images on my client were loading too fast, and it got to the point where it crashed my browser. I advise you to not lower that value below 50. Live demonstration of this code here
<script language="Javascript">
var streamParentElement = document.body, loadDelay = 200;
setTimeout(MakeImage,1);
function MakeImage(){
var img = new Image();
img.src = "http://IP:PORT/jpg/image.jpg?nocahce="+new Date().getTime()+Math.random();
img.width = 640;
img.height = 480;
img.style.border = 0;
img.style.cursor = 'crosshair';
img.id = 'stream';
img.onload = function(){
var stream = document.getElementById("stream");
streamParentElement.insertBefore(img,stream);
stream.outerHTML = '';
setTimeout(MakeImage, loadDelay);
};
}
</script>
<img id="stream" alt="Press reload if no video displays" />
create your html page. eg:
<html>
<head>
<title>
Some Page
</title>
</link rel="stylesheet" href="path to your css file"/>
<script type="text/javascript" src="path to you javasctipt file"></script>
</head>
<body>
<h1 onClick="javascript:someFunction()">
Click here
</h1>
</body>
</html>
you can then create many other "someFunction" functions. They all just reference the AJAX function.this is just to make typing a little less...
The easiest ajax way:
var path;
var div;
var xmlhttp = new XMLHttpRequest();
function someFunction()
{
path = "path to another html file";
div = "the name of the div tag's content you want to change eg. content";
AJAX(path, div);
}
function AJAX(path, div)
{
xmlhttp.open("GET", path, false);
xmlhttp.send();
if (xmlhttp.readyState == 4)
{
document.getElementById(div).innerHTML = xmlhttp.responseText;
}
}
now just include the image in the html file.
ajax allows you to change just the content of the div you gave it, without reloading the whole page.
I would try putting your images into photoshop and making the resolution 72 or less. Also if you save the images as a GIFs they should be much smaller.
maybe handle the image loading in an outside script that runs faster than a web page refreshes, then embed it? like a "videoloader.js" so that it can load separately and not have to wait on the html page to load.
<script src="videoloader.js"></script>
you could also convert the images shown on the fly into lesser quality jpgs using javascript
see if this helps:
Load lower quality image if higher one inst available

Can't access canvas element in iframe

I got a iframe and I want to select a canvas element in this iframe. But it doesn't work. I'm using the following code.
This is my iframe
<body>
<div id="canvasdiv" width="300" height="300"></div>
</body>
This is my parent page
<iframe name="iframe" id="iframe" frameborder="0" width="325" height="325" src="..."></iframe>
With javascript I add a canvas with some properties. For example the id.
canvas.node.id = "canvas";
In my parent page I got the following javascript.
var iframe = document.getElementById("iframe");
alert(iframe);
var iframe_canvas = iframe.contentDocument || iframe.contentWindow.document;
alert(iframe_canvas);
var canvas = iframe_canvas.getElementById("canvas");
alert(canvas);
Result:
iframe = iframe element
iframe_canvas = html element
canvas = null
Does somebody know why I can't access the canvas element? =(
I'm sorry, but I solved the problem. Thanks for all the replies. =)
To test the getElementById function I called it by $(document).ready. But at this time the iframe wasn't rendered by the browser. That's why I could access the iframe it self but not the elements of the iframe. Now I assigned the function to a button and it works.
According to your HTML, this line of code:
var canvas = iframe_canvas.getElementById("canvas");
should be this to target the proper id value in your div:
var canvas = iframe_canvas.getElementById("canvasdiv");
You're omitting the code that adds the <canvas> element itself. Are you sure its id is canvas?
If you are, then you might be running into same-origin policy problems regarding accessing contents of iframes.
your code is fine expect for one part.
replace
getElementById("canvas")
with
getElementById("canvasdiv");

How to pause a YouTube player when hiding the iframe?

I have a hidden div containing a YouTube video in an <iframe>. When the user clicks on a link, this div becomes visible, the user should then be able to play the video.
When the user closes the panel, the video should stop playback. How can I achieve this?
Code:
<!-- link to open popupVid -->
<p>Click here to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>
<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">
<iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40" frameborder="0" allowfullscreen></iframe>
<br /><br />
<a href="javascript:;" onClick="document.getElementById('popupVid').style.display='none';">
close
</a>
</div><!--end of popupVid -->
The easiest way to implement this behaviour is by calling the pauseVideo and playVideo methods, when necessary. Inspired by the result of my previous answer, I have written a pluginless function to achieve the desired behaviour.
The only adjustments:
I have added a function, toggleVideo
I have added ?enablejsapi=1 to YouTube's URL, to enable the feature
Demo: http://jsfiddle.net/ZcMkt/
Code:
<script>
function toggleVideo(state) {
// if state == 'hide', hide. Else: show video
var div = document.getElementById("popupVid");
var iframe = div.getElementsByTagName("iframe")[0].contentWindow;
div.style.display = state == 'hide' ? 'none' : '';
func = state == 'hide' ? 'pauseVideo' : 'playVideo';
iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
}
</script>
<p>Click here to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>
<!-- popup and contents -->
<div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">
<iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40?enablejsapi=1" frameborder="0" allowfullscreen></iframe>
<br /><br />
close
Here's a jQuery take on RobW's answer for use hiding /pausing an iframe in a modal window:
function toggleVideo(state) {
if(state == 'hide'){
$('#video-div').modal('hide');
document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
else {
$('#video-div').modal('show');
document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
}
}
The html elements referred to are the modal div itself (#video-div) calling the show / hide methods, and the iframe (#video-iframe) which has the video url as is src="" and has the suffix enablejsapi=1? which enables programmatic control of the player (ex. .
For more on the html see RobW's answer.
Here is a simple jQuery snippet to pause all videos on the page based off of RobW's and DrewT's answers:
jQuery("iframe").each(function() {
jQuery(this)[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*')
});
Hey an easy way is to simply set the src of the video to nothing, so that the video will desapear while it's hidden an then set the src back to the video you want when you click on the link that opens the video.. to do that simply set an id to the youtube iframe and call the src function using that id like this:
<script type="text/javascript">
function deleteVideo()
{
document.getElementById('VideoPlayer').src='';
}
function LoadVideo()
{
document.getElementById('VideoPlayer').src='http://www.youtube.com/embed/WHAT,EVER,YOUTUBE,VIDEO,YOU,WHANT';
}
</script>
<body>
<p onclick="LoadVideo()">LOAD VIDEO</P>
<p onclick="deleteVideo()">CLOSE</P>
<iframe id="VideoPlayer" width="853" height="480" src="http://www.youtube.com/WHAT,EVER,YOUTUBE,VIDEO,YOU,HAVE" frameborder="0" allowfullscreen></iframe>
</boby>
Since you need to set ?enablejsapi=true in the src of the iframe before you can use the playVideo / pauseVideo commands mentioned in other answers, it might be useful to add this programmatically via Javascript (especially if, eg. you want this behaviour to apply to videos embedded by other users who have just cut and paste a YouTube embed code). In that case, something like this might be useful:
function initVideos() {
// Find all video iframes on the page:
var iframes = $(".video").find("iframe");
// For each of them:
for (var i = 0; i < iframes.length; i++) {
// If "enablejsapi" is not set on the iframe's src, set it:
if (iframes[i].src.indexOf("enablejsapi") === -1) {
// ...check whether there is already a query string or not:
// (ie. whether to prefix "enablejsapi" with a "?" or an "&")
var prefix = (iframes[i].src.indexOf("?") === -1) ? "?" : "&";
iframes[i].src += prefix + "enablejsapi=true";
}
}
}
...if you call this on document.ready then all iframes in a div with a class of "video" will have enablejsapi=true added to their source, which allows the playVideo / pauseVideo commands to work on them.
(nb. this example uses jQuery for that one line that sets var iframes, but the general approach should work just as well with pure Javascript if you're not using jQuery).
I wanted to share a solution I came up with using jQuery that works if you have multiple YouTube videos embedded on a single page. In my case, I have defined a modal popup for each video as follows:
<div id="videoModalXX">
...
<button onclick="stopVideo(videoID);" type="button" class="close"></button>
...
<iframe width="90%" height="400" src="//www.youtube-nocookie.com/embed/video_id?rel=0&enablejsapi=1&version=3" frameborder="0" allowfullscreen></iframe>
...
</div>
In this case, videoModalXX represents a unique id for the video. Then, the following function stops the video:
function stopVideo(id)
{
$("#videoModal" + id + " iframe")[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
}
I like this approach because it keeps the video paused where you left off in case you want to go back and continue watching later. It works well for me because it's looking for the iframe inside of the video modal with a specific id. No special YouTube element ID is required. Hopefully, someone will find this useful as well.
You can stop the video by calling the stopVideo() method on the YouTube player instance before hiding the div e.g.
player.stopVideo()
For more details see here: http://code.google.com/apis/youtube/js_api_reference.html#Playback_controls
RobW's way worked great for me. For people using jQuery here's a simplified version that I ended up using:
var iframe = $(video_player_div).find('iframe');
var src = $(iframe).attr('src');
$(iframe).attr('src', '').attr('src', src);
In this example "video_player" is a parent div containing the iframe.
just remove src of iframe
$('button.close').click(function(){
$('iframe').attr('src','');;
});
Rob W answer helped me figure out how to pause a video over iframe when a slider is hidden. Yet, I needed some modifications before I could get it to work. Here is snippet of my html:
<div class="flexslider" style="height: 330px;">
<ul class="slides">
<li class="post-64"><img src="http://localhost/.../Banner_image.jpg"></li>
<li class="post-65><img src="http://localhost/..../banner_image_2.jpg "></li>
<li class="post-67 ">
<div class="fluid-width-video-wrapper ">
<iframe frameborder="0 " allowfullscreen=" " src="//www.youtube.com/embed/video-ID?enablejsapi=1 " id="fitvid831673 "></iframe>
</div>
</li>
</ul>
</div>
Observe that this works on localhosts and also as Rob W mentioned "enablejsapi=1" was added to the end of the video URL.
Following is my JS file:
jQuery(document).ready(function($){
jQuery(".flexslider").click(function (e) {
setTimeout(checkiframe, 1000); //Checking the DOM if iframe is hidden. Timer is used to wait for 1 second before checking the DOM if its updated
});
});
function checkiframe(){
var iframe_flag =jQuery("iframe").is(":visible"); //Flagging if iFrame is Visible
console.log(iframe_flag);
var tooglePlay=0;
if (iframe_flag) { //If Visible then AutoPlaying the Video
tooglePlay=1;
setTimeout(toogleVideo, 1000); //Also using timeout here
}
if (!iframe_flag) {
tooglePlay =0;
setTimeout(toogleVideo('hide'), 1000);
}
}
function toogleVideo(state) {
var div = document.getElementsByTagName("iframe")[0].contentWindow;
func = state == 'hide' ? 'pauseVideo' : 'playVideo';
div.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
};
Also, as a simpler example, check this out on JSFiddle
This approach requires jQuery. First, select your iframe:
var yourIframe = $('iframe#yourId');
//yourId or something to select your iframe.
Now you select button play/pause of this iframe and click it
$('button.ytp-play-button.ytp-button', yourIframe).click();
I hope it will help you.
RobW's answers here and elsewhere were very helpful, but I found my needs to be much simpler. I've answered this elsewhere, but perhaps it will be useful here also.
I have a method where I form an HTML string to be loaded in a UIWebView:
NSString *urlString = [NSString stringWithFormat:#"https://www.youtube.com/embed/%#",videoID];
preparedHTML = [NSString stringWithFormat:#"<html><body style='background:none; text-align:center;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>var player; function onYouTubeIframeAPIReady(){player=new YT.Player('player')}</script><iframe id='player' class='youtube-player' type='text/html' width='%f' height='%f' src='%#?rel=0&showinfo=0&enablejsapi=1' style='text-align:center; border: 6px solid; border-radius:5px; background-color:transparent;' rel=nofollow allowfullscreen></iframe></body></html>", 628.0f, 352.0f, urlString];
You can ignore the styling stuff in the preparedHTML string. The important aspects are:
Using the API to create the "YT.player" object. At one point, I only had the video in the iFrame tag and that prevented me from referencing the "player" object later with JS.
I've seen a few examples on the web where the first script tag (the one with the iframe_api src tag) is omitted, but I definitely needed that to get this working.
Creating the "player" variable at the beginning of the API script. I have also seen some examples that have omitted that line.
Adding an id tag to the iFrame to be referenced in the API script. I almost forgot that part.
Adding "enablejsapi=1" to the end of the iFrame src tag. That hung me up for a while, as I initially had it as an attribute of the iFrame tag, which does not work/did not work for me.
When I need to pause the video, I just run this:
[webView stringByEvaluatingJavaScriptFromString:#"player.pauseVideo();"];
Hope that helps!
This is working fine to me with YT player
createPlayer(): void {
return new window['YT'].Player(this.youtube.playerId, {
height: this.youtube.playerHeight,
width: this.youtube.playerWidth,
playerVars: {
rel: 0,
showinfo: 0
}
});
}
this.youtube.player.pauseVideo();
A more concise, elegant, and secure answer: add “?enablejsapi=1” to the end of the video URL, then construct and stringify an ordinary object representing the pause command:
const YouTube_pause_video_command_JSON = JSON.stringify(Object.create(null, {
"event": {
"value": "command",
"enumerable": true
},
"func": {
"value": "pauseVideo",
"enumerable": true
}
}));
Use the Window.postMessage method to send the resulting JSON string to the embedded video document:
// |iframe_element| is defined elsewhere.
const video_URL = iframe_element.getAttributeNS(null, "src");
iframe_element.contentWindow.postMessage(YouTube_pause_video_command_JSON, video_URL);
Make sure you specify the video URL for the Window.postMessage method’s targetOrigin argument to ensure that your messages won’t be sent to any unintended recipient.

Categories