Utilizing Node and Electron to dynamically adjust CSS style properties

Having a dilemma here: I need to access the CSS properties from styles.css within Electron. Trying to use

document.getElementsByClassName()
won't work because Node doesn't have document. The goal is to change the color of a specific div when the q key is pressed. Below is the code snippet:

index.js

const url = require('url');
const path = require('path');

const {app, BrowserWindow, globalShortcut} = require('electron');
let mainWindow;

app.on('ready', function(){
    // Create new window
    mainWindow = new BrowserWindow({backgroundColor: '#000000', fullscreen : true, frame : false});
    // Load html in window
    mainWindow.loadURL(url.format({
      pathname: path.join(__dirname, 'index.html'),
      protocol: 'file:',
      slashes:true
    }))
    globalShortcut.register('Esc', () => {
        app.quit();
    });
    globalShortcut.register('q', () => {
      leftLight();
  });

});


//This doesn't work
function leftLight() {
  var element =   ;
  element.style["background-color"] = "yellow";
}

index.html

<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">

<head>
    <link rel="stylesheet" href="styles.css">
    <title>Document</title>
</head>
<body>
    <div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
    <div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
    <div class = crono> <h2 class=blocktext>3:00</h2></div>
</body>
</html>

styles.css

.rect_green {
  display: flex;
  align-items: center;
  height: 400px;
  width:60%;
  background-color: green;
  position:relative;
  top:100px;
  text-align: center;

}

.rect_red {
  display: flex;
  align-items: center;
  height:400px;
  width:60%;
  background-color: red;
  position:relative;
  top:120px;
  float:right;
}

.crono {
  display: flex;
  align-items: center;
  height:300px;
  width:40%;
  background-color: beige;
  position:fixed;
  left: 50%;
  bottom : 50px;
  transform: translate(-50%, 0px);
  margin: 0 auto;
}

.blocktext {
  margin-left: auto;
  margin-right: auto;
  font-family: "Palatino", Times, serif;
  font-size: 180px;
}

Edit

Following some changes suggested by Gr8Miller (yet still no luck): index.html

<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">

<head>
    <link rel="stylesheet" href="styles.css">
    <title>Document</title>
</head>
<body>
    <div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
    <div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
    <div class = crono> <h2 class=blocktext>3:00</h2></div>
</body>

<script type="text/javascript">
        var ipc = require('electron').ipcRenderer;
        ipc.on('key-pressed-q', (e) => {
            //var element =  document.getElementsByClassName("rect_green");
            //element.style["background-color"] = "yellow";
            console.log("q pressed in html file");    
        });
    </script>

</html>

And index.js

const url = require('url');
const path = require('path');

const {app, BrowserWindow, globalShortcut, ipcMain, webContents} = require('electron');
let mainWindow;

app.on('ready', function(){
    // Create new window
    mainWindow = new BrowserWindow({
      backgroundColor: '#000000',
      fullscreen : true, 
      frame : false,
      icon : __dirname + "/res/icon.jpg",
      webPreferences: {
         nodeIntegration : true
       }
    });
    // Load html in window
    mainWindow.loadURL(url.format({
      pathname: path.join(__dirname, 'index.html'),
      protocol: 'file:',
      slashes:true
    }))
    globalShortcut.register('Esc', () => {
        app.quit();
    });
    globalShortcut.register('q', () => {
        leftLight();

  });

});

function leftLight() {
  mainWindow && mainWindow.webContents.send('key-pressed-q');
  console.log("Sending q pressed to html...");
}

Answer №1

Similar question can be found at this link.

To resolve this issue, consider creating a new JavaScript file with your code and then load it as a script in your HTML document.

You can add the following line to your index.html:

<script type="text/javascript" charset="utf8" src="./pageScript.js"></script>

Next, create a separate pageScript.js file where you can include your code like this:

window.onload = function () {
    // Your code goes here
    function leftLight() {
        var element = ;
        element.style["background-color"] = "yellow";
    }

    // Make sure to call the function
    leftLight();
}

Answer №2

Handling of view related tasks in Electron:

