2010-10-13 134 views

回答

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

添加的 'https:' 情況下,也,你會很開心。 – Blackcoat 2010-10-13 05:09:08

+1

這是不正確的。一個站點可以在本地託管,並且在本地託管在Web服務器上時仍然使用'http'協議。 – Nes 2017-09-27 06:28:01

1

其他的方法可以做到這一點:

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

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

或(slow,不推薦)

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