【问题标题】:How can I use JavaScript on the client side to detect if the page was encrypted?如何在客户端使用 JavaScript 来检测页面是否已加密?
【发布时间】:2010-09-21 21:34:32
【问题描述】:

是否可以在客户端检测用户是否在使用加密页面?

换一种说法——我想知道当前页面的URL是以http还是https开头的。

【问题讨论】:

    标签: javascript http https


    【解决方案1】:

    使用window.location.protocol判断是否为https:

    function isSecure()
    {
       return window.location.protocol == 'https:';
    }
    

    如果您没有本地范围的位置,您也可以省略指定“窗口”。

    function isSecure()
    {
       return location.protocol == 'https:';
    }
    

    【讨论】:

    • 窗口。是全局范围,因此不需要,只是一个旁注。
    • 不知道.protocol,比我的解决方案简单
    • jishi:这是一个风格问题,可以说是“窗口”。让房产的来源更加清晰。可以想象,您还可以有一个名为“location”的局部/闭包变量,在这种情况下,对全局的直接访问将被隐藏。
    • 我喜欢完全指定变量的清晰性,但我可以看到其他人可能会在哪里使用速记并使用全局范围。
    • This method 应尽可能使用,因为当证书出现问题时,此答案是不准确的。
    【解决方案2】:

    正如谷歌分析告诉我的那样:

    if ("https:" == document.location.protocol) {
        /* secure */
    } else {
        /* unsecure */
    }
    

    【讨论】:

      【解决方案3】:

      最新浏览器的第二种方法:

      var secure = window.isSecureContext;
      

      或者直接获取 isSecureContext:

      if (isSecureContext) {
         ...
      }
      

      更多:https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#Feature_detection#Feature_detection

      【讨论】:

      • 来自链接页面的警告:“本地交付的文件,例如 http://localhostfile:// 路径被视为已安全交付。”
      猜你喜欢
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      • 2013-11-22
      • 1970-01-01
      • 1970-01-01
      • 2014-07-04
      • 2011-10-28
      • 1970-01-01
      相关资源
      最近更新 更多