为什么我的服务人员会看到 "Error - Only secure origins are allowed"?

Why am I seeing "Error - Only secure origins are allowed" for my service worker?

当我尝试在我的渐进式 Web 应用程序页面上添加 Service Worker 时,为什么浏览器控制台会显示以下错误?

ERROR "Uncaught (in promise) DOMException: Only secure origins are allowed

JS代码:

(function () {
    'use strict';

    // TODO add service worker code here
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker
            .register('service-worker.js')
            .then(function () {
                console.log('Service Worker Registered');
            });
    }
})();

来自Service Worker FAQ

Q: I get an error message about "Only secure origins are allowed". Why?

A: Service workers are only available to "secure origins" (HTTPS sites, basically) in line with a policy to prefer secure origins for powerful new features. However http://localhost is also considered a secure origin, so if you can, developing on localhost is an easy way to avoid this error.

You can also use the --unsafely-treat-insecure-origin-as-secure command-line flag. This flag must be combined with a --user-data-dir flag. For example:

$ ./chrome --user-data-dir=/tmp/foo --unsafely-treat-insecure-origin-as-secure=http://your.insecure.site

If you want to test on https://localhost with a self-signed certificate, do:

$ ./chrome --allow-insecure-localhost https://localhost

You might also find the --ignore-certificate-errors flag useful.

你可以像这样在注册 service worker 之前检查协议, location.protocol === 'https:' && serviceWorker.register('service-worker.js')

尝试使用 http://127.0.0.1:8080 用于本地托管 代替 http://192.168.29.53:8080

在 chrome 中输入 chrome://flags

搜索"secure origin"

然后单击 已启用,重新启动 chrome。

  1. 类型url

    chrome://flags/#unsafely-treat-insecure-origin-as-secure

  2. 在文本区输入url

  3. 在select选项中选择Enabled look at the image to see detail