添加了键代码函数后不起作用的电子API

发布于 2025-02-10 21:39:49 字数 4769 浏览 1 评论 0原文

电子API不起作用。 我会收到以下错误。我看到sendpin函数不起作用。

Uncaught TypeError: Cannot read properties of undefined (reading 'sendPin')
    at HTMLDocument.handlekeyUp (pin-pad:86:28)
pin-pad:61 Uncaught TypeError: Cannot read properties of undefined (reading 'sendPin')
    at HTMLDivElement.<anonymous> (pin-pad:61:28)

它一直在工作,直到我添加了以下代码行,因此我怀疑这可能是主要原因。

if (13 === e.keyCode) { window.electronAPI.sendPin(Pin);

index.html如下。

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="pinpad.css" />

    <meta charset="UTF-8" />
    <title>Electron Test - Pin Pad</title>
    <meta
      http-equiv="Content-Security-Policy"
      content="script-src 'self' 'unsafe-inline';"
    />
  </head>

  <body>
    <div id="container">
      <div id="wrapper">
        <input type="password" id="display" disabled />

        <div id="pin-pad">
          <div data-number="1">1</div>
          <div data-number="2">2</div>
          <div data-number="3">3</div>
          <div data-number="4">4</div>
          <div data-number="5">5</div>
          <div data-number="6">6</div>
          <div data-number="7">7</div>
          <div data-number="8">8</div>
          <div data-number="9">9</div>
          <div>Enter</div>
          <div data-number="0">0</div>
          <div>Clear</div>
        </div>
      </div>
    </div>
  </body>

  <script>
    let display = document.getElementById("display");
    let validKeys = [
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "0",
      "Enter",
      "Clear",
    ];
    let pin = "";

    document.getElementById("pin-pad").addEventListener("click", (event) => {
      if (!validKeys.includes(event.target.innerText)) {
        return;
      }

      if (event.target.innerText === "Enter") {
        window.electronAPI.sendPin(pin);
        return;
      }

      if (event.target.innerText === "Clear") {
        pin = display.value = "";
        return;
      }

      pin = pin + event.target.innerText;
      display.value = "*".repeat(pin.length);
    });

    ///tests
    const handlekeyUp = function (e) {
      e.stopPropagation();

      const input = document.getElementById("display");
      console.log(input, e.key, input.value);
      var reg = new RegExp("^[0-9]$");
      const number = document.querySelector(`[data-number="${e.key}"]`);

      if (reg.test(e.key)) input.value += e.key;
      if (number) number.style.backgroundColor = "#fff";
      if (13 === e.keyCode) {
        window.electronAPI.sendPin(Pin);
      }
    };

    const handleKeyDown = (e) => {
      const number = document.querySelector(`[data-number="${e.key}"]`);
      if (!number) {
        return;
      }
      number.style.backgroundColor = "#eee";
    };

    document.addEventListener("keyup", handlekeyUp);

    document.addEventListener("keydown", handleKeyDown);
  </script>
</html>

main.js

const electronApp = require("electron").app;
const electronBrowserWindow = require("electron").BrowserWindow;
const electronIpcMain = require("electron").ipcMain;

const nodePath = require("path");

// Prevent garbage collection
let window;

function createWindow() {
  const window = new electronBrowserWindow({
    fullscreen: true,
    show: false,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: nodePath.join(__dirname, "preload.js"),
    },
  });

  window.loadFile("pin-pad.html").then(() => {
    window.show();
  });

  return window;
}

electronApp.on("ready", () => {
  window = createWindow();
});

electronApp.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    electronApp.quit();
  }
});

