Saltar al contenido

JS – window.history – Eliminar un estado

Si encuentras algún detalle que te causa duda puedes comentarlo y te ayudaremos lo mas rápido que podamos.

Solución:

Es posible que ya hayas avanzado, pero … hasta donde yo sé, no hay forma de eliminar una entrada (o estado) del historial.

Una opción que he estado investigando es manejar el historial usted mismo en JavaScript y usar el window.history objeto como una especie de portador.

Básicamente, cuando la página se carga por primera vez, crea su objeto de historial personalizado (iremos con un array aquí, pero use lo que tenga sentido para su situación), luego haga su pushState. Pasaría su objeto de historial personalizado como el objeto de estado, ya que puede ser útil si también necesita manejar a los usuarios que navegan fuera de su aplicación y regresan más tarde.

var myHistory = [];

function pageLoad() 
    window.history.pushState(myHistory, "", "");

    //Load page data.

Ahora, cuando navega, agrega a su propio objeto de historial (o no, ¡el historial ahora está en sus manos!) Y usa replaceState para mantener el navegador fuera del bucle.

function nav_to_details() 
    myHistory.push("page_im_on_now");
    window.history.replaceState(myHistory, "", "");

    //Load page data.

Cuando el usuario navega hacia atrás, llegará a su estado “base” (su objeto de estado será null) y puede manejar la navegación de acuerdo con su objeto de historial personalizado. Luego, haces otro pushState.

function on_popState() 
    // Note that some browsers fire popState on initial load,
    // so you should check your state object and handle things accordingly.
    // (I did not do that in these examples!)

    if (myHistory.length > 0) 
        var pg = myHistory.pop();
        window.history.pushState(myHistory, "", "");

        //Load page data for "pg".
     else 
        //No "history" - let them exit or keep them in the app.
    

El usuario nunca podrá navegar hacia adelante usando los botones de su navegador porque siempre está en la página más nueva.

Desde la perspectiva del navegador, cada vez que “retroceden”, inmediatamente vuelven a avanzar.

Desde la perspectiva del usuario, pueden navegar hacia atrás a través de las páginas pero no hacia adelante (básicamente simulando el modelo de “pila de páginas” del teléfono inteligente).

Desde la perspectiva del desarrollador, ahora tiene un alto nivel de control sobre cómo el usuario navega a través de su aplicación, al mismo tiempo que le permite usar los botones de navegación familiares en su navegador. Puede agregar / eliminar elementos de cualquier lugar de la cadena del historial como desee. Si usa objetos en su historial array, también puede rastrear información adicional sobre las páginas (como el contenido de los campos y otras cosas).

Si necesita manejar la navegación iniciada por el usuario (como el usuario que cambia la URL en un esquema de navegación basado en hash), entonces puede usar un enfoque ligeramente diferente como …

var myHistory = [];

function pageLoad() 
    // When the user first hits your page...
    // Check the state to see what's going on.

    if (window.history.state === null) 
        // If the state is null, this is a NEW navigation,
        //    the user has navigated to your page directly (not using back/forward).

        // First we establish a "back" page to catch backward navigation.
        window.history.replaceState(
             isBackPage: true ,
            "",
            ""
        );

        // Then push an "app" page on top of that - this is where the user will sit.
        // (As browsers vary, it might be safer to put this in a short setTimeout).
        window.history.pushState(
             isBackPage: false ,
            "",
            ""
        );

        // We also need to start our history tracking.
        myHistory.push("");

        return;
    

    // If the state is NOT null, then the user is returning to our app via history navigation.

    // (Load up the page based on the last entry of myHistory here)

    if (window.history.state.isBackPage) 
        // If the user came into our app via the back page,
        //     you can either push them forward one more step or just use pushState as above.

        window.history.go(1);
        // or window.history.pushState( isBackPage: false , "", "");
    

    setTimeout(function() 
        // Add our popstate event listener - doing it here should remove
        //     the issue of dealing with the browser firing it on initial page load.
        window.addEventListener("popstate", on_popstate);
    , 100);


function on_popstate(e) 
    if (e.state === null) 
        // If there's no state at all, then the user must have navigated to a new hash.

        // 
        // 
        // 

        // Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
        window.history.go(-1);

        // Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
        // This would also prevent them from using the "forward" button to return to the new hash.
        window.history.replaceState(
             isBackPage: false ,
            "",
            ""
        );
     else 
        if (e.state.isBackPage) 
            // If there is state and it's the 'back' page...

            if (myHistory.length > 0) 
                // Pull/load the page from our custom history...
                var pg = myHistory.pop();
                // 

                // And push them to our "app" page again
                window.history.pushState(
                     isBackPage: false ,
                    "",
                    ""
                );
             else 
                // No more history - let them exit or keep them in the app.
            
        

        // Implied 'else' here - if there is state and it's NOT the 'back' page
        //     then we can ignore it since we're already on the page we want.
        //     (This is the case when we push the user back with window.history.go(-1) above)
    

No hay forma de borrar o leer el historial pasado.

Puede intentar rodearlo emulando la historia en su propia memoria y llamando history.pushState ventana cada vez popstate se emite el evento (que es propuesto por la respuesta de Mike actualmente aceptada), pero tiene muchas desventajas que resultarán en una UX aún peor que no admitir el historial del navegador en su aplicación web dinámica, porque:

  • El evento popstate puede ocurrir cuando el usuario regresa ~ 2-3 estados al pasado
  • El evento popstate puede ocurrir cuando el usuario avanza

Entonces, incluso si intenta rodearlo construyendo un historial virtual, es muy probable que también pueda conducir a una situación en la que tenga estados de historial en blanco (a los que retroceder / avanzar no hace nada), o donde retroceder / avanzar salta algunos de tu historia dice totalmente.

¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)



Utiliza Nuestro Buscador

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *