No , you cannot create new Location objects yourself.
However, you can get closer. I built a small (~ 1kB) library that offers a custom Location function that works the way you would expect from the standard Location function:
With it, you can create new location objects, such as:
var x = new Location('https://joe: secret@example.com :8080/path?q=test#hash'); console.info(x.protocol); // > 'https:' console.info(x.hostname); // > 'example.com' console.info(x.port); // > '8080' console.info(x.pathname); // > '/path' console.info(x.search); // > '?q=test' console.info(x.hash); // > '#hash'
The created location object is very similar to the window.location object or bindings. If you install href , all other fields will be updated automatically:
x.href = 'http://www.example.org/wow' console.info(x.protocol); // > 'http:' console.info(x.hostname); // > 'www.example.org' console.info(x.port); // > '' console.info(x.pathname); // > '/wow' console.info(x.search); // > '' console.info(x.hash); // > ''
It even generates a 'change' event whenever a URL changes that you can listen to:
x.on('change', function(){ console.info(this.href); }) x.href= 'https://stackoverflow.com'
It works on Node as well as in the browser, but because of this tiny size, there is no separate download on the network; include it in your kit using Webpack or Browserify.
source share