electron基础(二)

347 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第7天,点击查看活动详情

1. 常用api_事件

文档地址:www.electronjs.org/docs/all

1.1 app常用事件

(1) ready:当electron完成初始化时触发

(2) window-all-closed:所有窗口关闭时触发

(3) cbefore-quit:在应用程序关闭窗口之前触发

(4) will-quit:所有窗口已及关闭且应用程序将退出时触发

(5) quit:应用程序退出时触发

1.2 webContents常用事件

(1) did-finish-load:导航完成时触发,即选项卡的选择器停止旋转,并指派load事件后。 如:mainWindow.webContents.on("did-finish-load",()=>{ })。

(2) dorm-ready:一个框架中的文本加载完成后触发。

1.3 常用api之进程对象process

(1) 文档地址 

www.electronjs.org/docs/api/pr…

(2) 注意事项

  • 版本5.0之前,需在main.js中的webPreferences里加上nodeIntegration: true progress、require等属性的使用需要设定上这个属性

  • 给button绑定事件,报内联错误:Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

原因:Chrome扩展的HTML中不能添加事件,只能在JS中动态添加

解决办法:

第一种: 在JS中注册触发事件

第二种:删掉

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
<meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'">

1.4 常用api之File对象

Electron已经向 文件 接口添加了一个 path 属性, 在文件系统上暴露出文件的真实路径

<div id="holder">

  Drag your file here
</div>

<script>

document.addEventListener('drop', (e) => { 

 e.preventDefault(); 

 e.stopPropagation(); 

   for (const f of e.dataTransfer.files) { 

     console.log('File(s) you dragged here: ', f.path) 

   } 

 }); 

 document.addEventListener('dragover', (e) => { 

   e.preventDefault(); 

   e.stopPropagation(); 

 });
</script>

1.5 常用api之<webview>标签

使用 webview 标签在Electron 应用中嵌入"外来"内容 (如 网页),"外来"内容包含在 webview 容器中,应用中的嵌入页面可以控制外来内容的布局和重绘,可嵌入脚本,引入css等。如: <webview>标签内嵌<iframe>标签

与 iframe 不同, webview 在与应用程序不同的进程中运行。可根据nodeIntegration来控制<webview>中的访页客是否能通过node api访问底层系统资源。它与您的网页没有相同的权限, 应用程序和嵌入内容之间的所有交互都将是异步的,这将保证你的应用对于嵌入的内容的安全性。

使用:

(1) <webview id="foo" src="https://www.github.com/" style="display:inline-flex; width:640px; height:480px"></webview>

(2) preload嵌入脚本,preload="./test.js", 引入css,<webview> .insertCSS(css)

(3) 当版本大于5,在构造 BrowserWindow 时,需要通过设置 webviewTag webPreferences选项来启用标签

1.6 常用api之window.open和BrowserWindowProxy,子窗口的弹出关闭及通信

(1) 打开子窗口

window.open(url[, frameName][, features])
如:window.open('https://github.com', '_blank', 'nodeIntegration=no')

(2) 子窗口向父窗口传值 将消息发送给指定来源的父窗口,如果未指定来源则发送给*,即所有窗口。

window.opener.postMessage(message, targetOrigin)

(3) 关闭子窗口

使用 window.open 创建一个新窗口时会返回一个 BrowserWindowProxy对象,并提供一个有限功能的子窗口。

BrowserWindowProxy 对象win.close(),不调用卸载事件,便关闭了子窗口。

1.7 常用api之BrowserWindow对象

创建和控制浏览器窗口

// 在主进程中.
const { BrowserWindow } = require('electron')

// 或者从渲染进程中使用 `remote`. 
// const { BrowserWindow } = require('electron').remote
let win = new BrowserWindow({ width: 800, height: 600 }) 
win.on('closed', () => { win = null })
win.loadURL('https://github.com')// 加载远程URL
win.loadURL(`file://${__dirname}/app/index.html`)// 或加载本地HTML文件

文档地址:www.electronjs.org/docs/api/br…

1.8 常用api之BrowserView对象

创建和控制视图

//进程:主进程
const { BrowserView, BrowserWindow } = require('electron')// 在主进程中.
let win = new BrowserWindow({ width: 800, height: 600 })
win.on('closed', () => { win = null })
let view = new BrowserView() 
win.setBrowserView(view) 
view.setBounds({ x: 0, y: 0, width: 300, height: 300 }) 
view.webContents.loadURL('https://electronjs.org')

BrowserView 被用来让 BrowserWindow 嵌入更多的 web 内容。它就像一个子窗口,除了它的位置是相对于父窗口,这意味着可以替代webview标签。

1.9 常用api之对话框dialog

