Electron js,如何将变量从main.js传递到html模板?

ff29svar  于 2023-08-01  发布在  Electron
关注(0)|答案(1)|浏览(206)

我是JavaScript和electron js的初学者。我正在创建一个待办事项列表管理器。我试图通过这个列表的标题检索sqlite todos.db,并填充它在一个选择菜单。我不知道如何将从数据库检索到的变量传递到HTML渲染页面。当我真正点击相应的按钮时,列表会填充一秒钟,然后消失。需要一些指导。
main.js的代码片段:

const { app, BrowserWindow, ipcMain } = require('electron');
const path = require('path');
const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('todos.db');

ipcMain.on("deleteList", (event, data) => {
        db.all('SELECT title FROM lists', [], function (error, rows) {
        if (error) {
            console.error(error);
        return;
        }
        const listNames = rows.map(row => row.title);
        mainWindow.webContents.send("listNames", listNames);
        mainWindow.loadFile(path.join(__dirname, 'delete-list.html'));
        console.log("main js working");
    
        });
    });

字符串
index.js的片段:

const ipcRenderer = require('electron').ipcRenderer;

ipcRenderer.on("listNames", (event, listNames) => {
  const listSelect = document.getElementById("list-select");
  console.log("index.js working")

  listNames.forEach(listName => {
    const option = document.createElement("option");
    option.text = listName;
    option.value = listName;
    listSelect.appendChild(option);
  });
});


delete-list.html:

<!DOCTYPE html>
<html>

<head>
  <title>Task Master</title>
  <link rel="stylesheet" type="text/css" href="index.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Jost:wght@200&display=swap" rel="stylesheet">
  <script src="index.js" type="text/javascript"></script>
</head>

<body>
  <div class="main">
    <div class="header">
      <h2 id="heading">Task Master V1.0</h2>
    </div>
    <div class="operations">
      <select id="list-select">
        <option disabled selected>Select the list</option>
      </select>
      <button onclick="deleteList()" id="submit">Delete</button>
      <button id="home" onclick="window.location.href = 'index.html';">Back To Home</button>
    </div>
  </div>
  
</body>

</html>

xbp102n0

xbp102n01#

我认为问题是这样的:

mainWindow.webContents.send("listNames", listNames);

mainWindow.loadFile(path.join(__dirname, 'delete-list.html'));

字符串
您通过以下方式填充列表

mainWindow.webContents.send("listNames", listNames);


然后重新加载文件,通过以下方式有效地删除列表

mainWindow.loadFile(path.join(__dirname, 'delete-list.html'));


尝试像这样切换:

mainWindow.loadFile(path.join(__dirname, 'delete-list.html'));

mainWindow.webContents.send("listNames", listNames);


请记住,发送可能会在html页面完成加载之前触发。
例如,你可以在delete-list.html中获取页面加载时的列表名
希望这对你有帮助!

相关问题