How to force iframe open all links stay in the iframe?

Member

by lew , in category: HTML & CSS , 3 months ago

How to force iframe open all links stay in the iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , a month ago

@lew 

To force an iframe to open all links within the iframe itself, you can add a target attribute to all anchor tags within the iframe that specifies the name of the iframe as the target. This will ensure that all links open within the iframe instead of navigating to a new page.


Here's an example of how you can achieve this:

  1. Add an id attribute to your iframe element in the parent HTML document:
1
<iframe id="myiframe" src="yourpage.html"></iframe>


  1. Add a script in the parent HTML document to add a target attribute to all anchor tags within the iframe:
1
2
3
4
5
6
7
var iframe = document.getElementById('myiframe');
iframe.onload = function() {
  var links = iframe.contentWindow.document.getElementsByTagName('a');
  for(var i = 0; i < links.length; i++) {
    links[i].setAttribute('target', 'myiframe');
  }
};


With this script, all links within the iframe will open within the iframe itself. Make sure to replace yourpage.html with the URL of the webpage you want to display within the iframe.