0

I know that the following JavaScript code instructs the browser to insert the specified URL string into the address bar AND go there:

document.location.href = 'http://www.john-doe.com/';

However, what I want to do is to only change the URL that appears in the address bar, but don't actually go to that URL.

How can I do this?

Joel Meine
  • 43
  • 1
  • 4
  • `document.location.href` is a javascript function that will redirect the user, why you used this function if you don't want to redirect them? –  Sep 22 '18 at 19:16
  • 1
    You really can't do what you want to do. Why would you even consider doing this? It sounds fishy to me.... – mrunion Sep 22 '18 at 19:21

2 Answers2

2
window.history.pushState({}, 'hi', '/hi')

More at the history API

Edit: This can only change the path, not the domain or protocol.

Andy Ray
  • 26,451
  • 11
  • 86
  • 123
  • 2
    Worth mentioning that ["The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception."](https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method) – spender Sep 22 '18 at 19:23
  • Yes. The example of the question seems to refer to a whole new domain. – Piero Sep 22 '18 at 19:26
  • Here is a more clear description of what I want to do: 1. User is currently at http://splash.john-doe.com 2. Use JavaScript to change http://splash.john-doe.com to http://www.john-doe.com but don't actually go to http://www.john-doe.com. – Joel Meine Sep 22 '18 at 19:43
  • @JoelMeine The origin can't be changed. – spender Sep 22 '18 at 20:49
-1

It is not possible to change the browser URL via code without going to it. For security reasons I suppose.

Piero
  • 194
  • 12