30 June 2013

Ever stuck with a problem/issue with browser back button and an iFrame on a webpage? If yes, read on.

Consider a scenerio where we have an iframe inside a webpage. When user clicks any links present inside iframe the iframe's content changes and it displays a new page.

As a side effect of clicking the link an entry is created in browser history for that URL. This changes browser behaviour as users will have to click twice to navigate to the previous page.

The first back button click will take the iframe to the prev displayed page. The second back button click will take the user to the actual previous page.

Even if you change the iframe's src with javascript, as in the code shown below. It will create an entry in the browser history.

$("myIframe").attr("src","http://devangpaliwal.com");

OR

document.getElementById("myIframe").src="http://devangpaliwal.com";


How to avoid making an entry in the browser history when we change the iframe's src url?

If we want to change the src of a iframe without changing the browser history we can take advantage of the location object. We can do something like this -

document.getElementById("myIframe").contentWindow.location.replace="http://abc.com";

Another solution would be to delete the iframe completely and add a new one dynamically with the desired src.


More Information



blog comments powered by Disqus