How do I add more than one domain to this alert?

1

Someone can help me because I can only add one domain, and when I try to put more than 1 URL does not work. If anyone can help me I'm grateful!

    if((window.location.href).indexOf('DOMÍNIO') >= 0){
      }else{ // Como faço para adicionar mais de um DOMÍNIO ?
   }

Edit:

I made it this way and the alert worked only on domain 1, when I open the second site the alert appears, can you help me because domain 2 is not being recognized? The following is the model below:

var listaDominios = ["http://www.dominio1.com", "http://www.dominio2.com"];
var dominioValido = listaDominios.find(function(dominio){
    return window.location.href.indexOf(dominio) > -1;
});    

if(dominioValido) {
}else{
alert('Site não autorizado');
}
    
asked by anonymous 24.11.2016 / 23:34

2 answers

0

Better to create an array of domains to avoid else if 's:

var dominios = ["DOMINIO1", "DOMINIO2"];

if(window.location.href.indexOf(dominios) > -1) {
  // faça qualquer coisa
}

Edit: I just realized now that the goal is to have only the domain and not the entire URL. Here is an example:

var listaDominios = ["DOMINIO1", "DOMINIO2"];
var dominioValido = listaDominios.find(function(dominio){
    return window.location.href.indexOf(dominio) > -1;
});    

if(dominioValido) {
  // faça qualquer coisa
}

Edit2: For my failure, you should use Array.prototype.some instead of Array.prototype.find , and use hostname as suggested by @MoshMage:

var listaDominios = ["DOMINIO1", "DOMINIO2"];
var dominioValido = listaDominios.some(function(dominio){
    return window.location.hostname.indexOf(dominio) > -1;
});    

if(dominioValido) {
  // faça qualquer coisa
} else {
  alert('Site não autorizado');
}

Note: In this case subdomains will match with super-domain in the list, if you want to compare at the sub-domain level, replace window.location.hostname.indexOf(dominio) > -1 .

    
24.11.2016 / 23:43
0

You have to have, as @Roberto says, a list of domains:

var dominios = ["dominio1.com", "dominio2.com"];

Then a simple iteration in this array, coupled with window.location.hostname tell yourself if you are (or are not) in this domain:

var dominioNaLista = dominios.some(function(dominio) { return dominio.indexOf(window.location.hostname) > -1 })

After this operation, dominioNaLista is a boolean with the positive or negative value, depending on whether or not you are in a domain contained in the list.

some is a Array that returns true the first time the callback condition is true.

window.location.hostname ( hostname is the key word here) returns the active window domain ( href returns all url ) - window.location.hostname value of this site, pex, is pt.stackoverflow.com

    
25.11.2016 / 02:47