Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to call a parent window function from an iframe using JavaScript?
When working with iframes, you often need to call functions defined in the parent window from within the iframe. JavaScript provides several methods to achieve this cross-frame communication.
Using window.parent
The most common approach is using window.parent to reference the parent window:
<!DOCTYPE html>
<html>
<head>
<title>Parent Window</title>
</head>
<body>
<h3>Parent Window</h3>
<div id="result"></div>
<script>
function displayMessage(message) {
document.getElementById("result").innerHTML = "Called from iframe: " + message;
}
</script>
<iframe srcdoc='<button onclick="window.parent.displayMessage("Hello Parent!")">Call Parent Function</button>'
width="300" height="100">
</iframe>
</body>
</html>
Using window.top
window.top references the topmost parent window, useful when dealing with nested iframes:
<!DOCTYPE html>
<html>
<head>
<title>Top Window</title>
</head>
<body>
<h3>Top Level Window</h3>
<div id="output"></div>
<script>
function showAlert(text) {
document.getElementById("output").innerHTML = "<strong>" + text + "</strong>";
}
</script>
<iframe srcdoc='<button onclick="window.top.showAlert("Message from nested iframe")">Call Top Function</button>'
width="350" height="80">
</iframe>
</body>
</html>
Comparison
| Method | Use Case | Target |
|---|---|---|
window.parent |
Direct parent window | Immediate parent |
window.top |
Nested iframes | Topmost window |
Error Handling
Always check if the parent window exists and the function is available:
// Safe way to call parent function
if (window.parent && typeof window.parent.myFunction === 'function') {
window.parent.myFunction('data');
} else {
console.log('Parent function not available');
}
Conclusion
Use window.parent for direct parent communication and window.top for accessing the topmost window. Always include error checking to prevent runtime errors when the parent function doesn't exist.
Advertisements
