No, you can't create new Location
objects yourself.
However, you can get pretty close. I built a small (~1kB) library that offers a custom Location
function that works like you would expect the standard Location
function to do:
With it you can create new location objects like this:
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 works very similar to the window.location
object or to anchors. If you set the href
, all other fields update 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 emits a 'change'
event whenever the URL changes that you can listen for:
x.on('change', function(){
console.info(this.href);
})
x.href= 'https://stackoverflow.com' // > 'https://stackoverflow.com'
It works on Node as well as on the browser but due to it's tiny size there is no separate web download; include it in your bundle using Webpack or Browserify.