electronApp.on("activate", () => {
  if (electronBrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// ---

electronIpcMain.on("pin", (event, pin) => {
  // Simple check of pin validity
  if (pin === "1234") {
    window.loadFile("sales.html");
  }
});

preload.js如下,我还添加了incase。

const contextBridge = require("electron").contextBridge;
const ipcRenderer = require("electron").ipcRenderer;

contextBridge.exposeInMainWorld("electronAPI", {
  sendPin: (pin) => {
    ipcRenderer.send("pin", pin);
  },
});

Electron API is not working.
I'm getting the following error. I see that the sendPin function is not working.

Uncaught TypeError: Cannot read properties of undefined (reading 'sendPin')
    at HTMLDocument.handlekeyUp (pin-pad:86:28)
pin-pad:61 Uncaught TypeError: Cannot read properties of undefined (reading 'sendPin')
    at HTMLDivElement.<anonymous> (pin-pad:61:28)

It was working until I had added following line of code, for this reason I suspect it may be the main reason.

if (13 === e.keyCode) { window.electronAPI.sendPin(Pin);

index.html is as following.

<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="pinpad.css" />

    <meta charset="UTF-8" />
    <title>Electron Test - Pin Pad</title>
    <meta
      http-equiv="Content-Security-Policy"
      content="script-src 'self' 'unsafe-inline';"
    />
  </head>

  <body>
    <div id="container">
      <div id="wrapper">
        <input type="password" id="display" disabled />

        <div id="pin-pad">
          <div data-number="1">1</div>
          <div data-number="2">2</div>
          <div data-number="3">3</div>
          <div data-number="4">4</div>
          <div data-number="5">5</div>
          <div data-number="6">6</div>
          <div data-number="7">7</div>
          <div data-number="8">8</div>
          <div data-number="9">9</div>
          <div>Enter</div>
          <div data-number="0">0</div>
          <div>Clear</div>
        </div>
      </div>
    </div>
  </body>

  <script>
    let display = document.getElementById("display");
    let validKeys = [
      "1",
      "2",
      "3",
      "4",
      "5",
      "6",
      "7",
      "8",
      "9",
      "0",
      "Enter",
      "Clear",
    ];
    let pin = "";

    document.getElementById("pin-pad").addEventListener("click", (event) => {
      if (!validKeys.includes(event.target.innerText)) {
        return;
      }

      if (event.target.innerText === "Enter") {
        window.electronAPI.sendPin(pin);
        return;
      }

      if (event.target.innerText === "Clear") {
        pin = display.value = "";
        return;
      }

      pin = pin + event.target.innerText;
      display.value = "*".repeat(pin.length);
    });

    ///tests
    const handlekeyUp = function (e) {
      e.stopPropagation();

      const input = document.getElementById("display");
      console.log(input, e.key, input.value);
      var reg = new RegExp("^[0-9]
quot;);
      const number = document.querySelector(`[data-number="${e.key}"]`);

      if (reg.test(e.key)) input.value += e.key;
      if (number) number.style.backgroundColor = "#fff";
      if (13 === e.keyCode) {
        window.electronAPI.sendPin(Pin);
      }
    };

    const handleKeyDown = (e) => {
      const number = document.querySelector(`[data-number="${e.key}"]`);
      if (!number) {
        return;
      }
      number.style.backgroundColor = "#eee";
    };

    document.addEventListener("keyup", handlekeyUp);

    document.addEventListener("keydown", handleKeyDown);
  </script>
</html>

main.js

const electronApp = require("electron").app;
const electronBrowserWindow = require("electron").BrowserWindow;
const electronIpcMain = require("electron").ipcMain;

const nodePath = require("path");

// Prevent garbage collection
let window;

function createWindow() {
  const window = new electronBrowserWindow({
    fullscreen: true,
    show: false,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: nodePath.join(__dirname, "preload.js"),
    },
  });

  window.loadFile("pin-pad.html").then(() => {
    window.show();
  });

  return window;
}

electronApp.on("ready", () => {
  window = createWindow();
});

electronApp.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    electronApp.quit();
  }
});

