小能豆

How do I modify the URL without reloading the page?

javascript

Is there a way I can modify the URL of the current page without reloading the page?

I would like to access the portion before the # hash if possible.

I only need to change the portion after the domain, so it’s not like I’m violating cross-domain policies.

 window.location.href = "www.mysite.com/page2.php";  // this reloads

阅读 83

收藏
2023-12-25

共1个答案

小能豆

Yes, you can modify the URL of the current page without reloading it using the history.pushState method provided by the HTML5 History API. This allows you to change the URL without triggering a page refresh. Here’s an example:

// Get the current URL
var currentURL = window.location.href;

// Construct the new URL (change the portion after the domain as needed)
var newURL = "www.mysite.com/page2.php";

// Use pushState to change the URL without reloading the page
history.pushState(null, null, newURL);

This will change the URL displayed in the address bar to the new one without triggering a page reload. However, please note that while this changes the URL in the browser, it doesn’t actually load a new page or change the content on the page. If you want to perform additional actions when the URL changes, you might also want to listen for the popstate event:

// Listen for the popstate event
window.addEventListener('popstate', function(event) {
    // Handle the URL change here
    console.log("URL changed to: " + window.location.href);
});

This event is triggered when the user navigates through the browser history (e.g., clicks the back or forward button). Using both pushState and the popstate event allows you to update the URL and respond to URL changes without triggering a full page reload.

2023-12-25