【发布时间】:2019-08-07 18:25:34
【问题描述】:
我想知道如何制作一个显示一次然后不再显示的页面,或者在您首次启动它时像 Visual Studio 代码一样制作一个“不再显示我”复选框。
【问题讨论】:
-
使用 localStorage 修复
标签: javascript html web electron
我想知道如何制作一个显示一次然后不再显示的页面,或者在您首次启动它时像 Visual Studio 代码一样制作一个“不再显示我”复选框。
【问题讨论】:
标签: javascript html web electron
你可以使用localStorage:
//Place this code in your electron app's initialisation
if (localStorage.getItem("showStartUpWindow") == "No") {
//Show main window
} else {
//Show startup window and wait until the "OK" button is clicked
if (doNotShowStartUpWindowCheckBox.checked) {
localStorage.setItem("showStartUpWindow", "No");
}
}
【讨论】:
使用 localStorage 的问题
问题是当应用程序被删除时,使用 localStorage 存储的数据可以继续保留
C:\Users\%USERNAME%\AppData\Roaming\Atom
包含 localDB、indexedDB 和一些其他缓存的东西
使用其他方式保存数据
我认为您可以将数据保存在 JSON 文件或任何配置文件文本中,在这种情况下,创建一个 json 文件(在任何路径中)
javascript
const electron = require('electron');
const path = require('path');
const fs = require('fs');
class Store {
constructor(opts) {
// Renderer process has to get `app` module via `remote`, whereas the main process can get it directly
// app.getPath('userData') will return a string of the user's app data directory path.
const userDataPath = (electron.app || electron.remote.app).getPath('userData');
// We'll use the `configName` property to set the file name and path.join to bring it all together as a string
this.path = path.join(userDataPath, opts.configName + '.json');
this.data = parseDataFile(this.path, opts.defaults);
}
// This will just return the property on the `data` object
get(key) {
return this.data[key];
}
// ...and this will set it
set(key, val) {
this.data[key] = val;
// Wait, I thought using the node.js' synchronous APIs was bad form?
// We're not writing a server so there's not nearly the same IO demand on the process
// Also if we used an async API and our app was quit before the asynchronous write had a chance to complete,
// we might lose that data. Note that in a real app, we would try/catch this.
fs.writeFileSync(this.path, JSON.stringify(this.data));
}
}
function parseDataFile(filePath, defaults) {
// We'll try/catch it in case the file doesn't exist yet, which will be the case on the first application run.
// `fs.readFileSync` will return a JSON string which we then parse into a Javascript object
try {
return JSON.parse(fs.readFileSync(filePath));
} catch(error) {
// if there was some kind of error, return the passed in defaults instead.
return defaults;
}
}
// expose the class
module.exports = Store;
第一次创建文件,如果配置文件中存在此值,是否可以验证该文件
javascript
const { app, BrowserWindow } = require('electron');
const path = require('path');
const Store = require('./store.js');
let mainWindow; //do this so that the window object doesn't get GC'd
// First instantiate the class
const store = new Store({
configName: 'user-preferences',
defaults: {
initialLaunch: true
}
});
获取该值并处理它
let { initialLaunch } = store.get('initialLaunch');
if(initialLaunch){
//show initial config window
}else{
//show other window
}
【讨论】: