Electron使用与学习

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Electron使用与学习相关的知识,希望对你有一定的参考价值。

对于electron是个新手,下面纯属个人理解。如有错误,欢迎指出。
 
一.安装
 如果你本地按照github上的
# Install the `electron` command globally in your $PATH
npm install electron-prebuilt -g
安装不起来的话,没事。按照这个博友的方法来安装即可。Electron安装
 
二.Electron是什么
类似NW.js。但是好像比它强大很多。而且社区很活跃,很有前途。
 
三.废话不多说,直接上实例。
main.js(主进程)
const electron = require(\'electron\')
 
const app = electron.app
 
const BrowserWindow = electron.BrowserWindow
 
let mainWindow
 
function createWindow(){
    mainWindow = new BrowserWindow({
        width:800,
        height:400
    })
 
    mainWindow.loadURL(`file://${__dirname}/index.html`);
 
    mainWindow.webContents.openDevTools()
 
    mainWindow.on(\'closed\', function () {
 
        mainWindow = null
    })
 
}
 
app.on(\'ready\',createWindow);
 
app.on(\'window-all-closed\', function () {
  if (process.platform !== \'darwin\') {
    app.quit()
  }
})
 
1.创建窗口的用法:
  BrowserWindow 类让你有创建一个浏览器窗口的权力。
  当然这里面有很多options 
  new BrowserWindow([options])
  • options Object
    • width Integer - 窗口宽度,单位像素. 默认是 800.
    • height Integer - 窗口高度,单位像素. 默认是 600.
    • x Integer - 窗口相对于屏幕的左偏移位置.默认居中.
    • y Integer - 窗口相对于屏幕的顶部偏移位置.默认居中...等等
 
2.app 模块是为了控制整个应用的生命周期设计的
 app有很多事件:
     ready:当 Electron 完成初始化时被触发,常用的
     window-all-closed:当所有的窗口都被关闭时触发,常用的
     quit:当应用程序正在退出时触发,常用的
     ....等等
 
3.mainWindow.webContents.openDevTools()这个是调用开发者工具的,用来调试页面
 
4.所以上面的js应该就很好理解了吧。
    
html:
<!DOCTYPE html>
<html>
<head>
    <title>zqz_electron</title>
    <meta charset="utf-8">
</head>
<script type="text/javascript">
 
    const remote = require(\'electron\').remote;
    const Menu = remote.Menu;
    const MenuItem = remote.MenuItem;
 
    var menu = new Menu();
    menu.append(new MenuItem({ label: \'MenuItem1\', click: function() { alert(\'zqz click  item 1\'); } }));
    menu.append(new MenuItem({ type: \'separator\' }));
    menu.append(new MenuItem({ label: \'MenuItem2\', type: \'checkbox\', checked: true }));
 
    window.addEventListener(\'contextmenu\', function (e) {
      e.preventDefault();
      menu.popup(remote.getCurrentWindow());
    }, false);
 
</script>
<body>
 
<input type="file">选取文件</input>
 
</body>
</html>
 
页面要注意:
    1. html中的require(\'electron\').remote与js中的electron = require(\'electron\')是不一样的。
        remote是什么:remote 模块提供了一种在渲染进程(网页)和主进程之间进行进程间通讯(IPC)的简便途径
        在这里,js就是主进程,页面中的js就是渲染进程。
        如果要使得独立js中与页面js的代码互相操作。必要要使用这样的通讯途径。(这个例子没有很好的验证,在我下一篇的例子上就有,还有ipc)
 
    2.Menus:是用来创建一个新的菜单.
    
    3.MenuItem:菜单项模块允许你向应用或menu添加选项
    
 
package.json
 {
  "name": "zqz",
  "version": "1.0.0",
  "main": "main.js",
  "scripts": {
    "start": "electron main.js"
  },
  "devDependencies": {
 
  }
}

 

运行:
    
效果:
 
 
 

以上是关于Electron使用与学习的主要内容,如果未能解决你的问题,请参考以下文章

Electron使用与学习--(页面间的通信)

Electron – 基础学习: 环境安装创建项目及入门

electron的安装与应用

electron安装与使用

Electron 使用Node原生模块

ELECTRON 学习三