我正在开发一个简单的电子应用程序来显示我的谷歌议程——为此我使用了谷歌的 node.js 快速入门指南,并尝试用电子/HTML 制作一个图形用户界面。现在我得到了我的数据。我可以使用此功能在我的控制台中编写它:
async function listEvents(auth, win) {
const calendar = google.calendar({version: 'v3', auth});
const res = await calendar.events.list({
calendarId: 'primary',
timeMin: new Date().toISOString(),
maxResults: 10,
singleEvents: true,
orderBy: 'startTime',
});
const events = res.data.items;
if (!events || events.length === 0) {
console.log('No upcoming events found.');
return;
}
console.log('Upcoming 10 events:');
events.map((event, i) => {
const start = event.start.dateTime || event.start.date;
console.log(`${start} - ${event.summary}`);
});
}
然后我使用这个将它存储在一个数组中(我认为):
win.webContents.send('events', events);
接下来在我的 main.js 中我得到了这个:
const { app, BrowserWindow } = require('electron')
const path = require('path')
const { listEvents } = require('./index.js')
const { authorize } = require('./index.js')
let win
async function createWindow () {
// Create the browser window.
win = new BrowserWindow({
width: 1920,
height: 1080,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
})
// and load the index.html of the app.
win.loadFile('index.html')
// Call the listEvents function from index.js
const auth = await authorize();
const events = await listEvents(auth, win);
// Send the events to the renderer process
win.webContents.send('events', events);
}
app.whenReady().then(createWindow)
然后我尝试这样显示它:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GUI</title>
</head>
<body>
<h1>Google Calendar API GUI</h1>
<ul id="events"></ul>
<script>
const { ipcRenderer } = require('electron')
// Listen for the 'events' message from the main process
ipcRenderer.on('events', (event, events) => {
const eventsList = document.getElementById('events');
eventsList.innerHTML = '';
for (const event of events) {
const start = event.start.dateTime || event.start.date;
const li = document.createElement('li');
li.textContent = `${start} - ${event.summary}`;
eventsList.appendChild(li);
}
})
</script>
</body>
</html>
所以现在我该怎么办?我错过了什么,我试过几件事:重命名我的窗口,编辑变量名,因为我认为我可能已经使用了一些我已经在其他地方使用过的变量名。
你只需要从你的
events
函数返回listEvents
async function listEvents(auth, win) {
...
const events = res.data.items;
...
return events;
}
并且不需要更改其余代码。
在
createWindow
您将获得events
并将它们发送到渲染器。
const events = await listEvents(auth, win);
win.webContents.send('events', events);
你会在你的 gui 中显示它们
ipcRenderer.on('events', (e, events) => {
...
for (const event of events) {
...
const li = document.createElement('li');
li.textContent = `${start} - ${event.summary}`;
eventsList.appendChild(li);
}