开发者

Is it possible to dynamically change the URL of a webpage?

开发者 https://www.devze.com 2022-12-16 11:18 出处:网络
I just wanted to know, is there any possible way to change the URL that appears in the addres开发者_Python百科s bar of a webpage dynamically? Like, maybe there are two buttons on the webpage, and when

I just wanted to know, is there any possible way to change the URL that appears in the addres开发者_Python百科s bar of a webpage dynamically? Like, maybe there are two buttons on the webpage, and when the user clicks one it will (or won't it does not matter) refresh the page and the url will be mysite.com/page1, or if the user clickes the second button, the url that appears in the address bar will be mysite.com/page2?

I do not need it to chaneg the domain, just the part after.

Just wanted to say, that I DO NOT want to go to another page. This must be done on one page. It does not matter if it is done with JS, PHP, or via the .htaccess file, but it must do this with only one page.


Outside of changing the .location you only really have control over the window.location.hash.

window.location.hash = "boo"; http://mysite.com -> http://mysite.com/#boo

This is the only way to not go to a new page while changing the URL. All other methods will refresh the page or redirect the page:

  1. window.location redirects user when changed
  2. window.location.pathname redirects user when changed
  3. window.location.search redirects user when changed
  4. window.location.hash does not redirect user when changed

You can also just change the non domain path by using a relative url:

window.location = "page1"; // include forward-slash if necessary
                           // goes to http://somesite.com/page1


You can definitely (and easily) serve the same page off both /page1 and /page2 and have the buttons navigate respectively to one and the other -- "refreshing the page", as you say (i.e. loading it up again from the server, or browser cache), and of course change accordingly what appears in the address bar, too. However, I don't see what's the point of doing that.


I don't quite understand what you want.

Is it that in both cases, you want the same page to be shown but with different urls ?

In that case, you could write a .htaccess file to redirect to the same page for both /link1 and /link2 and point the button to either of the links.


Just to update this question in case others come along.

This can now be handled via javascript using pushState(). There's a couple of libraries (such as History.js) that aim to ease implementation across different browsers currently without proper support. However, if you'd like see a simple usage example without the use of such libraries, feel free to check out the following article on Hawkee

Dynamically change URLs using Push and Popstate

0

精彩评论

暂无评论...
验证码 换一张
取 消