javascript - 将 eventListener 或 attachEvent 添加到 Electron 中的 anchor 标记的正确方法是什么?

标签 javascript html node.js electron

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

我还尝试将脚本放在 anchor 标记内。我没有在 main.js 中处理这段代码,因为我只想将函数链接到我的 anchor 标记。可能是因为我使用了 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 环境中实现这个的正确方法是什么吗?

最佳答案

确保在要添加监听器的标记之后启动脚本标记。

<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();
});

也尝试做 Node 集成true创建浏览器窗口时。
    const mainWindow = new BrowserWindow({
        width: 1100,
        height: 700,
        chromeWebSecurity: false,
        webPreferences: {
            nodeIntegration: true,
            webSecurity: false
        }
    })

关于javascript - 将 eventListener 或 attachEvent 添加到 Electron 中的 anchor 标记的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57687594/

相关文章:

javascript - 检查特定类的 div 是否包含文本或为空

html - 使用 flexbox 对齐 div 文本

php - 如何在浏览器中显示/运行 PHP 文件?就好像它是一个网页

javascript - Socket.IO - 如何更改客户端的超时值选项?

javascript - 用于查找页面上使用的所有字体的脚本

javascript - 如何防止函数数组中的函数在前一个函数完成之前执行

javascript - AngularJS:浏览页面内容未显示在主页中

javascript - Angular 错误: $parse:ueoe Unexpected End of Expression for a couple of expressions

node.js - AWS localhost 具有任意端口

node.js - C9.IO - 调试失败 - 无法在端口 15400 上打开套接字,等待 1000 毫秒再重试