2010-10-13 15 views

Respuesta

57
switch(window.location.protocol) { 
    case 'http:': 
    case 'https:': 
    //remote file over http or https 
    break; 
    case 'file:': 
    //local file 
    break; 
    default: 
    //some other protocol 
} 
+2

Añadir un 'https:' caso también , y estarás listo para irte. – Blackcoat

+1

Esto no es verdad. Un sitio puede ser alojado localmente y aún usar el protocolo 'http' cuando está alojado en un servidor web localmente. – Nes

1

Otras maneras de hacer esto:

if (/^h/.test(document.location)) { 
    // remote file over http or https 
} else { 
    // local file 
} 

o

if (document.location.host) { 
    // remote file over http or https 
} else { 
    // local file 
} 

o (slow, no se recomienda)

if ((''+document.location).indexOf('http') === 0) { 
// if (document.location.protocol.indexOf('http') === 0) { // another way 
    // remote file over http or https 
} else { 
    // local file 
} 
Cuestiones relacionadas