如何检测网页是从网站还是本地文件系统运行

问题描述:

我是javascript的新手。我怎样才能检测到我的JavaScript是从一个网站(http://)与本地文件运行。如何检测网页是从网站还是本地文件系统运行

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

其他的方法可以做到这一点:

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 
}