【问题标题】:What is the right way to add an eventListener or attachEvent to an anchor tag in Electron?将 eventListener 或 attachEvent 添加到 Electron 中的锚标记的正确方法是什么?
【发布时间】:2020-01-01 09:32:17
【问题描述】:

我想为我的 Electron 应用程序的 index.html 中的锚标记添加一个 NodeJS 模块功能的 eventListener。我一直在谷歌上搜索并在这里寻找解决方案,但它们似乎都不起作用。我明白了,这与电子有关。如果这与主进程和渲染器进程有关,请告诉我。到目前为止,我还没有使用过 ipc,因为它不是必需的。

我的 script.js 文件如下所示:

const nodejsModule = require('module');

var anchorTag = document.getElementById("a1");
if (typeof window.addEventListener != "undefined") {
    anchorTag.addEventListener("click",nodejsModule.function()),false);
} else {
    anchorTag.attachEvent("onclick",nodejsModule.function());
}

我也试过了:

const nodejsModule  = require('module');
const anchorTag = document.getElementById('a1');
anchorTag .addEventListener('click', function(e) {
    nodejsModule.function();
});

在我的 index.html 中有:

<a  href="#" id="a1" >Click me!</a>
<script src="script.js" type="text/javascript"></script>

我还尝试将脚本放在锚标记内。我没有在 main.js 中处理此代码,因为我只想将函数链接到我的锚标记。可能是因为我使用了 NodeJS 语法 require('module'),所以这在我的 HTML 代码中不起作用?这是我的第一个猜测,因为当我在没有事件侦听器的情况下运行 script.js 时,只包含 require 和函数,该函数确实像魅力一样工作。对于另一个模块。我用过

<script src="../node_modules\exampleModule\module.js" type="text/javascript"></script>

直接在我的 index.html 中。因此,我删除了 script.js 中的 require 并且它起作用了。我已经为当前模块尝试过这个,但没有成功。我认为这是因为模块中涉及到一些 Python 和 C++(它需要 Visual Studio 和 Python)。

能否请您帮助我了解在 Electron 环境中实现此功能的正确方法是什么?

【问题讨论】:

    标签: javascript html node.js electron


    【解决方案1】:

    确保您的脚本标签在您要添加侦听器的标签之后启动。

    <body>
        /* all of your code here */
        <a  href="#" id="a1" >Click me!</a>
        <script src="script.js"></script>
    </body>
    
    
    document.getElementById('element').addEventListener("click", () => {
       yourModule.function();
    });
    

    还可以在创建浏览器窗口时尝试进行节点集成true

        const mainWindow = new BrowserWindow({
            width: 1100,
            height: 700,
            chromeWebSecurity: false,
            webPreferences: {
                nodeIntegration: true,
                webSecurity: false
            }
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-07
      • 2016-11-09
      • 2023-04-09
      • 2018-03-20
      • 2011-01-06
      • 2022-01-01
      相关资源
      最近更新 更多