When working with Electron, it's important to understand that the entry JavaScript file (such as index.js) runs in the main process, acting as the manager for all browser windows it creates. The browser window itself runs in the render process where HTML elements and imported/embedded JavaScript code are executed. This means that the document object can only be directly accessed in the render process.

In scenarios like yours, where style changes need to be applied dynamically, it is best practice to perform these tasks in the render process:

  1. Send a message (e.g. key-pressed-q) from the main process to the render process when a specific key (like q) is pressed:
  2. Update the style in the render process upon receiving the message (key-pressed-q):

index.js

    mainWindow = new BrowserWindow({
        backgroundColor: '#000000', 
        fullscreen : true, 
        frame : false, 
        webPreferences: {
            nodeIntegration: true
        }});
    ...
    function leftLight() {
        mainWindow && mainWindow.webContents.send('key-pressed-q');
    }

index.html

    ...
    <script type="text/javascript">
    var ipc = require('electron').ipcRenderer;
    ipc.on('key-pressed-q', (e) => {
        console.log(e);
        var element = document.querySelector(".rect_green");
        element.style.backgroundColor = "yellow";
    });
    </script>
    ...

Updated on 2019-11-18

Aside from Electron-specific considerations, there are also other errors in your code related to basic HTML principles:

//var element =  document.getElementsByClassName("rect_green");
//element.style["background-color"] = "yellow";

The function getElementsByClassName returns an array of Elements, not a single Element. Additionally, the correct property for setting background color is backgroundColor, not background-color.

Furthermore, keep in mind that the console.log statements in the render process will not output logs to the main process's console. To view these logs, you'll need to open the DevTools of the browser window hosting the render process.

  // in your `index.js`

  // Open the DevTools.
  mainWindow.webContents.openDevTools(); // `console.log` in `index.html` will be shown in its own console.
  // in your `index.html`

var ipc = require('electron').ipcRenderer;
ipc.on('key-pressed-q', (e) => {
  var element = document.querySelector(".rect_green");
  element.style.backgroundColor = "yellow";
  console.log("q pressed in html file");   // this log won't appear in the main process's console.
});

Answer №3

Revise your index.html with the following changes :

<!DOCTYPE html>
<html lang="en">
<meta name="viewport" content="width=device-width, initial-scale=1">

<head>
    <link rel="stylesheet" href="styles.css">
    <title>Document</title>
</head>
<body>
    <div class = rect_green> <h2 class=blocktext >LEFT FENCER</h2></div>
    <div class = rect_red><h2 class=blocktext> RIGHT FENCER</h2> </div>
    <div class = crono> <h2 class=blocktext>3:00</h2></div>
    <script>
      function leftLight() {
        const element = document.getElementsByClassName("yourclassname")
        element[0].style.color = "red"
      }
      window.onkeydown = function(e) {
        if (e.key == "q") {
          leftLight()
        }
      }
    </script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Out of nowhere, JavaScript/jQuery ceased to function

Everything was running smoothly on my website with jQuery Ui until I changed the color, and suddenly everything stopped working. Any ideas why this happened? I even tried writing the JavaScript within the HTML file and linking it as a separate .js file, bu ...

Harness the power of ng-click in conjunction with data-ng-href for a

I am attempting to create a button that takes the user to the product details while also having the ability to increase a counter using an ng-click function. <div class="row center-block save-button" > <a data-ng-href="/savings/{{saving._id}} ...

Listening for server updates with jQuery

I am currently working on a web application that communicates with a server for database updates. The issue I am facing is that the update process can vary greatly in time, ranging from milliseconds to tens of seconds for larger updates. I would like to im ...

Seeking Up/Down Arrows HTML numerical input feature specifically designed for iOS devices

I am having an issue with a number input box on iOS. I am utilizing jquery, kendo mobile, and HTML5 for this particular task. While the number input displays up and down arrows in the Icenium simulator, they are not showing on the iPad. I am seeking a sol ...

Learn the steps for accessing and utilizing aria-label text in Google Chrome

