• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 300
  • Last Modified:

Checking the readability of an iframe

I have a dynamically created iframe that the src location contains a page on my domain.
This src location is able to change to a different domain causing a security read issue, and when it does I need to know so I can redirect the user.

So I created the code below that appears to be working, but I am unsure if I am supposed to be using setInterval() or setTimeout() in the startTimer() function.

Also, is this code a reliable means of checking the readability of an iframe among the popular browsers (IE, FF, Opera, Safari)?
Is there any modifications needed?
function startTimer()
{
	// Keep checking the iframe for readability
	timer_1 = setInterval("checkFrame()",50);
}
 
function checkFrame()
{
	// Get the contents of the iframe 
	var iframe = document.getElementById('MyFrame');
	if (iframe.contentDocument)
	{
		var doc = iframe.contentDocument;
	}
	else if (iframe.contentWindow)
	{
		var doc = iframe.contentWindow.document;
	}
	
	// Is the contents of the iframe still readable? if not, then redirect
	if ((typeof(doc.innerHTML) == 'undefined') || (typeof(doc.innerHTML) == null))
	{
		// This is where I call the redirect() function in 1 second
		clearTimeout(timer_1);
		timer_2 = setTimeout("redirect()",1000);
	}
}
 
function redirect()
{
	clearTimeout(timer_2);
	window.location.href='http://www.mywebsite.com/page.html';
}

Open in new window

0
ray-solomon
Asked:
ray-solomon
1 Solution
 
Michel PlungjanIT ExpertCommented:
It all looks correct, however would expect an Access Denied at
        var doc = iframe.contentDocument;
       or
         var doc = iframe.contentWindow.document;

0
 
ray-solomonAuthor Commented:
I found a fix for it.

I used your suggestion and put try/catch statements
around doc = iframe.contentDocument; and doc = iframe.contentWindow.document;
but there were no errors.

So instead I replaced this:

 if ((typeof(doc.innerHTML) == 'undefined') || (typeof(doc.innerHTML) == null))
{
      // This is where I call the redirect() function in 1 second
      clearTimeout(timer_1);
      timer_2 = setTimeout("redirect()",1000);
}

with this:

try {
var blah=doc.innerHTML;
}catch(e) {
clearTimeout(timer_1);
timer_2 = setTimeout("redirect()",1000);
}

And it worked perfectly.

However I rewritten my code since then and came up with a different solution that is more reliable.

Thanks for getting me in the right direction.
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now