将点击事件侦听器添加到电子应用程序中的元素

时间:2019-07-23 02:41:18

标签: javascript node.js electron

错误:启动电子应用程序时未定义文档

我试图做到这一点,以便当有人单击p元素时,我的js文件中用于运行电子东西的函数会打开一个新的电子窗口,但它一直在说未定义文档。

这是我的index.html(主要电子应用文件)

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>DTE</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/p5.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/addons/p5.dom.min.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.8.0/addons/p5.sound.min.js"></script>
    <script type="text/javascript" src="Entery.js"></script>
    <script type="text/javascript" src="index.js"></script>
</head>

<body style="margin: 0px; background-color: black">
    <div style="position: absolute; bottom: 39px;width: 100vw; height: 1px; background-color:white;"></div>
    <p id="commands" onclick="displayCommands()" style="position: absolute; bottom: -5px; left: 50%; transform: translateX(-50%);font-family: 'Roboto'; color: white;font-weight: 300;">Commands</p>
</body>

这是我的电子js文件

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

const { app, BrowserWindow, Menu } = electron;

let mainWindow;
let commandWindow;

app.on('ready', () => {

    mainWindow = new BrowserWindow();
    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'index.html'),
        protocol: 'file:',
        slashes: true
    }));
    Menu.setApplicationMenu(null);
    document.querySelector('#commands').addEventListener('click', () => {
        displayCommands();
    })
});

displayCommands = () => {
    commandWindow = new BrowserWindow({
        width: 300,
        height: 500,
        title: 'Avaliable Commands',

    });
    commandWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'commands.html'),
        protocol: 'file:',
        slashes: true
    }));
}

每次我运行它时都会弹出一个错误:

ReferenceError: document is not defined
   at App.<anonymous> (DIRECTORY_TO_ENTERY.JS:25:5)
   at App.emit (events.js:199:15)```

1 个答案:

答案 0 :(得分:0)

您不能在电子的主要过程中访问DOM(文档),而只能在其所属的渲染器中访问。请阅读以获取更多信息How to access DOM elements in electron?