iframe Back with javascript - avoid main page go b

2019-06-02 09:12发布

问题:

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)

回答1:

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