想操作 DOM,于是就引入了 jQuery,想注册点击事件触发 app 的事件监听,但是当我引入 jQuery 之后,却报了错,表示 $
符未定义。
Uncaught ReferenceError: $ is not defined
后来百度了一下才知道,jQuery 等新版本的框架,在 Electron 中使用普通的引入的办法会引发异常,原因是 Electron 默认启用了 Node.js 的 require 模块,而这些框架为了支持 commondJS 标准,当 Window 中存在 require 时,会启用模块引入的方式。找到了 下面的两种解决办法:
1、修改 jQuery
去掉 jQuery 中的第一行代码中的模块引入判断代码
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}
将其改成
!function(a,b){b(a)}
2、使用 Electron 官方论坛提供的方法
<head>
<script>
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
</script>
<script type="text/javascript" src="jquery.js"></script>
</head>
注意如果采用这种方法之后,在你需要导入 node.js 模块时,就必需采用 nodeRequire,而不能使用 require
<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<h1>hello world</h1>
<script>
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
</script>
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
const remote = nodeRequire('electron').remote
const win = remote.getCurrentWindow()
$('h1').click(function () {
win.close()
});
</script>
</body>
</html>
总结
个人建议使用第一种方法,改一个 jQuery 原文件就可以了,如果采用第二种方法,则在每个页面引入 jQuery 时都要重新一遍上述代码,很繁琐。
评论列表 (0条):
加载更多评论 Loading...