处理“ProtocolDeprecateCallback:不再需要协议模块 API 的回调参数”(Electron 7.0)

nos*_*tio 7 javascript electron

升级到 Electron 7.0 后,我注意到此弃用消息:

(node:8308) ProtocolDeprecateCallback: The callback argument of protocol module APIs is no longer needed.
Run Code Online (Sandbox Code Playgroud)

有问题的代码是:

  await new Promise((resolve, reject) => {
    electron.protocol.registerBufferProtocol(MY_PROTOCOL,
      (request, callback) => {
        const uri = request.url;
        if (uri) {
          callback({ mimeType: 'text/plain', data: Buffer.from(uri) });
        }
        else {
          callback({ error: -324 }); // EMPTY_RESPONSE
        }
      },
      error => error? reject(error): resolve()
    );
  });
Run Code Online (Sandbox Code Playgroud)

registerBufferProtocol从 Electron 7 开始,现在正确的调用方式是什么?

nos*_*tio 8

我花了一些时间来弄清楚如何registerBufferProtocol使用 Electron 7.0 正确调用,所以与社区和我未来的自己分享这个。

根据 Electron 的Breaking changes文档,registerBufferProtocol现在是同步的,所以调用它实际上变得更简单了:

  electron.protocol.registerBufferProtocol(MY_PROTOCOL,
    (request, callback) => {
      const uri = request.url;
      if (uri) {
        callback({ mimeType: 'text/plain', data: Buffer.from(uri) });
      }
      else {
        callback({ error: -324 }); // EMPTY_RESPONSE
      }
    });
Run Code Online (Sandbox Code Playgroud)

该警告的混淆(对我)的部分是,callback其实不是callbackARG的handler,而是最后completion传递到ARG protocol.registerBufferProtocolAPI本身。