1 | initial version |
To utilize Electron for loading an external site and store messages in JSON format, you can follow these steps:
Here's a sample code to get started:
const electron = require('electron');
const url = require('url');
const path = require('path');
const request = require('request');
const { app, BrowserWindow, Menu, dialog } = electron;
const fs = require('fs');
// Create a new window
let mainWindow;
app.on('ready', () => {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
// Load the external website
mainWindow.loadURL('https://www.example.com');
// Create a menu template
const menuTemplate = [{
label: 'File',
submenu: [{
label: 'Save JSON',
accelerator: process.platform == 'darwin' ? 'Command+S' : 'Ctrl+S',
click() {
saveJSON();
}
}]
}
];
// Add the menu to the window
const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
// Select page select box
const selectBox = document.getElementById('selectbox');
selectBox.onchange = function() {
const selectedPage = selectBox.value;
request(`https://www.example.com/api/pages/${selectedPage}`, {json: true}, (error, response, body) => {
if (error) {
dialog.showErrorBox('Error', 'Unable to retrieve JSON data.');
} else {
const data = JSON.stringify(body);
fs.writeFile('data.json', data, (err) => {
if (err) {
dialog.showErrorBox('Error', 'Unable to store JSON data.');
} else {
dialog.showMessageBox(mainWindow, {message: 'JSON data has been saved sucessfully.'});
}
});
}
});
}
});
// Function to save JSON data to a local file
function saveJSON() {
dialog.showSaveDialog(mainWindow, {defaultPath: 'data.json'}, (filename) => {
if (filename === undefined) {
dialog.showErrorBox('Error', 'Unable to save JSON data.');
return;
}
fs.readFile('data.json', 'utf-8', (err, data) => {
if (err) {
dialog.showErrorBox('Error', 'Unable to read JSON data.');
} else {
fs.writeFile(filename, data, (err) => {
if (err) {
dialog.showErrorBox('Error', 'Unable to save JSON data.');
} else {
dialog.showMessageBox(mainWindow, {message: 'JSON data has been saved sucessfully.'});
}
});
}
});
});
}
Note that this is just a sample code and you will have to modify it according to your needs.