electronApp.on("activate", () => {
  if (electronBrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

// ---

electronIpcMain.on("pin", (event, pin) => {
  // Simple check of pin validity
  if (pin === "1234") {
    window.loadFile("sales.html");
  }
});

preload.js is as following, I have also added just incase.

const contextBridge = require("electron").contextBridge;
const ipcRenderer = require("electron").ipcRenderer;

contextBridge.exposeInMainWorld("electronAPI", {
  sendPin: (pin) => {
    ipcRenderer.send("pin", pin);
  },
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅忆 2025-02-17 21:39:49

index.html中,在中,如果(13 === e.KeyCode){...}语句,window.electronapi的参数.sendpin(...);调用是错误的情况。它应该是PIN,应该是PIN

也就是说,pin在您的const handlekeyup = function(e){...}函数中未更新,因此按下“ enter”(或“返回”)时。 ,它无法将更新的PIN发送到您的渲染过程。

仔细查看index.html文件中包含的JavaScript代码:

  1. 无需停止事件传播。
  2. Regex的事情可能很棘手,有时很难实施。仅在您真正需要的情况下才使用它们。
  3. 看来您使用#display值,而不是使用已定义的pin变量来构建您的pin> pin

继续使用已定义的pin变量,您可以一起使用鼠标和键盘(如果用户真正想要)输入PIN。

使用 data-attributes> data-attributes 是一种明智的方式标准化键PIN-PAD输入。将这个想法扩展到“输入”和“清晰”按钮将是一个好主意。将数据属性值转换为较低的情况并与有效的密钥列表进行比较仍然是必经之路。为“清除”按钮添加快捷方式c也可以工作。 PS:ESC也可以实现以清除显示。

最后,使用JavaScript使用JavaScript添加和删除包含颜色的CSS类名称,而不是通过手动添加和删除凹陷的按钮背景颜色。将CSS设置保留在样式表中,可以进行良好的代码分离且容易调试。 PS:有时,人们在其CSS类名称中添加JS - < / code>前缀,该名称由JavaScript切换 /控制。


在下面,我在CSS中添加了其他悬停/JS depressed类,以涵盖鼠标和键盘用户的反馈。

pinpad.css(渲染过程)

#pin-pad div:hover,
#pin-pad div.js-depressed {
    background-color: #ccc;
}

,我借此自由来刷新您的index.html javascript稍微删除不必要的代码行,并简化了键盘的实现(与鼠标)实现。

可以进行更多的重构以保持代码干燥(如果愿意,请不要重复)。

使您的代码尽可能简单,可以易于阅读 /调试代码。

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" href="pinpad.css"/>

        <meta charset="UTF-8"/>
        <title>Electron Test - Pin Pad</title>
        <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';"/>
    </head>

    <body>
        <div id="container">
            <div id="wrapper">
                <input type="text" id="display" disabled/>

                <div id="pin-pad">
                    <div data-key="1">1</div>
                    <div data-key="2">2</div>
                    <div data-key="3">3</div>
                    <div data-key="4">4</div>
                    <div data-key="5">5</div>
                    <div data-key="6">6</div>
                    <div data-key="7">7</div>
                    <div data-key="8">8</div>
                    <div data-key="9">9</div>
                    <div data-key="enter">Enter</div>
                    <div data-key="0">0</div>
                    <div data-key="clear">Clear</div>
                </div>
            </div>
        </div>
    </body>

    <script>
        let display = document.getElementById('display');
        let validKeys = [
            '1',
            '2',
            '3',
            '4',
            '5',
            '6',
            '7',
            '8',
            '9',
            '0',
            'enter',
            'clear',
            'backspace'
        ];
        let pin = "";

        // Mouse input
        document.getElementById('pin-pad').addEventListener('click', (event) => {
            let key = event.target.dataset.key;

            if (! validKeys.includes(key)) {
                return;
            }

            if (key === 'enter') {
                window.electronAPI.sendPin(pin);
                return;
            }

            if (key === 'clear') {
                pin = display.value = "";
                return;
            }

            pin = pin + key;
            display.value = '*'.repeat(pin.length);
        });

        // Keyboard input
        document.addEventListener('keydown', (event) => {
            let key = event.key.toLowerCase();

            if (! validKeys.includes(key)) {
                return;
            }

            if (key === 'backspace') {
                pin = pin.slice(0, -1);
                display.value = "*".repeat(pin.length);
                return;
            }

            document.querySelector(`[data-key="${key}"]`).classList.add('js-depressed');

            if (key === 'enter') {
                window.electronAPI.sendPin(pin);
                return;
            }

            pin = pin + key;
            display.value = '*'.repeat(pin.length);
        });

        document.addEventListener('keyup', (event) => {
            let key = event.key.toLowerCase();

            if (! validKeys.includes(key) || key === 'backspace') {
                return;
            }

            document.querySelector(`[data-key="${key}"]`).classList.remove('js-depressed');
        });
    </script>
</html>

一个人没有考虑到弹跳。即:如果用户将手指握在钥匙上,则输入将以快速速率重复填充引脚场。如果不需要此行为,则可能希望添加“弹跳”功能。

In reference to index.html, within the if (13 === e.keyCode) { ... } statement, the argument of the window.electronAPI.sendPin(...); call is of the incorrect case. Instead of Pin, it should be pin.

That said, pin is not updated within your const handlekeyUp = function (e) { ... } function, so when "Enter" (or "Return") is pressed, it can't send an updated pin to your render process.

Looking closer at your JavaScript code contained within your index.html file:

  1. There would be no need to stop event propagation.
  2. Regex's can be tricky things and hard to implement at times. Only use them if you really need to.
  3. It appears that you are use the #display value instead of using the already defined pin variable to build your pin.

Continuing to use the already defined pin variable allows you to use both the mouse and the keyboard together (if the user really wants to) to enter a pin.

Use of data-attributes is a smart way to standardize key pin-pad input. Extending this idea to the "Enter" and "Clear" buttons would be a great idea. Converting the data-attribute value to lower case and comparing against a valid list of keys is still the way to go. Adding a shortcut for the "Clear" button c can work as well. PS: esc could also be implemented to clear the display.

Lastly, instead of manually adding and removing the depressed button background color via Javascript, use Javascript to add and remove a CSS class name containing the color. Keeping CSS settings within your style sheet(s) allows for good code separation and easy of debugging. PS: Sometimes, people add a js- prefix to their CSS class names that are toggled / controlled by Javascript.


Below, I have added an additional hover / js-depressed class to your CSS to cover mouse and keyboard user feedback.

pinpad.css (render process)

#pin-pad div:hover,
#pin-pad div.js-depressed {
    background-color: #ccc;
}

Below, I took the liberty to rework your index.html Javascript a little bit to remove unnecessary lines of code and simplify the implementation of keyboard (along with mouse) implementation.

Even more refactoring could be performed to keep your code DRY (Don't Repeat Yourself) if you wanted to.

Keeping your code as simple as possible makes for easy to read / debug code.

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" href="pinpad.css"/>

        <meta charset="UTF-8"/>
        <title>Electron Test - Pin Pad</title>
        <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';"/>
    </head>

    <body>
        <div id="container">
            <div id="wrapper">
                <input type="text" id="display" disabled/>

                <div id="pin-pad">
                    <div data-key="1">1</div>
                    <div data-key="2">2</div>
                    <div data-key="3">3</div>
                    <div data-key="4">4</div>
                    <div data-key="5">5</div>
                    <div data-key="6">6</div>
                    <div data-key="7">7</div>
                    <div data-key="8">8</div>
                    <div data-key="9">9</div>
                    <div data-key="enter">Enter</div>
                    <div data-key="0">0</div>
                    <div data-key="clear">Clear</div>
                </div>
            </div>
        </div>
    </body>

    <script>
        let display = document.getElementById('display');
        let validKeys = [
            '1',
            '2',
            '3',
            '4',
            '5',
            '6',
            '7',
            '8',
            '9',
            '0',
            'enter',
            'clear',
            'backspace'
        ];
        let pin = "";

        // Mouse input
        document.getElementById('pin-pad').addEventListener('click', (event) => {
            let key = event.target.dataset.key;

            if (! validKeys.includes(key)) {
                return;
            }

            if (key === 'enter') {
                window.electronAPI.sendPin(pin);
                return;
            }

            if (key === 'clear') {
                pin = display.value = "";
                return;
            }

            pin = pin + key;
            display.value = '*'.repeat(pin.length);
        });

        // Keyboard input
        document.addEventListener('keydown', (event) => {
            let key = event.key.toLowerCase();

            if (! validKeys.includes(key)) {
                return;
            }

            if (key === 'backspace') {
                pin = pin.slice(0, -1);
                display.value = "*".repeat(pin.length);
                return;
            }

            document.querySelector(`[data-key="${key}"]`).classList.add('js-depressed');

            if (key === 'enter') {
                window.electronAPI.sendPin(pin);
                return;
            }

            pin = pin + key;
            display.value = '*'.repeat(pin.length);
        });

        document.addEventListener('keyup', (event) => {
            let key = event.key.toLowerCase();

            if (! validKeys.includes(key) || key === 'backspace') {
                return;
            }

            document.querySelector(`[data-key="${key}"]`).classList.remove('js-depressed');
        });
    </script>
</html>

One this not taken into account if de-bouncing. IE: If the user holds their finger on a key, the input will repeat at a rapid rate fill the pin field. If this behavior is not desired then a "de-bouncing" function may wish to be added.

热情消退 2025-02-17 21:39:49
window.electronAPI.sendPin(Pin); --> window.electronAPI.sendPin(pin);

window.electronAPI.sendPin(Pin); --> window.electronAPI.sendPin(pin);

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文