How to Open a Link From <iframe> in the Parent Window
In this snippet, you can find out how it is possible to open a link from the HTML <iframe> element in the parent window. For that, you can use the <base> element.
To open a link from an <iframe> in the parent window, you can use the "target" attribute with the value "_parent" in the <a> tag that contains the link. This will tell the browser to open the link in the parent window instead of the <iframe> window.
Here is an example code:
parent.html:
How to Open a Link From <iframe> in the Parent Window
<!DOCTYPE html>
<html>
<head>
<title>Parent Window</title>
</head>
<body>
<h1>Parent Window</h1>
<iframe src="iframe.html" width="400" height="300"></iframe>
</body>
</html>In this example, we have an <iframe> element that loads a file called "iframe.html". Inside the "iframe.html" file, we have a link that we want to open in the parent window.
iframe.html:
<!DOCTYPE html>
<html>
<head>
<title>IFrame</title>
</head>
<body>
<h1>IFrame Window</h1>
<a href="http://www.example.com" target="_parent">Open Link in Parent Window</a>
</body>
</html>In this example, we have used the "target" attribute with the value "_parent" in the <a> tag that contains the link. When the user clicks on the link, the browser will open the link in the parent window instead of the <iframe> window.
Note that this works regardless of whether the <iframe> and the parent window are on the same domain. Cross-origin navigation via the target attribute is fully supported by browsers.
More helpful details:
When a web page contains an <iframe>, it creates a nested browsing context. By default, links and forms inside the <iframe> load within that same context. To change this behavior, use the target attribute on the <a> or <form> element. Setting target="_parent" loads the content in the immediate parent frame. Setting target="_self" keeps it in the current <iframe>. For breaking out of deeply nested frames, target="_top" is often preferred as it replaces the entire window. Note that these navigation targets work across different domains without security restrictions; window.postMessage() is only required for JavaScript communication between cross-origin frames.