Erica Stockwell-Alpert
Erica Stockwell-Alpert

Reputation: 4863

Iframe messing up browser history - adding current page to history

I have product pages on my site that have an iframe on them. The presence of the iframe is messing up the browser history - the current page gets added to the history stack, and when I click the back button the page remains the same, I have to click twice to get to the actual previous page (and I have to click quickly, or else the page gets added to the stack again). I have isolated this as the problem because when I remove the entire iframe, the issue goes away; it is also resolved when I remove the src on the iframe.

<iframe sandbox="allow-same-origin allow-scripts" class="add-to-cart__iframe" id="addtocartiframe" src="https://buy.website.com/en/addtocart/#/addToCart/109ATCA714-1003R/71cbba730b634200ac437cc3907ed626/en" title="Add to Cart"></iframe>

I tried adding sandbox="allow-same-origin allow-scripts" based on How can I prevent Iframe messing browser's history after interactions with it? but it didn't help.

I know that I could remove the src and use Javascript to update the src only when the button to show the iframe is clicked, however, this would still cause the back button to not work as expected if the iframe button has been clicked, and the client has specifically called that out as an issue (if they go to the page, click the button to open the iframe, and then try to click back, it doesn't work and this is frustrating them)

Upvotes: 5

Views: 1888

Answers (1)

Evan Kleiner
Evan Kleiner

Reputation: 514

I just ran into a very similar problem in my application. This issue happens when you programmatically update the src attribute of the <iframe> element, which it sounds like you're doing when users click "the button to show the iframe".

I settled on the suggestion at https://stackoverflow.com/a/32854398/8948645 to use an <object> tag with the data attribute rather than an <iframe> tag with the src attribute. It seems to work identically, except that it avoids the issue with the browser history that you've encountered.

I also found https://stackoverflow.com/a/8681618/8948645. Instead of modifying the src attribute, that answer suggests removing the <iframe> element from the DOM, modifying it, then putting it back in the DOM. I think this strategy would have also addressed my issue, but I didn't try it because the <object> tag worked great for me.

Upvotes: 1

Related Questions