Reputation: 2143
I want to open new tab on clicking of anywhere in iframe window.
<div id="iframeDiv">
<iframe id="frame" src="anysite.com" width="100%" height="400"></iframe>
</div>
on click of iframeDiv , I want to open anysite.com in new browser tab
Upvotes: 2
Views: 10761
Reputation: 6778
Browsers treat an iframe
as another page and will not throw events on the parent. This means that the only way to actually detect clicks on an iframe
is to put an invisible element in front of the iframe
so that you're not actually clicking on the frame, but on the overlaying element.
var iframeContainers = document.getElementsByClassName("iframe-container");
for (let container of iframeContainers) {
container.addEventListener("click", function(event) {
let iframe = event.target.parentElement.querySelector('iframe');
if (iframe) {
let url = iframe.getAttribute('src');
window.open(url, '_blank').focus();
}
});
}
.iframe-container {
position: relative;
background-color: yellow;
height: 300px;
width: 300px;
}
.iframe-container > iframe {
width: 100%;
height: 100%;
}
.iframe-container > .iframe-overlay {
position: absolute;
top: 0px;
bottom: 0px;
left: 0px;
right: 0px;
}
<div class="iframe-container">
<iframe id="iframe" src="https://www.example.com"></iframe>
<div class="iframe-overlay"></div>
</div>
The snippet's on-click behavior doesn't work in Stack Overflow's environment for some reason but it does work on jsFiddle:
https://jsfiddle.net/nathanwailes/xtzqy35u/40/
Upvotes: 6
Reputation: 401
When we define an src attribute for the frame, which loads the frame with URL in the src. any functions written to the frame will not be affected
Instead, try like this create a new page named frame.html with this code
<!DOCTYPE html>
<html>
<body>
<div id="iframeDiv">
<base target="_blank" />
<iframe width="400" height="215" frameborder="10px" scrolling="no" marginheight="0" marginwidth="0"
src="frameinside.html">
</iframe>
</div>
</body>
</html>
and a page frameinside.html
<html>
<head>
<title>This frame goes inside</title>
</head>
<body onclick="window.open('http://google.com', '_blank')">
<h1 align="center">Welcome home</h1>
</body>
</html>
Whenever you click this frame in "frame.html", you will be redirected to a link in a new window.
Upvotes: 2