This is the scenario: we have a x.html page that could be loaded as a “standalone” page or as frame of another page y.html (same domain). Both pages have a function called setDirtyFlag() that just sets an internal flag to true or false. When x is loaded inside a y iframe, it should also set the parent dirty flag with the same value. This is the code for x and y pages:
x.html:
<html>
<head>
<script>
var setDirtyFlag=function(val) {
isDirty = val;
if (window.parent && window.parent.setDirtyFlag)
window.parent.setDirtyFlag(val);
}
setDirtyFlag(true);
</script>
</head>
<body>
This is the iframe
</body>
</html>
y.html:
<html>
<head>
<script>
var setDirtyFlag = function(val) {
alert('dirty flag set');
}
</script>
</head>
<body>
<iframe src="x.html"></iframe>
</body>
</html>
You can create two files in a folder and load y.html without problems, you will see an alert saying that dirty flag has been set. But if you load x.html apparently everithing is ok, but the script is entering in a recursive loop that will finish when the browser exceeds its capacity. You can see it by adding an alert inside the if (window.parent && window.parent.setDirtyFlag):
if (window.parent && window.parent.setDirtyFlag) {
alert("again");
window.parent.setDirtyFlag(val);
}
Why window.parent is defined even if the page is not inside an iframe? And why it contains a reference to the functions in this frame? And the most important, how to make it work?
When a window does not have a parent, the “parent” property is a reference to itself.
You can just check to see if
window.parent == window.