1

I'm using an iframe, and I have a back button which runs this javascript code (when user clicks on back button):

document.getElementById("myframe").contentWindow.history.go(-1); // back

This works fine, but If there is no previous page in the frame, main page will go back.

How to avoid this? I want just iframe to go back, and if there is no previous page, simply do nothing.

EDIT: This is my code. (@ jsfiddle)

Mahdi Ghiasi
  • 13,093
  • 16
  • 63
  • 116

1 Answers1

3

Keep track of changes like this:

<script>
    window.iFrameChanges = -1; //will get incremented to 0 on first page load
</script>

<iframe onLoad="window.iFrameChanges+=1;" src="..."></iframe>

And the decrement the window.iFrameChanges value on history go back

This way you can know the "length" of history

wmarbut
  • 4,335
  • 3
  • 40
  • 72
  • This may not work, if user clicks on back button when page is not completely loaded... Any ideas? – Mahdi Ghiasi Dec 05 '12 at 11:24
  • The code that introduces the window.iFrameChanges should be above the back button that you added. If it is, then it will always be run before the user has a chance to use your back button. The only way I could see this occurring is if the script that introduces the variable is beneath the back button. Also make sure your javascript call on the back button isn't inline. Use a method. `` and the script `function goBack() { if (window.iFrameChanges > 0) { document.getElementById("myframe").contentWindow.history.go(-1); } }` – wmarbut Dec 05 '12 at 15:13
  • The problem is, you increase `iFrameChanges` on `onLoad`, means that it increases after new page is completely loaded. But if new page is loading, but still not completed, and user clicks on back button, then `iFrameChanges` won't increase... – Mahdi Ghiasi Dec 05 '12 at 16:57
  • I got an error if I try to access `history` property of the frame: https://stackoverflow.com/questions/25098021/securityerror-blocked-a-frame-with-origin-from-accessing-a-cross-origin-frame Any solution to this? I mean there maybe some workaround to tell iframe to go back and forth without accessing `history`. – ADM-IT Apr 14 '21 at 09:34