Electron学习(一)之第一个程序

什么是Electron?

官网地址
Electron是使用JavaScript,HTMLCSS构建跨平台的桌面应用程序框架。

特点及优势

  • web技术:基于Chromium、Node.js
  • 开源:众多贡献者组成活跃社区共同维护的开源项目
  • 跨平台:Electron兼容Mac、WindowsLinux

需要掌握的知识

  • HTML,JS,CSS的基础知识
  • Node.js的最基本知识

环境要求

  • node版本 > 8.00
  • git

快速启动

# 克隆示例项目的仓库
git clone https://github.com/electron/electron-quick-start
# 进入这个仓库
cd electron-quick-start
# 安装依赖并运行
npm install && npm start

效果如下:

主进程-Main Process

  • 可以使用和系统对接的ElectronAPI-创建菜单,上传文件等等
  • 创建渲染进程-RendererProcess
  • 全面支持Nodejs
  • 只有一个,作为整个程序的入口点

渲染进程-RendererProcess

  • 可以有多个,每个对应一个窗口
  • 每个都是一个单独的进程
  • 全面支持Nodejs和DOMAPI
  • 可以使用一部分Electron提供的API

第一个程序

main.js内容如下:

const {app,BrowserWindow}=require("electron")
//ready:当electron完全加载,准备好创建BrowserWindow的时候
app.on('ready',()=>{
  const win=new BrowserWindow({
    width:800,
    height:600,
    webPreferences:{
      //意思是在man.js中可以使用nodejs的api
      nodeIntegration:true
    }
  })
  win.loadFile("index.html")
  const secondWin=new BrowserWindow({
    width:400,
    height:300,
    webPreferences:{
      //意思是在man.js中可以使用nodejs的api
      nodeIntegration:true
    },
    //加入该属性后,只要关闭win,即主窗口,第二个窗口也会关闭
    parent:win
  })
  secondWin.loadFile("second.html")
})

index.html内容如下:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
    <link href="./styles.css" rel="stylesheet">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>

second.html内容如下:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'">
    <link href="./styles.css" rel="stylesheet">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>second html</h1>
  </body>
</html>

运行效果:

posted @ 2022-06-29 06:30  久曲健  阅读(125)  评论(0编辑  收藏  举报