Update iframe without affecting browser history

You may face a scenario where you need to update the iframe element on your html page based on some JavaScript condition e.g. a calendar component may be running inside the iframe. Simply updating the “src” attribute causes the browser history to be updated and enables the forward and back browser buttons. This may cause issues in enabling/disabling holidays or weekend dates.

document.getElementById('calfrm1').src = "popcal.asp?target=form1.duedate&weekends=Y

The below code snippet uses contentWindow property of the iframe and replaces the location without affecting the browser history.

var ifr = document.getElementById("calfrm1");

ifr.contentWindow.location.replace("popcal.asp?target=form1.duedate");

Using replace() works only within your own domain iframes. It fails to work on remote sites.

You can remove and construct a new iframe element in the same spot to handle this. When you modify the src attribute, it creates history items as mentioned above, so make sure to set it before the append.

var container = iframe.parent();

iframe.remove();
iframe.attr('src', 'about:blank');

container.append(iframe);
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.