Get response status code of cross domain iframe? - javascript

I have a iframe on my website which points to 3rd party page (i.e. Not on my domain and I don't have any control on their server).
I want to be able to just check if their website is being loaded properly inside the iframe or not. There can be cases where -
it gets blocked by some firewall
their service is down or something.
So that I can show a proper error message inside the iframe in that case. I was hoping that I can find out the iframe's response status code somehow. How can I achieve something like this?

Try this.
<script>
function checkIframeLoaded() {
// Get a handle to the iframe element
iframe = document.getElementById('your_iframe');
var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
// Check if loading is complete
if ( iframeDoc.readyState == 'complete' ) {
iframe.contentWindow.onload = function(){
alert("I am loaded");
};
// The loading is complete, call the function we want executed once the iframe is loaded
afterLoading();
return;
}
// If we are here, it is not loaded. Set things up so we check the status again in 100 milliseconds
window.setTimeout('checkIframeLoaded();', 100);
}
function afterLoading(){
alert("I am here");
}
</script>
<body onload="checkIframeLoaded();">

Related

How to get location.href from external window object?

This is my example code to print esternal window location after 5sec:
<SCRIPT TYPE="text/javascript">
function Loaded()
{
var newPage=window.open('http://externaldomainurl','myWindow');
newPage.focus();
setTimeout(function(){urlCheck(newPage)}, 5000);
}
function urlCheck(newPage)
{
alert(newPage.location)
newPage.close();
}
</SCRIPT>
TEST
But nothing appear on alert.
Tnks
Access to data on other origins is restricted for security reasons. You can't monitor where a user has browsed to after they leave your site.
You can use postMessage and addEventListener('message', listener) to pass messages between the two origins if you are able to edit the code for both of them.

Get tag content from a lot of urls

I have a situation here: in CSV file have a lot of URL's - more than 3000 in that format:
www.site1.com/product1
www.site1.com/product2
www.site1.com/product3
....
www.site1.com/product3001
from all page i must read specific tag - <div id="cat">category1</div>
I've try to solve this on server side, but that require a lot of server resources and cause Time Out err. Then i wonder - is there a way that i can do that with some kind of java script or jQuery? In that case, browser will take the traffic. Of course - this will take some time... but better than get TimeOut from server.
I think this is possible with some ajax calls and then looking for that particular element (id="cat"). But i guess the sites must be on the same server/domain for this to work.
Another method i would try is to create an iframe and on a loop load the page and wait for the onload method of the iframe, after it's loaded i would look for that particular element and get its content... This is somewhat more likely to work but it will be painfully slow...
var urls = [url1, url2, url3...]; //get all the urls from your file
var urlsLength = urls.length; //get the number of urls to loop for
var iFrame = document.createElement("iframe"); //create an iframe
var iframeContainer = document.getElementById("iframeContainer"); //iframeContainer must exists on your page, you can even hide it with display="none"
var iFrameBody; //variable to hold the iframe body
iframeContainer.appendChild( iFrame ); //add the iframe to its container
for( var i = 0; i<urlsLength; ++i ){ //loop for all the urls
iFrame.src = urls[i]; //browse the designated url
iFrame.onload = function(){ //when it loads, then do your work
iFrameBody = iFrame.contentDocument || iFrame.contentWindow.document; //get the body of the iFrame
doSomething( iFrameBody.getElementById("ELEMENT ID TO LOOK FOR") ); //send the element to your functions
}
}
//this function will receive the element from inside the iframe, you can do whatever you need to
function doSomething(element){
var elementHTML = element.innerHTML;
console.log( element );
}
-EDIT-
This method is way too slow, as mentioned above in the comments, doing this server side is (IMHO) the best approach, but at least you have alternatives, i would stay away from AJAX requests to do something like this on massive urls ( 30+ ) and stick to iframes, but still believe that server side is the GO GO. Cheers.

Hide Image When Anchor HREF Source Is Not Present

I would like to poll an anchor's href source about once every 5 seconds, to see whether a file at that address is present. When it is present, display an image in the anchor. In other words, the link is basically not there unless the file is present.
I'm guessing I would have to poll using an http HEAD request to determine whether the file exists, then toggle the image appropriately. Once the file has been determined to exist, I can stop polling and leave the image visible.
Is there a better way to do this, and can anyone suggest some script that would handle this functionality?
If your server is configured to do so you can use:
http://api.jquery.com/jQuery.ajax/
To poll for the file's existence by using the statusCode map
function checkFile() {
$.ajax({
statusCode: {
404: function() {
//file does not yet exist
setTimeout(checkFile, 5000);
}
200: function() {
//file exists.
showImage();
}
}
});
}
You may want to capture a few more edge cases though, (for example, an error callback).
// note, this piece of code assumes to be using jQuery
var interval = setInterval(function(){
var _el=$('#hrefId');
var href = _el.attr('href');
if(href == null || typeof href == 'undefined' || href == '')
return;
ajax call to href(in case on ur server(!) )
// on success
_el.attr('href','TheLink');
$('img', _el).show(); // show image
}, 5);
You can also use a socket library so the server can push a notification when the image is ready. socket.io seems like a good options here.
Another way would be to listen for the error event on the image, then wait for x milliseconds before trying to load it again. This is quite easy to implement, because every time you define a src attribute, the browser will add new listeners.
It’s basically the same as your meta-description but you don’t need to use ajax. You will also be able to load images from other domains (ajax have a cross-site policy):
var img = new Image(),
src = '/path/to/image.jpg';
img.onload = function() {
console.log('loaded', img);
};
img.onerror = function() {
window.setTimeout(function() {
img.src = src;
},500);
};
img.src = src;​
Here is a proof of concept: http://jsfiddle.net/L2L3U/. The program will try to load a 404 image for three seconds, after that I change the src to a real image and it will display it.

Detect if the iframe content has loaded successfully

I have a widget that contains an iframe. The user can configure the url of this iframe, but if the url could not be loaded (it does not exists or the user does not have access to internet) then the iframe should failover to a default offline page.
The question is, how can I detect if the iframe could be loaded or not? I tried subscribing to the 'load' event, and, if this event is not fired after some time then I failover, but this only works in Firefox, since IE and Chrome fires the 'load' event when the "Page Not Found" is displayed.
I found the following link via Google: http://wordpressapi.com/2010/01/28/check-iframes-loaded-completely-browser/
Don't know if it solves the 'Page Not Found' issue.
<script type="javascript">
var iframe = document.createElement("iframe");
iframe.src = "http://www.your_iframe.com/";
if (navigator.userAgent.indexOf("MSIE") > -1 && !window.opera) {
iframe.onreadystatechange = function(){
if (iframe.readyState == "complete"){
alert("Iframe is now loaded.");
}
};
} else {
iframe.onload = function(){
alert("Iframe is now loaded.");
};
}
</script>
I haven't tried it myself, so I don't know if it works. Good luck!
Nowadays the browsers have a series of security limitations that keep you away from the content of an iframe (if it isn´t of your domain).
If you really need that functionality, you have to build a server page that have to work as a proxy, that receive the url as a parameter, test if it is a valid url, and does the redirect or display the error page.
If you control the content of the iframe, the iframe can send a message to the parent.
parent.postMessage('iframeIsDone', '*');
The parent callback listens for the message.
var attachFuncEvent = "message";
var attachFunc = window.addEventListener ;
if (! window.addEventListener) {
attachFunc = window.attachEvent;
attachFuncEvent = "onmessage";
}
attachFunc(attachFuncEvent, function(event) {
if (event.data == 'iframeIsDone') { // iframe is done callback here
}
});
How about checking if the url is available and only then setting the actual url of the iframe?
e.g. with JQuery
var url = "google.com"
var loading_url = "/empty.html"
document.getElementById("iframe").src = loading_url;
$.ajax({
url: url,
type: 'GET',
complete: function(e, xhr, settings){
if(e.status === 200){
document.getElementById("iframe").src = url;
}
}
});
Edit:
This does not seem to work cross domain, the status code is 0 in those cases.
If you have control over the contents of the iframe (e.g. you can add arbitrary code to the page), you can try to implement a special function in each of them, then in your page, you call that function and catch an error (via window.onerror handler) if the function called via eval fails because the page didn't load.
Here's example code: http://www.tek-tips.com/viewthread.cfm?qid=1114265&page=420
After the onload fires, you can scavenge the content of the iframe to see if it contains a usefull page or not. You'd have to make this browser specifuc unfortunately because they all display a different "page not found" message.
For more info, take a look here at http://roneiv.wordpress.com/2008/01/18/get-the-content-of-an-iframe-in-javascript-crossbrowser-solution-for-both-ie-and-firefox/

How to make a script to run on pages that updates with ajax requests?

I have a script that runs on some pages. The problem is that I attach the script on the page load, but all links on the page make requests and change the contents from the response. (The url's hash changes)
I need a way to check when the "page" is finished loading to add my scripts.
The problem:
somesite.com/home (event load is fired)
*user clicks a link*
somesite.com/home#profile (event load isn't fired, the page is
already loaded, but the contents are
being changed through ajax calls)
How can I do that? I'm thinking on adding a watcher that will check the page all the time and call the corresponding script.
How can I check if the page is sending a request and execute something when the request ends? (I guess it's possible since Firebug does that)
You could use setInterval, and check every 500 ms for changes in the location hash:
var oldHash = '';
setInterval(function(){
var newHash = location.hash;
if(oldHash != newHash){
oldHash = newHash;
// do something
}
}, 500);

Categories