添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
瘦瘦的柚子  ·  “On-The-Fly” ...·  3 月前    · 
坚韧的开心果  ·  python 调用 powershell ...·  4 月前    · 
从未表白的电池  ·  ShellProperties.Telnet ...·  10 月前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I am trying to add functionality to a button in index.html file is as follows: I have a button element in index.html

<button id="auth-button">Authorize</button>

In main.js of the app, I have

require('crash-reporter').start();
console.log("oh yaeh!");
var mainWindow = null;
app.on('window-all-closed', function(){
    if(process.platform != 'darwin'){
        app.quit();
app.on('ready',function(){
    mainWindow = new BrowserWindow({width:800, height : 600});
    mainWindow.loadUrl('file://' + __dirname + '/index.html');
    var authButton = document.getElementById("auth-button");
    authButton.addEventListener("click",function(){alert("clicked!");});
    mainWindow.openDevTools();
    mainWindow.on('closed',function(){
        mainWindow = null;

But an error occurs as follows: Uncaught Exception: ReferenceError: document is not defined

Can the DOM objects be accessed while building electron apps? or is there any other alternative way that can give me the required functionality?

The main process doesn't have access to the DOM, it's the renderer that has access. Learn the difference – Ben Fortune Sep 25, 2015 at 11:06

DOM can not be accessed in the main process, only in the renderer that it belongs to.

There is an ipc module, available on main process as well as the renderer process that allows the communication between these two via sync/async messages.

You also can use the remote module to call main process API from the renderer, but there's nothing that would allow you to do it the other way around.

If you need to run something in the main process as a response to user action, use the ipc module to invoke the function, then you can return a result to the renderer, also using ipc.

Code updated to reflect actual (v0.37.8) API, as @Wolfgang suggested in comment, see edit history for deprecated API, if you are stuck with older version of Electron.

Example script in index.html:

var ipc = require('electron').ipcRenderer;
var authButton = document.getElementById('auth-button');
authButton.addEventListener('click', function(){
    ipc.once('actionReply', function(event, response){
        processResponse(response);
    ipc.send('invokeAction', 'someData');

And in the main process:

var ipc = require('electron').ipcMain;
ipc.on('invokeAction', function(event, data){
    var result = processData(data);
    event.sender.send('actionReply', result);
                When I use require in index.html the following error shows up.` Uncaught ReferenceError: require is not defined any idea why?
– ant_1618
                Sep 25, 2015 at 12:32
                It seems you forgot to include the error. I don't currently have access to electron, but I think require() should be available in renderer process. Edit: OK it's now here.
– ROAL
                Sep 25, 2015 at 12:36
                @ROAL: Yes indeed, it is possible to use .once(). Electron's IPC is a standard Node.js EventEmitter. Also, require('ipc') has been depreciated, it's now require('electron').ipcMain and require('electron').ipcRenderer.
– Wolfgang
                May 5, 2016 at 19:20

You can use webContents.executeJavaScript(code[, userGesture, callback]) API to execute JavaScript code.

for example:

mainWindow.loadUrl('file://' + __dirname + '/index.html');
mainWindow.webContents.on('did-finish-load', ()=>{
    let code = `var authButton = document.getElementById("auth-button");
            authButton.addEventListener("click",function(){alert("clicked!");});`;
    mainWindow.webContents.executeJavaScript(code);
  

In Electron, we have several ways to communicate between the main process and renderer processes, such as ipcRenderer and ipcMain modules for sending messages, and the remote module for RPC style communication.

So you can follow the example in https://github.com/electron/electron-api-demos. You should have a js file for each html. In that js file, you can use require anytime you want.

Code in renderer.js:

const ipc = require('electron').ipcRenderer
const asyncMsgBtn = document.getElementById('async-msg')
asyncMsgBtn.addEventListener('click', function () {
  ipc.send('asynchronous-message', 'ping')
ipc.on('asynchronous-reply', function (event, arg) {
  const message = `Asynchronous message reply: ${arg}`
  document.getElementById('async-reply').innerHTML = message

Code in ipc.html:

<script type="text/javascript">
  require('./renderer-process/communication/sync-msg')
  require('./renderer-process/communication/async-msg')
  require('./renderer-process/communication/invisible-msg')
</script>

in my case the window was created by invoking window.open by default electron NodeIntegration is disabled, so you can't access the DOM of the other window. changing the property nativeWindowOpen to true fixed my issue.

// in main.ts
async function createWindow() {
  const win = new BrowserWindow({
    // ....
    webPreferences: {
      nativeWindowOpen: true,

Now i can access the window.document element when i create the window using window.open

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.