To start the popstate / statechange event, two clicks on the back button are required.

I have a page containing an iframe. An IFrame can accept user input (by pressing a button or selecting a menu) and display content accordingly. I need it, when the user manipulates the iframe, the browser pushes each set of iframe parameters into the story; and when the user clicks the back button, the iframe reloads its content using the saved parameters from the previous history entry. I have a piece of code performing a reboot as shown below.

It is strange when I make several settings in the iframe (therefore, several status records are added to the history), and then click on the back button, it will work as follows:

Say I have state 4, 3, 2 in history, and I'm now in state 5

  • first click restore to state 4 (status message "---- state changed ----" printed
  • a second click reloads the iframe with the default content. "---- state changed ----" is not printed; reboot code is not called.
  • third click restore to state 3
  • fourth click is like second click
  • 5th click restore to state 2

So, after each click that successfully restores the state, it takes two clicks to fire the popstate event (I also tried to change the state with the same result) and restore it to another previous state.

Does anyone know what is going on here? Thanks in advance.

History.Adapter.bind(window, "popstate", function (event) { console.log("----state changed------", History.getState()); console.log("----state data------",History.getState().data.state); //code to do reload an iframe to its proper state }); 
+4
source share
2 answers

So, I came across the same problem. The situation we encountered was to use history.pushState() to update the url, and then after changing the src attribute for <iframe> . By changing src <iframe> , we implicitly tell the browser to add to its history that the iframe has changed. In this way...

  • When we clicked for the first time, window.history popstate is launched by the <iframe> src attribute and returns to it in its previous state.
  • Pressing the second button again raises the popstate event for the state you originally popstate stack

Our solution was that when we decided to update the URL and push the state onto the stack, when we wanted to update the <iframe> , we used jQuery to replace the <iframe> list, so ...

 $("#iFrameID").replaceWith(('<iframe id="iFrameID" src="' + location + '"></iframe>' 

By doing this, we removed the side effect of the browser history polluted by our update with the <iframe> .

+4
source

I had the same problem. Instead of navigating the user to the previous page on the website, the back button moved the user to the previous page inside the iframe. This code below will help you solve your problem:

 iframe.contentWindow.location.replace(href) 
0
source

Source: https://habr.com/ru/post/1481024/


All Articles