Electron создаёт первую стартовую страницу - PullRequest
0 голосов
/ 17 марта 2019

Я хочу знать, как создать страницу, которая будет отображаться один раз, а затем никогда больше не показываться, или установить флажок «Никогда больше не показывать меня», как код Visual Studio при первом запуске.

Ответы [ 2 ]

2 голосов
/ 17 марта 2019

Вы можете использовать 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");
    }
}
0 голосов
/ 17 марта 2019

Проблема с использованием localStorage

проблема в том, что при удалении приложения данные, сохраненные с помощью localStorage, могут продолжать сохраняться

C:\Users\%USERNAME%\AppData\Roaming\Atom

содержит localDB, indexedDB и несколько других вещей кеша

использовать другой способ сохранения данных

Я думаю, вы можете сохранить данные в файле JSON или любом текстовом файле конфигурации, в этом случае создать файл json (по любому пути)

1020 * 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;

файл создается впервые и существует, если его можно проверить, если это значение существует в файле конфигурации

1025 * 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
}
...