Clicking on iframe, open new tab in browser

2019-03-01 05:49发布

问题:

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

回答1:

What you might try is to add a listener on the element:

var iframeDiv = document.getElementById("iframeDiv");

iframeDiv.addEventListener("click", function(e) {
    window.location.href = document.getElementById("frame").src;
}, true);

The true passed after the function in the addEventListener call tells the browser to run this function on capture, which means before the event is executed inside the iframe. If you don't do that, clicking on a link inside the iframe would follow that link before the JavaScript event runs. Sadly, capture events aren't compatible with IE<9

But it doesnt work with iframes!

I thought this could work, but it seems browsers treat the iframe as an other 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 element.

var iframeDiv = document.getElementById("iframeDiv");

iframeDiv.addEventListener("click", function(e) {
  window.location.href = document.getElementById("frame").src;
});
#iframeDiv {
  position: absolute;
  background-color: yellow;
}
#frameDummy {
  position: absolute;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0px;
}
<div id="iframeDiv">
  <iframe id="frame" src="/" width="200" height="200"></iframe>
  <div id="frameDummy"></div>
</div>



回答2:

Probably the thing which you are looking for is not a right idea, because when we define a src attribute for the frame, which loads the frame with the url given in the src. any functions written to the frame will not be effected

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>

</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>

When ever you click this frame in "frame.html",you will be redirected to a link into a new window.



标签: html iframe