Technology

Communicating With JavaScript Inside and Outside iframes

Discover how to enable communication between an iframe and its parent document using JavaScript, enhancing web page interactivity.

Sangrak

The iframe tag, originally supported only by older versions of Internet Explorer, is an incredibly useful tag for embedding virtual frames within documents. Due to its usefulness, it has become somewhat of a unique tag incorporated into web standards over time.

When utilizing this tag, there's often a need for communication between the content inside the iframe and the surrounding document, such as automatically adjusting the iframe's vertical size.

Executing a Function from Inside to Outside

document (body.html)

<html>
	<head>
		<script type="text/javascript">
		function callbackTest()
		{
			alert("Function from body.html");
		}
		window.onload = function(){
			frames['testname'].callbackTestInner();
		}
		</script>
	</head>
	<body>
		<iframe src="inner.html" name="testname"></iframe>
	</body>
</html>

document (inner.html)

<html>
	<head>
		<script type="text/javascript">
		function callbackTestInner()
		{
			alert('Function from inner.html');
		}
		parent.callbackTest();
		</script>
	</head>
	<body>
		Test content
	</body>
</html>

To call a function from the outer document inside the iframe, you simply use parent.outerDocumentFunctionName().

Conversely, to invoke a function within the iframe from the outer document, utilize the iframe's name attribute to obtain the iframe object, then call the function as follows:

frames['testname'].callbackTestInner();

This allows the function inside the specified iframe to be executed.

Considerations

A common issue with iframe communication is that the total loading time of both documents might differ, causing potential misalignment in function execution timing. This discrepancy can lead to unexpected behavior and errors, suggesting the need to be cautious and considerate of timing when implementing iframe communication.

More on this topic