You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron程序如何实现关闭时记录当前URL并在下次启动自动加载

实现方案

你可以直接使用Node.js内置的文件读写能力,将历史URL存储在Electron默认的用户数据目录下,无需引入额外第三方依赖,修改逻辑如下:

  • 应用启动时读取本地存储的历史URL,校验合法则加载,否则加载默认地址
  • 应用退出前自动获取当前窗口加载的URL,写入本地存储文件

修改后的完整主进程代码

// Modules to control application life and create native browser window.
const { app, BrowserWindow, Menu } = require("electron");
const fs = require('fs');
const path = require('path');

// 定义默认加载地址
const DEFAULT_URL = "https://google.com";
// 历史URL存储文件路径,存放在应用专属用户数据目录
const HISTORY_URL_PATH = path.join(app.getPath('userData'), 'last-url.txt');

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

// 读取上次保存的URL
function getLastUrl() {
  try {
    if (fs.existsSync(HISTORY_URL_PATH)) {
      const savedUrl = fs.readFileSync(HISTORY_URL_PATH, 'utf8').trim();
      return savedUrl.startsWith('http') ? savedUrl : DEFAULT_URL;
    }
  } catch (err) {
    // 读取失败直接返回默认地址即可
  }
  return DEFAULT_URL;
}

// 保存当前窗口的URL到本地
function saveCurrentUrl() {
  try {
    if (mainWindow && mainWindow.webContents) {
      const currentUrl = mainWindow.webContents.getURL();
      fs.writeFileSync(HISTORY_URL_PATH, currentUrl, 'utf8');
    }
  } catch (err) {
    // 保存失败不做处理,下次启动自动加载默认地址
  }
}

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    frame: false,
    webPreferences: {
      preload: `${__dirname}/preload.js`
    }
  });

  // 优先加载上次保存的URL,无历史记录则加载默认地址
  mainWindow.loadURL(getLastUrl());

  // Emitted when the window is closed.
  mainWindow.on("closed", function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
}

// The toggleFullScreen function stated in the createMainMenu function.
function toggleFullscreen() {
    if (mainWindow.isFullScreen()) {
        mainWindow.setFullScreen(false);
    } else {
        mainWindow.setFullScreen(true);
    }
}

function createMainMenu() {
  const template = [
    {
      label: "Options",
      submenu: 
      [
        {
            label: "Quit",
            accelerator: "CmdOrCtrl+Q",
            click() {
              app.quit();
          }
        },
        {
            label: 'Toggle full screen',
            accelerator: 'CmdOrCtrl+F',
            click: () => {
            toggleFullscreen();
          }
        },
        {
            label: 'Toggle developer tools',
            accelerator: 'CmdOrCtrl+I',
            click(item, focusedWindow){
              focusedWindow.toggleDevTools();
          }
        }
      ]
    }
  ];

  const menu = Menu.buildFromTemplate(template);
  Menu.setApplicationMenu(menu);
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", () => {
  createWindow();
  createMainMenu();
});

// 应用退出前保存当前URL
app.on('will-quit', saveCurrentUrl);

// Quit when all windows are closed.
app.on("window-all-closed", function() {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q.
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", function() {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) {
    createWindow();
  }
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.

补充说明

  • 存储文件默认保存在Windows系统下的C:\Users\你的用户名\AppData\Roaming\你的应用名\last-url.txt路径下
  • 代码自带URL合法性校验,就算存储文件被篡改,也会自动回退到默认地址,不会影响应用启动

内容的提问来源于stack exchange,提问作者Kurbey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 17:57:03