Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$window.location.origin gives wrong value when using IE

$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?

like image 914
Ryan Langton Avatar asked Mar 21 '14 16:03

Ryan Langton


People also ask

What does Window location Origin return?

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

What is the difference between document location and window location?

window. location is read/write on all compliant browsers. document. location is read-only in Internet Explorer (at least), but read/write in Gecko-based browsers (Firefox, SeaMonkey).

What does setting window location do?

The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.


2 Answers

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.

like image 118
Jason Avatar answered Oct 27 '22 02:10

Jason


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: '');
}
like image 20
giammin Avatar answered Oct 27 '22 02:10

giammin