I have an iframe pointing to an external link that does some redirections as soon as the iFrame loads. This causes added history into the browser and also when users click on links inside the iframe.
This causes a weird user experience because you have extra back history states pointing to the same parent page.
I was wondering if there was a way to prevent the iframe from ever adding history to the browser?
No, You can do almost nothing with an iframe which has src set to another domain because of XXS
You can try to use sandbox="" attribute to prevent the iframe from redirecting.
Source (MDN)
location.replace() | MDN
Since the link is external, the short answer is no. If you are in control of the content of the iframe there are a few things you can do. History will be updated any time the src attribute of an iframe is changed after it has been added to the DOM or if the user follows a link in the iframe. With control of the iframe content, when a user clicked a link, you could use postMessage and have the parent window replace the iframe element with a new one. In the same domain, you could just use window.parent.
http://jsbin.com/coregedoze/2 Here is a link of my code with an iframe, this has no sandbox attribute- as this attribute only works with HTML5 and limited browser version. I rechecked this code and it wont save any history. Only case is if you change your source of the iframe the whole page reloads and makes another entry into history, which can be avoided using sandbox="value" as mentioned in above answer by JAYDEN LAWSON. Another way around is declare your links in your page out of iframe and call them in iframe like traget="iframe_a" , where iframe_a is your iframe name. hope this helps :-)