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

时间:2010-10-13 04:59:42

标签: javascript

我是javascript的新手。如何检测我的javascript是从网站(http://)运行到本地文件。

4 个答案:

答案 0 :(得分:60)

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

答案 1 :(得分: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
}

答案 2 :(得分:1)

要一次测试不同的“本地”种类:

// Returns the page location type
// 0 (falsey) = Local file, direct from disk (file://path/to/file.html)
// 1 (truthy) = Virtually remote file, from local server (http://localhost)
// 2 (truthy) = Remote file from remote server (http://example.com)

function locationType(){
    if( window.location.protocol == 'file:' ){ return 0; }
    if( !window.location.host.replace( /localhost|127\.0\.0\.1/i, '' ) ){ return 2; }
    return 1;
}

合理的价格:您可能要测试页面是否是a)在远程服务器上,或b)在本地服务器(同一台计算机上进行测试,例如使用AMP),或c)本地文件(直接检索)从磁盘通过“ file://”协议。

请注意,这不能处理所有可能的边缘情况。例如,您可以在技术上将不同的IP重定向到“ localhost”,而其他非“ file://”方案(例如“ foo://”)实际上可能表示本地访问。但是它适用于大多数情况,并且可以根据需要进行调整

仅对“ http”和“ https”进行测试是有一定局限性的,因为在世界范围内,还有许多其他的LAN和WAN网络方案正在使用。当然,它们是本地的还是甚至可以使用HTML / JS代码也可能有所不同(IANA URI Schemes)。

答案 3 :(得分:1)

与@Beejor相比,我使用了稍微修改的版本,该版本也处理可能的端口。它允许为e设置基数uriHost。 G。如果以本地文件而不是通过SSH隧道或直接通过IP:Port运行,则ajax / jquery请求可能需要主机部分。检测部分处于if-else条件。

var uriHost = "";
if (window.location.protocol === "file:") {
  console.log("Running as local file!");
  // like: file://<path>/index.html
  uriHost = "http://<my-host-or-ip>:<my-port>";
} else if (
  !window.location.host.replace(/(localhost|127\.0\.0\.1)(:\d+)?/i, "")
) {
  console.log("Running on local server (ssh tunnel etc.)");
  // like: "http://127.0.0.1:<my-port>"
} else {
  console.log("Running normally, via web server");
  // like: "http://<my-host-or-ip>:<my-port>"
}
// now do something with uriHost, e.g. for ajax uris etc.

要检查是否作为本地文件(即file://)运行,仅检查window.location.protocol === "file:"就足够了。