DEV Community

loading...

Electron Adventures: Episode 2: Frontend Code and Backend Code

Tomasz Wegrzanowski
Updated on ・2 min read

An Electron app is sort of two apps in one. There's the frontend app controlling the frontend, and the backend app controlling the backend, and they communicate like they're two separate programs.

We already wrote a small backend app in the previous episode, so let's build a simple frontend app as well.

Of course we can use fancy web frameworks like Svelte, Imba, or React, but we're going to use plain old Javascript for now.

index.html

Let's get some interaction going - the simplest kind. Just a button and a counter how many times you've pressed it.

<!DOCTYPE html>
<html>
  <body>
    <h1>Welcome to the Internet!</h1>
    <div id="counter"></div>
    <button>Click me</button>
    <script src="app.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

app.js

Now let's write some app.js to control the counter. This isn't anything Electron specific, just classic Javascript.

let counter = 0
let div = document.querySelector("#counter")
let button = document.querySelector("button")

let updateCounter = () => {
  div.innerHTML = `You clicked the button ${counter} times`
}

button.addEventListener("click", () => {
  counter++
  updateCounter()
})

updateCounter()
Enter fullscreen mode Exit fullscreen mode

The result

And here's what we got:

Alt Text

All the code for the episode is here.

In the next episode we'll talk about how we can communicate between the frontend and the backend.

Security

But before you go, let's talk about security.

Frontend and backend code have very different security models.

  • backend code has full access to your computer, but it assumes you only run code you trust
  • frontend code just runs anyone's code from random sites on the internet, but it has (almost) no access to anything outside the browser, and even in-browser, (almost) only to stuff from the same domain

Writing Electron apps we need to be very careful that we don't mix those two things, or you'll be giving strangers full access to your machine, and that would be bad.

Anyway, see you in the next episode.

Discussion (0)