使用本地 HTTPS

出于安全考虑,Service Workers 只能通过安全连接进行注册(localhost 上的本地开发除外)。在某些项目设置中,你可能需要通过 HTTPS 运行本地应用,并且在启动 MSW 的工作程序时很快就会遇到以下错误:

¥Due to security considerations, Service Workers can only be registered over a secure connection (exception being the local development on localhost). In some project setups, you may require to run your local application over HTTPS and will shortly encouter the following error when starting MSW’s worker:

SecurityError: Failed to register a ServiceWorker:
  An SSL certificate error occurred when fetching the script.

发生此错误是因为你的浏览器不信任你的自签名证书。因此,浏览器将阻止 Service Worker 注册尝试,并且 MSW 将不起作用。

¥This error occurs because your browser will not trust your self-signed certificate. As a result of it, the browser will block the Service Worker registration attempt and MSW will not work.

要使用具有本地 HTTPS 设置的库,你必须让浏览器信任你的自签名证书。这可以通过下面描述的多种方式实现。

¥To use the library with a local HTTPS setup you must make your browser trust your self-signed certificate. This can be achieve in multiple ways described below.

在系统级别信任证书

¥Trust certificate on system level

你可以将自签名证书添加到系统的受信任证书中。请参考相应的在线资源,了解如何根据你的操作系统执行此操作。

¥You can add your self-signed certificate to the system’s trusted certificates. Please refer to the respective resources online on how to do so based on your operating system.

在浏览器级别信任证书

¥Trust certificate on browser level

Chrome / Brave

  1. 打开 chrome://flags(如果使用 Brave,则打开 brave://flags);

    ¥Open chrome://flags (or brave://flags if using Brave);

  2. 在列表中搜索 unsafely-treat-insecure-origin-as-secure 标志;

    ¥Search for unsafely-treat-insecure-origin-as-secure flag in the list;

  3. 选择标志旁边的 “已启用” 选项。

    ¥Select the “Enabled” option next to the flag.

  4. 在字段中输入你的本地主机。

    ¥Enter your local host into the field.

如果遇到证书获取/验证问题,请将 ignore-certificate-errors 标志设置为 “已启用”。

¥If encountering certificate fetching/validation issues, set the ignore-certificate-errors flag to “Enabled”.

Firefox

  1. 打开由 HTTPS 提供服务的本地应用;

    ¥Open your local application served by HTTPS;

  2. 在 “连接不安全” 屏幕上单击 “高级” 按钮;

    ¥On the “Connection is not secure” screen click the “Advanced” button;

  3. 在下面的部分中,单击 “添加异常” 按钮。

    ¥In the section below, click the “Add Exception” button.

  4. 将你的应用的 URL 指定为 “位置” 输入值;

    ¥Specify your application’s URL as the “Location” input value;

  5. 单击 “确认安全异常” 按钮。

    ¥Click the “Confirm Security Exception” button.

Safari

我们不知道有任何设置可以让 Safari 信任自签名证书。考虑在 MacOS 上启用 系统范围的信任

¥We are not aware of any settings to make Safari trust self-seigned certificates. Consider enabling System-wide trust on MacOS instead.