0

I have a button defined as following

In index.html:

<body>
  <section>
    <button id="open-file">Open File</button>
    ...(series of other similar buttons)...

  </section>
</body>

<script>
    require('./renderer');
</script>

In renderer.js:

const openFileButton = document.querySelector('#open-file');
...

openFileButton.addEventListener('click', () => {
  console.log('You clicked the "Open File" button.');
});

In main.js:

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    show: false,
    webPreferences: {
        nodeIntegration: true
    }
  });
  mainWindow.loadFile('app/index.html');
  ...
});

When I click on that button in the app window, nothing happens in the console. Are there any extra steps I need to add to execute this event listener?

13
  • make sure const openFileButton = document.querySelector('#open-file'); is executed AFTER <button id="open-file">Open File</button> is in the DOM - and check for errors in the browser console Commented Oct 26, 2020 at 8:06
  • 1
    is <button id="open-file">Open File</button> inside a <form> perhaps? Commented Oct 26, 2020 at 8:11
  • 1
    Open dev tools and see what happens or not, i mean/think the render process do not print on stdout Commented Oct 26, 2020 at 8:26
  • 1
    Ah, so it did work all along :D. To answer you question, it is because "The Console method log() outputs a message to the web console." - MDN. The electron app runs in it's own container, so JavaScript cannot log to the linux console. Commented Oct 26, 2020 at 8:51
  • 1
    @TristanTran I think so. You can open the dev tools in the render process with: win.webContents.openDevTools() on the main process. Commented Oct 26, 2020 at 8:56

2 Answers 2

1

In your HTML file, you're using require in your script tag which is a Node.js specific function. Based on what you're expecting, it looks like you would like to link renderer.js to your HTML file. Therefore, link it directly by entering <script src="renderer.js"></script>.

Sign up to request clarification or add additional context in comments.

Comments

1

Have you tried <script src="./renderer.js"></script>? Are you sure your renderer.js runs as intended?

Just to clarify, require() doesn't exist in client-side JavaScript. Open your browsers developer console and you should see that require() isn't defined.

Take a look at MDN script tag documentation for more information how you can include your .js files.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.