-1

i'm trying to change urls without reloading the browser , i've used history.pushState it show the new url but not reloading the page till i'll reload the browser manually

  function change_url(url) {
    history.pushState(null, null, url);
  }  
<button onclick="change_url('/');" class="btn btn-primary dim btn-dim" id="btn-main" type="button"><i class="fas fa-home"> </i> main</button>
<button onclick="change_url('/parts/');" class="btn btn-warning dim btn-dim" type="button"><i class="fas fa-grip-horizontal"> </i> parts </button></a>
artiest
  • 554
  • 5
  • 20
  • 1
    Dear Hunar, your question is misleading. For me it sounds paradox: You want to change the URL without reloading, but you are not satisfied, because you need to reload the page. Maybe should have a look in the docs: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState – Michael W. Czechowski Aug 09 '21 at 09:33
  • so what is the solution , should i change content? – artiest Aug 09 '21 at 10:02

1 Answers1

1

As you already mentioned history.pushState will not affect a reload, so you will need to handle any content changes manually by the client. For example you could add an event-listeners, which will listen to changes on the location and then do something:

  function change_url(url) {
    history.pushState(null, null, url);
// add this to your function
 window.dispatchEvent(new Event('popstate'));
  }  
window.addEventListener('popstate', function(){
    console.log('url changed!');
/* do something ...*/
})
B Polit
  • 162
  • 8
  • not work : what should i put instead `do something` ? – artiest Aug 09 '21 at 09:58
  • 1
    Whatever you need to happen, such as loading the part of the content that changed. We don't know how your application is designed so we can't answer that. But it's a bit unclear what you are even trying to do here. Maybe you just want to actually load a new page, by using `location.href = url` instead of `history.pushState(null, null, url)`? – CherryDT Aug 09 '21 at 11:51
  • 2
    Like @CherryDT said – `do something` is just a placeholder for your action. So maybe you need to load content (e.g. via `fetch()`) from the server and replace the `html:body` with this content. So maybe you could try to explain a little bit more, what you're trying to achieve. – B Polit Aug 09 '21 at 12:14
  • switch pages without reloading the browser – artiest Aug 09 '21 at 12:43
  • @BPolit it still reload the pages when i click the buttons to go new url – artiest Aug 09 '21 at 12:55
  • @CherryDT all i want is preventing reloaing browser whenever a button clicked on – artiest Aug 09 '21 at 12:56
  • location.href = url witll reload the browser – artiest Aug 09 '21 at 12:57
  • sorry but then it's not clear what you mean. if you don't want to reload the page, then _you_ have to update the content in the way _you_ want/need. I'm not sure what we then can do to help you (we have no idea how your application is built)! – CherryDT Aug 09 '21 at 13:59