29
我是javascript的新手。我怎樣才能檢測到我的JavaScript是從一個網站(http://)與本地文件運行。如何檢測網頁是從網站還是本地文件系統運行
我是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
}
其他的方法可以做到這一點:
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
}
添加的 'https:' 情況下,也,你會很開心。 – Blackcoat 2010-10-13 05:09:08
這是不正確的。一個站點可以在本地託管,並且在本地託管在Web服務器上時仍然使用'http'協議。 – Nes 2017-09-27 06:28:01