I want to monitor an unmount event on my NAS.
it has a seperate page to unmount all usb drives.
I've included it via iframe and want to keep the site loading until the image source has been changed to a specific source (a green bar, indicating that it has done unmounting).
The reason why I want to keep it loading is because im calling it via a jquery.get function from another site, and i want it to wait till the unmounting process is done.
Would be great if this is possible only in plain javascript, but if needed I can also include jquery.
Here is what I got so far:
<script type="text/javascript">
function check(){
if (!(document.getElementById("uiView_TestPic").src == "/css/default/images/finished_ok_green.gif")){
window.setTimeout(check(), 2000);
}else{
alert("Done!");
}}
window.onload(check());
</script></head>
<body>
<iframe seamless width="100%" frameborder="0" height="80%" src="http://fritz.box/usb/usb_diskcut.lua?usbdev=all"></iframe>
I am immediately receiving an error that the element "uiView_TestPic" does not exist, even when I add a timeout before running check.
The included iFrame site stops loading as soon as all images are loading and not when the whole process is done.
First off, both frames must be running on the same domain because browsers will prevent code in one frame from accessing anything in the other frame if they are different domains. If the two frames are not on the same domain, then the iframe will have to monitor itself and notify the other frame when it has finished using something like window.postMessage().
If they are on the same domain, this is slightly complicated. You have to get the iframe element (that's in your main document). You have to wait for that to be ready (since it has to load it's own contents). Then, you have to get the document in the iframe. Then you can find the desired image in the iframe. Then you can observe it's contents. And, of course, you can only do any of this if the iframe is the same domain as your main page (because of security restrictions).
First, add an id to the iframe:
<iframe id="myFrame" seamless width="100%" frameborder="0" height="80%" src="http://fritz.box/usb/usb_diskcut.lua?usbdev=all"></iframe>
Then, you can use this:
// put this code in your document AFTER the iFrame tag
// or only run it after the DOM is loaded in your main document
function checkImageSrc(obj) {
if (obj.src.indexOf("/finished_ok_green.gif") !== -1) {
// found the green gif
// put whatever code you want here
} else {
// check repeatedly until we find the green image
setTimeout(function() {
checkImageSrc(obj);
}, 2000);
}
}
// get the iframe in my documnet
var iframe = document.getElementById("myFrame");
// get the window associated with that iframe
var iWindow = iframe.contentWindow;
// wait for the window to load before accessing the content
iWindow.addEventListener("load", function() {
// get the document from the window
var doc = iframe.contentDocument || iframe.contentWindow.document;
// find the target in the iframe content
var target = doc.getElementById("uiView_TestPic");
checkImageSrc(target);
});
FYI, there's more detail on waiting for an iframe to be ready here: How can I access the DOM elements within an iFrame
If you control the code in the iframe, then a much cleaner way to implement this would be to use window.postMessage() to post a message to the parent window when the code in the iframe finishes its operation. Then the parent window can just listen for that single message and it will know when the operation is done.
That could look something like this. Put this code in the iframe:
// put this code in your document AFTER the relevant image tag
// or only run it after the DOM is loaded in your iframe
// if you can hook into the actual event that knows the unmount
// is done, that would be even better than polling for the gif to change
function checkImageSrc(obj) {
if (obj.src.indexOf("/finished_ok_green.gif") !== -1) {
// found the green gif
// notify the parent
window.parent.postMessage("unmount complete", "*");
} else {
// check repeatedly until we find the green image
setTimeout(function() {
checkImageSrc(obj);
}, 2000);
}
}
// find the target in the iframe content
var target = document.getElementById("uiView_TestPic");
checkImageSrc(target);
Then, in your main window, you would listen for the posted message like this:
window.addEventListener("message", function(e) {
// make sure this is coming from where we expect (fill in the proper origin here)
if (e.origin !== "http://example.org:8080") return;
if (e.data === "unmount complete") {
// unmount is complete - put your code here
}
});
You can check whether the element is there in the dom or not and then have the check for the src. Something like this should work:
function check(){
if (document.getElementById("uiView_TestPic") && !(document.getElementById("uiView_TestPic").src == "/css/default/images/finished_ok_green.gif")){
window.setTimeout(check(), 2000);
}else{
alert("Done!");
}}
window.onload(check());
In this Fiddle you will see that src null error is not happening. However if you remove document.getElementById("uiView_TestPic") && you get your error
Related
I'm talking about an icon that is displayed on a tab during page loading.
Chrome:
Firefox (with TreeTab plugin):
You get the idea. I want to make it seem like the page is loading, when it's already loaded. Some event fires is javascript and then the tab looks like it's being loaded. Is there a way to do that?
One way I can think of is to replace a favicon with a spinner, but I'm not sure if it's possible to change on the fly and even if it is, it would be a hassle to make it cross-browser.
I don't think it is a good idea to do it, you'll make your users do a lot of useless requests, and this kills trees : /
IMO, it's better to do all you have in the page itself, and let the browser's UI do his own stuff.
But since I liked the challenge, here is one hacky way :
Loading an iframe will trigger this icon in both chrome and Firefox[1], so you could ,
append an iframe in the document,
set its src to some huge document,
onload of the iframe, set it again with a ? cache hack,
regularly check if the duration has elapsed so you can remove the iframe's src.
[1] It seems that Firefox does trigger the icon only if it was triggered when the document was still loading.
In code :
// how to use :
showTabLoader(25000);
// takes duration in ms as only parameter
function showTabLoader(duration) {
if (!duration) return;
var now = performance.now();
// To avoid flickering, you need some big document
// Please change this url in your script, wikimedia may not be happy with us.
var url = 'https://upload.wikimedia.org/wikipedia/commons/3/35/Viborg_Katedralskole_Symmetrical.jpg';
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
iframe.onload = function() {
if (performance.now() - now < +duration) {
this.src = url + '?' + Math.random();
}
};
var check = function(time) {
if (time - now > +duration) {
iframe.src = '';
iframe.parentNode.removeChild(iframe);
return;
}
requestAnimationFrame(check);
}
requestAnimationFrame(check);
iframe.src = url;
}
I recently thought of the same idea. A neat option is to use a dynamic favicon instead of hacking in hidden requests, which is a really bad idea in my opinion. I found this example. It's to much code to include here and doesn't work in iframes so no way of showing it directly on Stackoverflow. Instead i describe the idea behind.
https://www.cssscript.com/favicon-loading-indicator-favloader/
The idea is simple. Replace the favicon in an interval with the loading animation icons. A favicon cannot be GIF so you have to load each image step by step with JS. When you are done, simply replace it back with the original favicon.
For me this works at least in all chrome based browsers. Firefox throw some errors in this example, but i guess it can be fixed.
Alternitive:
There is no function that shows the actual loading process of the webpage. But you can do it manually, like you said!
The event below starts to run when the page is fully loaded, even after all the images are loaded:
$(window).on('load', function() {
// do stuff
});
So what you could do is set up your html like this:
<div class="preloader">
// your loader here, animations, video, gif, anything you want
</div>
<div class="main" style="display: none;">
// the page
</div>
and your jquery like this:
$(window).on('load', function() {
setTimeout(function() {
$('.preloader').css('display', 'none');
$('.main').css('opacity', '1');
}, 5000); // <-- 5seconds
});
And there you have your manual loading function! Works perfect.
Example website: ifly50
EDIT:
added code snippet
Code snippet:
$(window).on('load', function() {
setTimeout(function() {
$('.preloader').css('display', 'none');
$('.main').css('display', 'block');
}, 3000); // <-- 3 seconds
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="preloader">loading</div>
<div class="main" style="display: none;">main</div>
I need the same source i can find in the Elements window of DevTool console in my extension. I tried using the content script
var text = document.documentElement.innerHTML;
injected after catched the "complete" status from chrome.tabs.onUpdated.addListener, but i recived only the html code without the content dynamically created.
In particular i want my extension to find all "div" added dynamically.
Any help will be appreciated!
The complete event fires once the initial page content has been loaded. It has no relation to dynamically generated content, otherwise it would have to wait indefinitely, since more content may always be added later.
If you are interested in a specific element, you can use setTimeout to periodically poll for the element. Like so:
function getElement() {
return new Promise(function(res, rej) {
var interval = setInterval(function() {
var elm = document.getElementById('the-element-you-want');
if(elm){
clearInterval(interval);
res(elm);
}
}, 10);
});
}
Another option would be to use a MutationObserver to detect when the desired element(s) have been created.
In the console I have 180 failed to load resources, I need to get a list of these resources so that I can send a report to the webmaster with the images URLs. How can this be done?
You can easily track images that fail to load, as long as you set up an event listener before the image starts to load. Like this:
img.addEventListener('error', function() {
//report failed image
}, false);
If all of your images are loaded in <img> tags that are in the html, you can set up an error event for all of them in a script. Just make sure the script that sets this up is placed after the img tags, but do not run the setup in a page load event or DOMContentLoaded because you may have missed some error events, and it will be too late.
See this example:
http://jsbin.com/ekiram/2/edit
If you want, you can set up a MutationObserver event to watch for any new <img> elements added dynamically and set up an error event there. But it won't work in all browsers.
You can check whether an image has loaded by looking at the naturalWidth property. If it's 0, it hasn't loaded. But there's no way to know whether the image has actually failed to load or is just taking a really long time, like if there's a slow network connection. I suppose you could use this if you have another way to know if the page and all images are really done loading, like after a page load event or if you're willing to set a very long timeout.
If you can add a script to the page, you can bind a handler to the error event and track all failures:
$(function(){
var errorImages = [];
$('img').on('error', function(){
errorImages.push(this.src);
});
$(window).on('load', function(){
alert(errorImages);
});
});
Working example: http://jsbin.com/iboyik/3
If you want to get all failed images on a page that is already loaded, that is a little trickier. I was able to do that by reloading all images:
(function(){
var errorImages = [];
$('img')
.on('error', function(){
errorImages.push(this.src);
})
.prop('src', function(i, src){return src;});
// wait for all images to fail (bit of a hack)
setTimeout(function(){alert(errorImages);}, 1000);
})();
Working example: http://jsbin.com/iboyik/2
I need to execute a callback when an IFRAME has finished loading. I have no control over the content in the IFRAME, so I can't fire the callback from there.
This IFRAME is programmaticly created, and I need to pass its data as a variable in the callback, as well as destroy the iframe.
Any ideas?
EDIT:
Here is what I have now:
function xssRequest(url, callback)
{
var iFrameObj = document.createElement('IFRAME');
iFrameObj.src = url;
document.body.appendChild(iFrameObj);
$(iFrameObj).load(function()
{
document.body.removeChild(iFrameObj);
callback(iFrameObj.innerHTML);
});
}
This callsback before the iFrame has loaded, so the callback has no data returned.
First up, going by the function name xssRequest it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe.
On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine:
// possibly excessive use of jQuery - but I've got a live working example in production
$('#myUniqueID').load(function () {
if (typeof callback == 'function') {
callback($('body', this.contentWindow.document).html());
}
setTimeout(function () {$('#frameId').remove();}, 50);
});
I am using jQuery and surprisingly this seems to load as I just tested and loaded a heavy page and I didn't get the alert for a few seconds until I saw the iframe load:
$('#the_iframe').load(function(){
alert('loaded!');
});
So if you don't want to use jQuery take a look at their source code and see if this function behaves differently with iframe DOM elements, I will look at it myself later as I am interested and post here. Also I only tested in the latest chrome.
I have had to do this in cases where documents such as word docs and pdfs were being streamed to the iframe and found a solution that works pretty well. The key is handling the onreadystatechanged event on the iframe.
Lets say the name of your frame is "myIframe". First somewhere in your code startup (I do it inline any where after the iframe) add something like this to register the event handler:
document.getElementById('myIframe').onreadystatechange = MyIframeReadyStateChanged;
I was not able to use an onreadystatechage attribute on the iframe, I can't remember why, but the app had to work in IE 7 and Safari 3, so that may of been a factor.
Here is an example of a how to get the complete state:
function MyIframeReadyStateChanged()
{
if(document.getElementById('myIframe').readyState == 'complete')
{
// Do your complete stuff here.
}
}
The innerHTML of your iframe is blank because your iframe tag doesn't surround any content in the parent document. In order to get the content from the page referred to by the iframe's src attribute, you need to access the iframe's contentDocument property. An exception will be thrown if the src is from a different domain though. This is a security feature that prevents you from executing arbitrary JavaScript on someone else's page, which would create a cross-site scripting vulnerability. Here is some example code the illustrates what I'm talking about:
<script src="http://prototypejs.org/assets/2009/8/31/prototype.js" type="text/javascript"></script>
<h1>Parent</h1>
<script type="text/javascript">
function on_load(iframe) {
try {
// Displays the first 50 chars in the innerHTML of the
// body of the page that the iframe is showing.
// EDIT 2012-04-17: for wider support, fallback to contentWindow.document
var doc = iframe.contentDocument || iframe.contentWindow.document;
alert(doc.body.innerHTML.substring(0, 50));
} catch (e) {
// This can happen if the src of the iframe is
// on another domain
alert('exception: ' + e);
}
}
</script>
<iframe id="child" src="iframe_content.html" onload="on_load(this)"></iframe>
To further the example, try using this as the content of the iframe:
<h1>Child</h1>
Google
<p>Use the preceeding link to change the src of the iframe
to see what happens when the src domain is different from
that of the parent page</p>
I wanted to hide the waiting spinner div when the i frame content is fully loaded on IE, i tried literally every solution mentioned in Stackoverflow.Com, but with nothing worked as i wanted.
Then i had an idea, that when the i frame content is fully loaded, the $(Window ) load event might be fired. And that exactly what happened. So, i wrote this small script, and worked like magic:
$(window).load(function () {
//alert("Done window ready ");
var lblWait = document.getElementById("lblWait");
if (lblWait != null ) {
lblWait.style.visibility = "false";
document.getElementById("divWait").style.display = "none";
}
});
Hope this helps.
This function will run your callback function immediately if the iFrame is already loaded or wait until the iFrame is completely loaded.
This also addresses the following issues:
Chrome initializes every iFrame with an about:blank page which will have readyState == "complete". Later, it will replace `about:blank with the actual iframe src value. So, the initial value of readyState will not represent the readyState of your actual iFrame. Therefore, besides checking for readyState value, this function also addresses the about:blank issue.
DOMContentLoaded event doesn't work with iFrame. So it uses the load event for running the callback function if iFrame isn't already loaded. The load event is equivalent to readyState == "complete" which has been used to check whether iFrame is already loaded. So, in any scenario, the callback function will run after iFrame is fully loaded.
iFrame src can have redirects and therefore load a page different from the original src url. This function will also work in that scenario.
Pass in your callback function that you want to run when the iFrame finishes loading and the <iframe> element to this function:
function iframeReady(callback, iframeElement) {
const iframeWindow = iframeElement.contentWindow;
if ((iframeElement.src == "about:blank" || (iframeElement.src != "about:blank" && iframeWindow.location.href != "about:blank")) && iframeWindow.document.readyState == "complete") {
callback();
} else {
iframeWindow.addEventListener("load", callback);
}
}
I had a similar problem as you. What I did is that I use something called jQuery. What you then do in the javascript code is this:
$(function(){ //this is regular jQuery code. It waits for the dom to load fully the first time you open the page.
$("#myIframeId").load(function(){
callback($("#myIframeId").html());
$("#myIframeId").remove();
});
});
It seems as you delete you iFrame before you grab the html from it. Now, I do see a problem with that :p
Hope this helps :).
I have a similar code in my projects that works fine.
Adapting my code to your function, a solution could be the following:
function xssRequest(url, callback)
{
var iFrameObj = document.createElement('IFRAME');
iFrameObj.id = 'myUniqueID';
document.body.appendChild(iFrameObj);
iFrameObj.src = url;
$(iFrameObj).load(function()
{
callback(window['myUniqueID'].document.body.innerHTML);
document.body.removeChild(iFrameObj);
});
}
Maybe you have an empty innerHTML because (one or both causes):
1. you should use it against the body element
2. you have removed the iframe from the your page DOM
I think the load event is right.
What is not right is the way you use to retreive the content from iframe content dom.
What you need is the html of the page loaded in the iframe not the html of the iframe object.
What you have to do is to access the content document with iFrameObj.contentDocument.
This returns the dom of the page loaded inside the iframe, if it is on the same domain of the current page.
I would retreive the content before removing the iframe.
I've tested in firefox and opera.
Then i think you can retreive your data with $(childDom).html() or $(childDom).find('some selector') ...
I've had exactly the same problem in the past and the only way I found to fix it was to add the callback into the iframe page. Of course that only works when you have control over the iframe content.
Using onload attrbute will solve your problem.
Here is an example.
function a() {
alert("Your iframe has been loaded");
}
<iframe src="https://stackoverflow.com" onload="a()"></iframe>
Is this what you want?
Click here for more information.
I need to execute a callback when an IFRAME has finished loading. I have no control over the content in the IFRAME, so I can't fire the callback from there.
This IFRAME is programmaticly created, and I need to pass its data as a variable in the callback, as well as destroy the iframe.
Any ideas?
EDIT:
Here is what I have now:
function xssRequest(url, callback)
{
var iFrameObj = document.createElement('IFRAME');
iFrameObj.src = url;
document.body.appendChild(iFrameObj);
$(iFrameObj).load(function()
{
document.body.removeChild(iFrameObj);
callback(iFrameObj.innerHTML);
});
}
This callsback before the iFrame has loaded, so the callback has no data returned.
First up, going by the function name xssRequest it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe.
On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine:
// possibly excessive use of jQuery - but I've got a live working example in production
$('#myUniqueID').load(function () {
if (typeof callback == 'function') {
callback($('body', this.contentWindow.document).html());
}
setTimeout(function () {$('#frameId').remove();}, 50);
});
I am using jQuery and surprisingly this seems to load as I just tested and loaded a heavy page and I didn't get the alert for a few seconds until I saw the iframe load:
$('#the_iframe').load(function(){
alert('loaded!');
});
So if you don't want to use jQuery take a look at their source code and see if this function behaves differently with iframe DOM elements, I will look at it myself later as I am interested and post here. Also I only tested in the latest chrome.
I have had to do this in cases where documents such as word docs and pdfs were being streamed to the iframe and found a solution that works pretty well. The key is handling the onreadystatechanged event on the iframe.
Lets say the name of your frame is "myIframe". First somewhere in your code startup (I do it inline any where after the iframe) add something like this to register the event handler:
document.getElementById('myIframe').onreadystatechange = MyIframeReadyStateChanged;
I was not able to use an onreadystatechage attribute on the iframe, I can't remember why, but the app had to work in IE 7 and Safari 3, so that may of been a factor.
Here is an example of a how to get the complete state:
function MyIframeReadyStateChanged()
{
if(document.getElementById('myIframe').readyState == 'complete')
{
// Do your complete stuff here.
}
}
The innerHTML of your iframe is blank because your iframe tag doesn't surround any content in the parent document. In order to get the content from the page referred to by the iframe's src attribute, you need to access the iframe's contentDocument property. An exception will be thrown if the src is from a different domain though. This is a security feature that prevents you from executing arbitrary JavaScript on someone else's page, which would create a cross-site scripting vulnerability. Here is some example code the illustrates what I'm talking about:
<script src="http://prototypejs.org/assets/2009/8/31/prototype.js" type="text/javascript"></script>
<h1>Parent</h1>
<script type="text/javascript">
function on_load(iframe) {
try {
// Displays the first 50 chars in the innerHTML of the
// body of the page that the iframe is showing.
// EDIT 2012-04-17: for wider support, fallback to contentWindow.document
var doc = iframe.contentDocument || iframe.contentWindow.document;
alert(doc.body.innerHTML.substring(0, 50));
} catch (e) {
// This can happen if the src of the iframe is
// on another domain
alert('exception: ' + e);
}
}
</script>
<iframe id="child" src="iframe_content.html" onload="on_load(this)"></iframe>
To further the example, try using this as the content of the iframe:
<h1>Child</h1>
Google
<p>Use the preceeding link to change the src of the iframe
to see what happens when the src domain is different from
that of the parent page</p>
I wanted to hide the waiting spinner div when the i frame content is fully loaded on IE, i tried literally every solution mentioned in Stackoverflow.Com, but with nothing worked as i wanted.
Then i had an idea, that when the i frame content is fully loaded, the $(Window ) load event might be fired. And that exactly what happened. So, i wrote this small script, and worked like magic:
$(window).load(function () {
//alert("Done window ready ");
var lblWait = document.getElementById("lblWait");
if (lblWait != null ) {
lblWait.style.visibility = "false";
document.getElementById("divWait").style.display = "none";
}
});
Hope this helps.
This function will run your callback function immediately if the iFrame is already loaded or wait until the iFrame is completely loaded.
This also addresses the following issues:
Chrome initializes every iFrame with an about:blank page which will have readyState == "complete". Later, it will replace `about:blank with the actual iframe src value. So, the initial value of readyState will not represent the readyState of your actual iFrame. Therefore, besides checking for readyState value, this function also addresses the about:blank issue.
DOMContentLoaded event doesn't work with iFrame. So it uses the load event for running the callback function if iFrame isn't already loaded. The load event is equivalent to readyState == "complete" which has been used to check whether iFrame is already loaded. So, in any scenario, the callback function will run after iFrame is fully loaded.
iFrame src can have redirects and therefore load a page different from the original src url. This function will also work in that scenario.
Pass in your callback function that you want to run when the iFrame finishes loading and the <iframe> element to this function:
function iframeReady(callback, iframeElement) {
const iframeWindow = iframeElement.contentWindow;
if ((iframeElement.src == "about:blank" || (iframeElement.src != "about:blank" && iframeWindow.location.href != "about:blank")) && iframeWindow.document.readyState == "complete") {
callback();
} else {
iframeWindow.addEventListener("load", callback);
}
}
I had a similar problem as you. What I did is that I use something called jQuery. What you then do in the javascript code is this:
$(function(){ //this is regular jQuery code. It waits for the dom to load fully the first time you open the page.
$("#myIframeId").load(function(){
callback($("#myIframeId").html());
$("#myIframeId").remove();
});
});
It seems as you delete you iFrame before you grab the html from it. Now, I do see a problem with that :p
Hope this helps :).
I have a similar code in my projects that works fine.
Adapting my code to your function, a solution could be the following:
function xssRequest(url, callback)
{
var iFrameObj = document.createElement('IFRAME');
iFrameObj.id = 'myUniqueID';
document.body.appendChild(iFrameObj);
iFrameObj.src = url;
$(iFrameObj).load(function()
{
callback(window['myUniqueID'].document.body.innerHTML);
document.body.removeChild(iFrameObj);
});
}
Maybe you have an empty innerHTML because (one or both causes):
1. you should use it against the body element
2. you have removed the iframe from the your page DOM
I think the load event is right.
What is not right is the way you use to retreive the content from iframe content dom.
What you need is the html of the page loaded in the iframe not the html of the iframe object.
What you have to do is to access the content document with iFrameObj.contentDocument.
This returns the dom of the page loaded inside the iframe, if it is on the same domain of the current page.
I would retreive the content before removing the iframe.
I've tested in firefox and opera.
Then i think you can retreive your data with $(childDom).html() or $(childDom).find('some selector') ...
I've had exactly the same problem in the past and the only way I found to fix it was to add the callback into the iframe page. Of course that only works when you have control over the iframe content.
Using onload attrbute will solve your problem.
Here is an example.
function a() {
alert("Your iframe has been loaded");
}
<iframe src="https://stackoverflow.com" onload="a()"></iframe>
Is this what you want?
Click here for more information.