48

$window.location.origin returns the wrong value on IE.

The origin property returns the protocol, hostname and port number of a URL.

Example

url: http://localhost:8080/products/search

Chrome: $window.location.origin returns http://localhost:8080

IE: $window.location.origin returns http://localhost:8080/products/search

How can I have the right value on IE?

giammin
  • 18,620
  • 8
  • 71
  • 89
Ryan Langton
  • 6,294
  • 15
  • 53
  • 103
  • are you using the same browser? – giammin Mar 21 '14 at 16:26
  • you're right, it's a browser problem. Updated the question. – Ryan Langton Mar 21 '14 at 16:29
  • I don't know how it differs between all browsers, but I would consider writing something that parses a URL into various components for consistency. This may help: http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript – Zhihao Mar 21 '14 at 16:30
  • It's worth adding that `$window` is the same as `window` but provided by Angular. https://docs.angularjs.org/api/ng/service/$window – Tom Robinson Feb 02 '17 at 16:30

2 Answers2

85

You may also need the port number. If so, you can use this polyfill

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" 
    + window.location.hostname 
    + (window.location.port ? ':' + window.location.port : '');
}

This polyfill is already part of Modernizr.

jgillich
  • 71,459
  • 6
  • 57
  • 85
Jason
  • 8,400
  • 10
  • 56
  • 69
  • 1
    This is probably a better answer. – imns Mar 05 '15 at 15:19
  • 1
    Are there any downsides to using `window.location.hostname` instead of hostname and port? It should include both parts according to https://developer.mozilla.org/en-US/docs/Web/API/Location – Tom Robinson Feb 02 '17 at 16:27
  • alt syntax using template string on that last line of code: `+ (window.location.port ? ``:${window.location.port}`` : '');` (except single tilde, not double, not sure how to do that in comments) – MrBoJangles Jul 05 '18 at 17:33
32

The problem (as usual) is IE that does not have window.location.origin

Instead try to use something like:

var root = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');

Or you can add on top of your javascript this code so you don't have to bother about it

if (!window.location.origin) {
  window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
Shannon Hochkins
  • 11,763
  • 15
  • 62
  • 95
giammin
  • 18,620
  • 8
  • 71
  • 89
  • Are there any downsides to using `window.location.hostname` instead of `hostname` and `port`? It should include both parts according to https://developer.mozilla.org/en-US/docs/Web/API/Location – Tom Robinson Feb 02 '17 at 16:23
  • 1
    @tjrobinson No. if you dont care having always the port specified (http://stackoverflow.com:80) – giammin Feb 02 '17 at 17:39