Struggling with the aria-label attribute for blind users in Chrome. Can't seem to hear the aria-label text. Any insights on how aria-label behaves in Chrome or if I'm using the wrong approach? If I'm heading in the wrong direction or using ...

The command to create a new Next.js app using npx, "<project-name>", is currently not functioning as

After entering the command npx create-next-app ., an error message appeared saying: npm ERR! cb.apply is not a function npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\****\AppData\Roaming\npm-cache&bsol ...

No matter how tall I make it, the scroll bar just won't stop showing

Check out this fiddle for more information: http://jsfiddle.net/LAueQ/ Even after increasing the height of the campaignDiv div, the scrollbar keeps showing up. If possible, I would like to avoid using overflow: hidden. ...

Using more than one submit button in an HTML form

I am attempting to include multiple buttons on a single form. I would like to perform different actions on the form depending on which submit button is clicked. <script type="text/javascript> $("#<portlet:namespace/>Form").submit(function( ...

Accessing the background page of a Chrome extension while it's in operation

I am in the process of developing my first chrome extension that allows youtube.com/tv to run in the background so it can be accessed easily on a phone or tablet. Everything is working fine, except for the fact that if I want to watch the video and not j ...

The error "Unable to create an instance of mssql.Schema" indicates that the

Seeking assistance from experienced ReactJS developers to address the issue outlined below. The code provided is based on a tutorial I was following. Despite numerous attempts, I have been unable to resolve the issue. Here is the code snippet from User.js ...

The essential criteria for script tag and page validation requirements

There are instances where I have pages that contain only a script without any content (such as sending data through postMessage and then closing itself). In these cases, is the page considered valid with just <script>doSomeStuff</script> or do ...

Establish a connection between a single EC2 instance running a Node.js application and another EC2 instance acting as a PostgreSQL

Currently, I have two running EC2 instances. One is running a Postgres server and the other is hosting a NodeJS app that needs to connect to the Postgres database. However, it appears that the connection cannot be established as I am unable to ping the P ...

retaining the scroll position of a window when refreshing a div

There's this issue that's been bothering me lately. I update the database via an ajax call, refresh the div, everything works fine, but it still scrolls to the top of the page. Here's what I have attempted: function postdislike(pid, user, ...

Hiding a div becomes impossible once it has been set to display:block

When I click on an element, I want a box to open and then when I click on a "CLOSE" button, I want it to disappear. However, I am encountering an issue where the box appears using "display:block" but does not disappear with "display:none" as intended (see ...

Issue with AngularJS $http not responding to ng-click after first call

My landing controller uses a service that initiates the $http call by default when the App loads. However, I need to pass parameters based on click events, so I implemented an ajax call on ng-click. The issue is that I keep receiving the same data on ng-c ...

Running two different versions of the same React-App concurrently: A step-by-step guide

I currently have a react-app that was created using create react app. There is an older branch that is approximately 1 month old, as well as a current branch. I am interested in running both branches simultaneously and making changes to the current branch ...

Problem with flags series in Highcharts/Highstock

Can anyone help me figure out why not all the flags in the withdrawals series are displaying? For reference, you can view the following JS fiddle: https://jsfiddle.net/lucianpurcarea/5zxa0jsm/13/ The snippet of code below is responsible for creating the d ...

Protractor - Error: prop is undefined

Need assistance in identifying an error. Currently, I am learning Protractor and attempting to create a basic test using Page Object. //login_pageObject.js let loginContainer = function() { this.usernameInput = $("input.login-form-01"); this.passwordInp ...

The table headers in the second table do not match the queryAllSelector

I've encountered an issue with my JavaScript snippet that displays a responsive table. When I use the snippet for a second table with the same class, the formatting gets messed up on mobile devices (try resizing your screen to see). It seems like the ...

Difficulty with font rendering across different web browsers such as Firefox, Chrome, and Opera

Visit the following website: I have implemented font-face on my site: @font-face { font-family: 'SegoeUI'; src: url('{site_url}themes/site_themes/agile_records/fonts/segoeui.eot?') format('eot'), url(' ...