(1) 显示用于打开和保存文件、警报等的本机系统对话框

(2) 主进程中使用

const { dialog } = require('electron'console.log(dialog.showOpenDialog({ properties: ['openFile', 'multiSelections'] }))

(3) 渲染进程中使用

const { dialog } = require('electron').remote 
console.log(dialog)

(4) 文档地址

http://www.electronjs.org/docs/api/dialog

1.10 常用api之系统快捷键globalShortcut对象

(1) 在 globalShortcut模块中使用 register 方法注册

(2) 主进程注册快捷键

const { app, globalShortcut } = require('electron')

app.on('ready', () => { // Register a 'CommandOrControl+Y' shortcut listener.
  globalShortcut.register('CommandOrControl+Y', () => { 
    // Do stuff when Y and either Command/Control is pressed. 
  })
})

(3) 渲染进程注册快捷键

const {remote} = require("electron");
remote.globalShortcut.register('CommandOrControl+Y', () => {
// Do stuff when Y and either Command/Control is pressed. 

})

1.11 常用api_主进程与渲染进程通信ipcMain和ipcRenderer

1.11.1 主进程ipcMain

(1) 被动通信

// 在主进程中.
const { ipcMain } = require('electron') 

ipcMain.on('asynchronous-message', (event, arg) => { 
   console.log(arg) // prints "ping" 
   //返回异步发送的消息
   event.reply('asynchronous-reply', 'pong')
 }) 
 
 ipcMain.on('synchronous-message', (event, arg) => { 
   console.log(arg) // prints "ping" 
   //返回异同发送的消息
   event.returnValue = 'pong' 
})

(2) 主动通信

const {BrowserWindow} = require('electron')
const mainWindow = new BrowserWindow({ width: 800, height: 600)  
mainWindow.webContents.send("asynchronous-reply","主进程主动给渲染进程发消息")

1.11.2 渲染进程ipcRenderer

//在渲染器进程 (网页) 中
const { ipcRenderer } = require('electron'//异步发送
console.log(ipcRenderer.sendSync('synchronous-message', 'ping')) // prints "pong"
//同步发送
ipcRenderer.send('asynchronous-message', 'ping')
ipcRenderer.on('asynchronous-reply', (event, arg) => { console.log(arg) // prints "pong" })

1.12 常用api之原生应用菜单Menu对象

(1) 主进程基本使用不到此对象

(2) 渲染进程

用法1

<script> 
const { remote } = require('electron'const { Menu, MenuItem } = remote 
const menu = new Menu() 

menu.append(new MenuItem(
   { label: 'MenuItem1', click() { console.log('item 1 clicked') } }
)) 

menu.append(new MenuItem(
   { type: 'separator' }
)) 

menu.append(new MenuItem(
   { label: 'MenuItem2', type: 'checkbox', checked: true }
)) 

 window.addEventListener('contextmenu', (e) => { 
    e.preventDefault() 
    menu.popup({ window: remote.getCurrentWindow() })  
}, false</script>

用法2

const { remote } = require('electron') 
const { Menu} = remote 

const template = [  { id: '1', label: 'one' }, { type: 'separator' }, { id: '3', label: 'three', beforeGroupContaining: ['1'] }, 
 { id: '4', label: 'four', afterGroupContaining: ['2'] }, 
 { type: 'separator' }, 
 { id: '2', label: 'two' } 
]  

Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
menu.popup()

1.13 常用api之网络net对象

(1) 使用Chromium的原生网络库发出HTTP / HTTPS请求

const { net } = require('electron').remote   
const request = net.request('https://github.com') 

request.on('response', (response) =>console.log(`STATUS: ${response.statusCode}`console.log(`HEADERS: ${JSON.stringify(response.headers)}`) 
    response.on('data', (chunk) => { console.log(`BODY: ${chunk}`) 
})

response.on('end', () => { console.log('No more data in response.') }) })

//表示请求发送完毕,系统才会进行响应,返回数据
request.end()

(2) 发送网络请求一般使用封装好的公开的库,如:axious; 使用系统代理时,使用原生请求net.request

2. 与vue框架集成

(1) 安装脚手架工具

npm install -g vue-cli

(2) 创建工程

vue init simulatedgreg/electron-vue  electron-vue-start(项目名称)
(版本vue 2.x,python 2.x)

(3) 进入工程安装依赖

 cd electron-vue-start
 yarn

若未安装yarn,则需要安装yarn命令

npm install -g yarn

若安装速度太慢,安装不成功,则切换镜像

npm install -g yrm  //安装yram并切换镜像
yrm ls //查看所有镜像
yrm use taobao //切换淘宝镜像

(4) 启动开发模式

yarn dev

(5) 打包

yarn build