-1

I have a variable that gets the server url:

var server = parent.Xrm.Page.context.getClientUrl();

I want to be able to console log different things based on the server URL so created an if created an if condition:

if(server = "www.homemysiteserver.com"){
  console.log("home page");
} else if(server = "www.aboutmysiteserver.com"){
  console.log("about page");
} else if(server = "www.infomysiteserver.com"){
  console.log("about page");
}

However this doesn't work. I'm not sure what I'm doing wrong

T.Doe
  • 1,969
  • 8
  • 27
  • 46
  • 1
    is that valid one `parent.Xrm.Page.context.getClientUrl();` .Whats they are return ? .For condition use `===` instead of `=` – prasanth Nov 14 '19 at 11:46
  • You might also need the protocol. Also I second the above, what's wrong with window.location.href – TommyBs Nov 14 '19 at 11:48
  • In javascript compaire two values if (x === y) – Edwin Nov 14 '19 at 11:48
  • @prasanth parent.Xrm.Page.context.getClientUrl(); is valid and produces the correct result. – T.Doe Nov 14 '19 at 11:50
  • `=` is for [assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators), `==` or `===` is the [comparison operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators) – Liam Nov 14 '19 at 11:53

2 Answers2

1

You should use strict equal to ensure that the server string is equal to a given value and of the same type. More info here.

So instead of doing

if(server = "www.homemysiteserver.com")

you should be doing this

if(server === "www.homemysiteserver.com")

Also in case you want to simply to obtain the host url you can use the following:

window.location.hostname and this will give you homemysiteserver.com or any other value according to the url.

The same applies to all the other validations you are doing.

Hugo Barona
  • 1,303
  • 9
  • 21
1

As both Hugo Barona and Liam have pointed out, the original issue was that you were trying to compare the server names using the assignment operator =, instead of the comparison operators == or ===. The difference between these is very well explained in the answers to this question. (as a rule of thumb, use === for strings)

In order to get the server URL (commonly referred to as hostname), you can use the global window property. This has a property window.location.hostname, which will return for instance stackoverflow.com.

var hostname= window.location.hostname;

if(hostname === "www.homemysiteserver.com"){
  console.log("home page");
} else if(hostname === "www.aboutmysiteserver.com"){
  console.log("about page");
} else if(hostname === "www.infomysiteserver.com"){
  console.log("about page");
}

Do note that the returned value may not include www. or http://, so your use of var server = parent.Xrm.Page.context.getClientUrl(); is likely more consistent for you situation.

Liam
  • 27,717
  • 28
  • 128
  • 190
J Lewis
  • 462
  • 1
  • 4
  • 15