Electron使用指南 - [07] 特性和技巧

特性和技巧

本节我们来学习一下 Electron 其他特性和使用技巧。

1、Offscreen 渲染

// Modules
const {app, BrowserWindow} = require('electron')
const fs = require('fs')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

app.disableHardwareAcceleration()

// Create a new BrowserWindow when `app` is ready
function createWindow () {

  mainWindow = new BrowserWindow({
    width: 1000, height: 800,
    show: false,
    webPreferences: {
      nodeIntegration: true,
      offscreen: true
    }
  })

  // Load index.html into the new BrowserWindow
  mainWindow.loadURL('https://electronjs.org')

  let i = 1
  mainWindow.webContents.on('paint', (e, dirty, image) => {

    let screenshot = image.toPNG()
    fs.writeFile( app.getPath('desktop') + `/screenshot_${i}.png`, screenshot, console.log )
    i++
  })

  mainWindow.webContents.on('did-finish-load', e => {
    console.log( mainWindow.getTitle() )

    mainWindow.close()
    mainWindow = null
  })

  // Open DevTools - Remove for PRODUCTION!
  // mainWindow.webContents.openDevTools();

  // Listen for window being closed
  // mainWindow.on('closed',  () => {
  //   mainWindow = null
  // })
}

// Electron `app` is ready
app.on('ready', createWindow)

// Quit when all windows are closed - (Not macOS - Darwin)
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

// When app icon is clicked and app is running, (macOS) recreate the BrowserWindow
app.on('activate', () => {
  if (mainWindow === null) createWindow()
})

2、网络检测 (Network Detection)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>App is: <u id="status"></u></h1>

    <!-- All of the Node.js APIs are available in this renderer process. -->
    We are using Node.js <strong><script>document.write( process.versions.node)</script></strong>,
    and Electron <strong><script>document.write( process.versions.electron )</script></strong>.

    <script>

      const setStatus = status => {
        const statusNode = document.getElementById('status')
        statusNode.innerText = status ? 'online' : 'offline'
      }

      setStatus( navigator.onLine )

      window.addEventListener('online', e => {
        setStatus(true)
      })
      window.addEventListener('offline', e => {
        setStatus(false)
      })

    </script>
  </body>
</html>

3、提醒(Notivications)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>

    <!-- All of the Node.js APIs are available in this renderer process. -->
    We are using Node.js <strong><script>document.write( process.versions.node)</script></strong>,
    and Electron <strong><script>document.write( process.versions.electron )</script></strong>.

    <script>

      const { remote } = require('electron')

      const self = remote.getCurrentWindow()

      setTimeout(() => {

        let notification = new Notification( 'Electron App', {
          body: 'Some notification info!'
        })

        notification.onclick = e => {
          if( ! self.isVisible() ) self.show()
        }

      }, 2000)

    </script>
  </body>
</html>

4、预加载脚本(Preload Scripts)

4.1 index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline'">
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>

    <!-- All of the Node.js APIs are available in this renderer process. -->
    We are using Node.js <strong><script>document.write( versions.node)</script></strong>,
    and Electron <strong><script>document.write( versions.electron )</script></strong>.

    <br><textarea id="content" rows="8" cols="80"></textarea>
    <br><button id="save" οnclick="saveText()">Save Content</button>

    <script>

      const saveText = e => {

        const text = document.getElementById('content').value

        writeToFile( text )
      }

    </script>
  </body>
</html>

4.2 main.js

// Modules
const {app, BrowserWindow} = require('electron')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow

// Create a new BrowserWindow when `app` is ready
function createWindow () {

  mainWindow = new BrowserWindow({
    width: 1000, height: 800,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: false,
      preload: __dirname + '/preload.js'
    }
  })

  // Load index.html into the new BrowserWindow
  mainWindow.loadFile('index.html')

  // Open DevTools - Remove for PRODUCTION!
  mainWindow.webContents.openDevTools();

  // Listen for window being closed
  mainWindow.on('closed',  () => {
    mainWindow = null
  })
}

// Electron `app` is ready
app.on('ready', createWindow)

// Quit when all windows are closed - (Not macOS - Darwin)
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

// When app icon is clicked and app is running, (macOS) recreate the BrowserWindow
app.on('activate', () => {
  if (mainWindow === null) createWindow()
})

4.3 preload.js

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

const desktopPath = remote.app.getPath('desktop')

window.writeToFile = text => {
  fs.writeFile( desktopPath + '/app.txt', text, console.log )
}


window.versions = {
  node: process.versions.node,
  electron: process.versions.electron
}

5、进度条(Progress Bar)

// renderer.js

const { remote } = require('electron')

const self = remote.getCurrentWindow()

let progress = 0.01

let progressInterval = setInterval(() => {

  self.setProgressBar(progress)

  if (progress <= 1) {
    progress += 0.01
  } else {
    self.setProgressBar(-1)
    clearInterval(progressInterval)
  }
}, 75)

Guess you like

Origin blog.csdn.net/sdasadasds/article/details/109802385
07