为什么我在本地主机上的 Chrome 中收到 getCurrentPosition() 和 watchPosition() "insecure origins" 错误?

Why do I get a getCurrentPosition() and watchPosition() "insecure origins" error in Chrome on localhost?

我正在本地开发环境 (Ubuntu 16.04) 上开发网站,并通过 http://localhost.example/ 在 Chrome (58) 上测试网站 - 它连接到本地网络服务器。

运行 这个 Javascript:

$(document).ready(function() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
});

触发此错误:

[Deprecation] getCurrentPosition() and watchPosition() no longer work on insecure origins. To use this feature, you should consider switching your application to a secure origin, such as HTTPS. See https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins for more details.

这是为什么?我知道面向 public 的网站需要 运行 HTTPS 才能使地理定位库/功能正常工作。我们有许多 public 个网站 运行 跨 HTTPS 的类似代码。

然而根据depreciation documentation

localhost is treated as a secure origin over HTTP, so if you're able to run your server from localhost, you should be able to test the feature on that server.

上面的 Javascript 是 运行 内嵌在通过 http://localhost.example/test-page/ 加载的 HTML 正文中 - 那么为什么我会收到 "insecure origins" 错误Chrome?

Firefox (53) 按预期显示在浏览器中访问位置提示。

SSL over HTTP 协议确保客户端和服务器之间的私密通信。信息在传输过程中可能会通过专用网络传输。网络上的任何第三方(黑客)都可以窃取该信息。为避免浏览器强制用户使用安全连接。

在本地服务器上,信息不会超出我们的私人本地网络,因为不需要这种安全措施。所以我们可以期望浏览器允许在本地服务器上不使用 SSL 进行地理定位。理想情况下,浏览器开发人员应该跳过本地主机和 127.0.0.1 或类似来源的验证。

必须有一些技巧可以避免此类问题,即您可以在本地服务器上安装自签名 SSL 证书,或者您可以编辑 Chrome 配置文件以允许域访问地理定位、网络摄像头等。

有用的链接,

https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-powerful-features-on-insecure-origins

https://ngrok.com/

Chrome 认为 localhost over http 是安全的。当您在 http 上使用 hostnme localhost.example 时,这被认为是不安全的。

注意:Firefox 的行为与 Firefox 55 类似