如何在退出时删除所有 Electron bloatware?

How to remove all Electron bloatware on exit?

当电子应用程序退出时,如何从“AppData\roaming\MyApp”文件夹中删除 cookie、本地存储和其他废话?

我尝试在应用程序退出时删除整个目录,但它会抛出 EBUSY 错误。显然文件被锁定了或什么的,几乎就像有人不希望我们能够消除膨胀?

const fs = require('fs-extra');

const clearBloat = async () => fs.remove(path.join(app.getPath('appData'), app.name));

app.on('window-all-closed', async () => {
  await clearBloat();
});

经过一些测试,我发现您必须在 电子进程结束后删除文件 (尝试在 quitwill-quit app events 不会删除 files/folders;他们会立即得到 re-created。Electron 中的某些东西(可能是 Chromium)希望这些 files/folders 在应用程序 运行 存在时存在,并且弄清楚如何挂钩它的工作太多了) .

对我有用的是从等待 3 秒的 shell 生成一个分离的 cmd,然后删除给定应用程序文件夹中的所有 files/folders。 reader 之前的练习是隐藏 ping 命令的输出(或隐藏 window,但有 mixed success on that front), or choose a different command. I've found timeout works, but sleep and choice (ie. something like this)做 工作。

以下是您需要添加的内容:

const { app } = require("electron");
const { spawn } = require("child_process");
const path = require("path");

...

app.on("will-quit", async (event) => {
  const folder = path.join(app.getPath("appData"), app.name);

  // Wait 3 seconds, navigate into your app folder and delete all files/folders
  const cmd = `ping localhost -n 3 > nul 2>&1 && pushd "${folder}" && (rd /s /q "${folder}" 2>nul & popd)`;
  
  // shell = true prevents EONENT errors
  // stdio = ignore allows the pipes to continue processing w/o handling command output
  // detached = true allows the command to run once your app is [completely] shut down
  const process = spawn(cmd, { shell: true, stdio: "ignore", detached: true });

  // Prevents the parent process from waiting for the child (this) process to finish
  process.unref();
});

正如另一位用户提到的,a method available on your electron session 是原生的 API,它清除了所有这些 files/folders。但是,它 returns 是一个承诺,我无法弄清楚如何在其中一个 app-events.

中同步执行它

Reference #1