How to make all links in an iframe open in a new tab

I try to do this when you click the link in the <iframe> , it will open the link in a new tab, not in the <iframe> . Please note: I do not control the content that people view through the <iframe> .

I am trying to do this using javascript, for example, $('a').setAttribute('target','_blank'); but it does not work for me. I also have an HTML <base target="_blank"> in the document, which doesn't do the trick either.

It's impossible? Or was I just looking for the wrong place? Thanks in advance!

+7
javascript jquery html iframe
source share
6 answers

I would expect this:

 $('a').setAttribute('target','_blank'); 

.. for failure (in silence - because jquery usually fails), because if the contents of the iFrame belong to a different domain, there are problems accessing the page in the iFrame from the containing page.

That is: if your own page belongs to domain a (for example, mysite.com) and iframe belongs to domain b (for example someothersite.com), then the security behavior of the web browser is such that using javascript to control the contents of the iFrame will result in an error "Access denied."

If you used jQuery jQuery without jquery, you will see an error. From the parent page something like this:

 window.frames["iFrameName"].getElementsByTagName("a")[0].target="_blank" 

you will see an error.

Unfortunately, I'm not sure what you can do about it. This is a deliberate thing to stop one website, including another, and change the contents after loading so that it says something else.

One way would be to call a script on your server (i.e. in the same domain) and pass the URL. The script receives the contents of the page you were on and rejects it in your browser, so you will have the contents of your desired web page, but its address is on your site .. for example, if it's php:

http://yourdomain.com/getURL.php?url=http:www.google.com

Beware of authentication issues there though

+7
source share

To load all links on a page in the parent window, use:

 <base target="_parent" /> 

else in a new window:

 <base target="_blank" /> 
+7
source share

check out this solution that helped me: Make links inside iframe open in a new window

or you can try parent.window.open ("{{your location}}");

+1
source share

Use $('a').attr('target','_blank'); instead of setAttribute ...

Fiddle

+1
source share

Replace target='blank' with onclick='window.open();'

+1
source share

using javascript

 var links= document.getElementsByTagName('a'); for (var i=0; i<links.length; i++){ links[i].setAttribute('target', '_top'); } 

using jquery

 $('a').each(function() { var a = new RegExp('/' + window.location.host + '/'); if (!a.test(this.href)) { $(this).attr("target","_top"); } }); 
+1
source share

All Articles