I'm comparing all iframes in my javascript, to see if one of them matches my element's (an a -tag) body element. The problem I have is that the collection of iframes can sometimes change, because they are all generated by a framework. Hence sometimes I get "Access is denied" errors in IE8 and sometimes I don't. I'm not referencing any external Iframes since all my Iframe开发者_运维百科 are part of the framework and hence have same protocoll, port etc. This is the code I use to loop through the iframe collection:
var calculatedwidth = 0;
var calculatedheight = 0;
var searchbody = $(srcElement).closest('body');
//I store the Iframe-nodelist in var arrFrames
var arrFrames = document.getElementsByTagName("iframe");
LabelA1:
for(i = 0; i<arrFrames.length; i++){
//console.log(i);
//if(arrFrames[i].id != 'PeopleDetailsIframe'){
if($(arrFrames[i].contentWindow.document.body).is(searchbody)){
// This line is where the error occures normaly
calculatedwidth = $(arrFrames[i]).offset().left;
calculatedheight = $(arrFrames[i]).offset().top;
break LabelA1;
}
else{
//console.log("Forum Iframe not found");
}
}
}
I temporarily fixed my problem by including a break, to break out of the loop if my searched iframe is found. This works about 80% of the time my code is executed. But since the webpage is customizable, some users have responded that they get a javascript error when my code runs. Based on some research I did on the subject Cross-Domain scripting , Scripting with Iframe Collection, I learned that the Iframe collection is a live-collection? So this means that the collection is bound to change (sometimes) when I'm looping through it. So I assumed that this can cause 2 errors, an infinite loop or wrong index errors. I thought that storing the refrence to the iframes in a var, would prevent the errors. But obviously I was wrong:
var arrFrames = document.getElementsByTagName("iframe");
This didn't help. Any suggestions how I can prevent the wrong index Issue? Or am I completely wrong about where my problem lies? Help is much appreciated!
You can put a try-catch
around the if()
. That way the loop should always run without an error.
var calculatedwidth = 0;
var calculatedheight = 0;
var searchbody = $(IframeDocument).closest('body');
var arrFrames = document.getElementsByTagName("iframe");
LabelA1:
for(i = 0; i<arrFrames.length; i++){
//console.log(i);
//if(arrFrames[i].id != 'PeopleDetailsIframe'){
try {
if($(arrFrames[i].contentWindow.document.body).is(searchbody)){
// This line is where my the error occures normaly
calculatedwidth = $(arrFrames[i]).offset().left;
calculatedheight = $(arrFrames[i]).offset().top;
break LabelA1;
}
else{
//console.log("Forum Iframe not found");
}
} catch() {
// the IFrame has security issue => avoid it
}
}
}
精彩评论