Home > Software engineering >  How to write a script that will be executed only once, when the Electron application starts?
How to write a script that will be executed only once, when the Electron application starts?

Time:02-10

The idea is that on the first run, main-menu.html is loaded into the body element using the custom toPage() function, and later on, the template of the menu item that was clicked. However, the script treats each page refresh as a new load: new content is loaded, but immediately after that, toPage("main-menu") fires and replaces it with the start menu. When writing, the jQuery library is used.

Tried to implement it like this (preload.js):

window.addEventListener('DOMContentLoaded', () => {
    window.$ = window.jQuery = require('jquery')
    toPage("main-menu");
})
function toPage(name) {
    $( "body" ).empty();
    $( "body" ).load(name   ".html", function(id, Element) {
        $( ".button" ).each(function() {
            $("#" this.id ".button").on("click", onFuncs[this.id   'OnClick']);
        })
    })
}
var onFuncs = {
    playOnClick: function () {
        toPage("game-menu");
    },

    preferencesOnClick: function () {
        toPage("preferences");
    },

    exitOnClick: function () {
        window.close();
    }
}

And so (renderer.js, including the jQuery library file in index.html):

function toPage(name) {
    $( "body" ).empty();
    $( "body" ).load(name   ".html", function(id, Element) {
        $( ".button" ).each(function() {
            $("#" this.id ".button").on("click", onFuncs[this.id   'OnClick']);
        })
    })
}
toPage("main-menu");
var onFuncs = {
    playOnClick: function () {
        toPage("game-menu");
    },

    preferencesOnClick: function () {
        toPage("preferences");
    },

    exitOnClick: function () {
        window.close();
    }
}

The result hasn't changed. I tried to set the condition for execution:

if (!$("main").length) toPage("main-menu");

But it is being ignored.

How to properly implement this in Electron?

CodePudding user response:

  •  Tags:  
  • Related