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

Asked

Viewed 47 times

1

Someone can help me because I can only add one domain, and when I try to put more than 1 URL it doesn’t 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 did so and the alert worked only in Domain 1, when I open the second site appears the alert, can you help me because Domain 2 is not being recognized? Below is the model:

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');
}

2 answers

0


Better create a domain array to avoid else if's:

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

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

Edit: I just realized that the goal is to have only the domain and not the entire URL. Follow 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: By my fault, you must use the 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 sub-domains will do match with super-domain in the list, if you want to compare to the sub-domain level, replace window.location.hostname.indexOf(dominio) > -1 for window.location.hostname === dominio.

  • You have to review the question Edit?

0

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

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

after a simple iteration on this array, joins with the window.location.hostname tells you whether you are (or not) in that 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 listed domain.

some is a method of Array returning true the first time the callback condition is true.

window.location.hostname (hostname is the keyword here) returns the domain of the active window (href returns whole url) - the value of window.location.hostname of this website, Pex, is pt.stackoverflow.com

Browser other questions tagged

You are not signed in. Login or sign up in order to post.