简体   繁体   中英

history.pushState() causing browser navigation

I am trying to change the URL of a page without navigating the browser to that page and causing a refresh. In the MDN documentation for manipulating the browser history , it states the following:

Suppose http://mozilla.org/foo.html executes the following JavaScript:

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

This will cause the URL bar to display http://mozilla.org/bar.html , but won't cause the browser to load bar.html or even check that bar.html exists.

This seems to be corroborated by everyone on StackOverflow as well. However, in my code, window.history.pushState() is navigating the page. The console even states quite clearly:

Navigated to http://localhost:8090/?

Here's the code I'm using:

attemptLogin(username, password)
  .then((result) => {
    // navigate to Landing Page
    window.history.pushState('data', 'title', '/');
  })

I'm also not sure why it's adding a question mark, but the fact that it is navigating the browser seems like the more pressing issue. Does anyone have any insight they could offer?

The code you have provided will not cause the effect you have described.

You are triggering that code somehow . The symptoms you have say that it is from an event such as a click on a link or a submission of a form.

The JavaScript is running, and then the normal behaviour of the link or form submission is occurring … which is to cause the browser to navigate to a new URL.

You need to prevent the default behaviour of that action, for example:

document.querySelector("a").addEventListener("click", handler);

function handler(evt) {
    evt.preventDefault();

    attemptLogin(username, password)
        .then((result) => {
                    window.history.pushState('data', 'title', '/');
        });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM