欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Electron使用指南——获得屏幕快照

程序员文章站 2022-06-04 14:49:19
...

1、完善主进程处理

从渲染进程中拿到 url 后,通过 offscreen 获取屏幕快照。 在项目根目录下,创建 readItem.js

// /readItems

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

// Offscreen BrowserWindow
let offscreenWindow

// Exported readItem function
module.exports = (url, callback) => {

  // Create offscreen window
  offscreenWindow = new BrowserWindow({
    width: 500,
    height: 500,
    show: false,
    webPreferences: {
      offscreen: true
    }
  })

  // Load item url
  offscreenWindow.loadURL(url)

  // Wait for content to finish loading
  offscreenWindow.webContents.on('did-finish-load', e => {

    // Get page title
    let title = offscreenWindow.getTitle()

    // Get screenshot (thumbnail)
    offscreenWindow.webContents.capturePage( image => {

      // Get image as dataURL
      let screenshot = image.toDataURL()

      // Execute callback with new item object
      callback({ title, screenshot, url })

      // Clean up
      offscreenWindow.close()
      offscreenWindow = null
    })
  })
}

2、更新 main.js

在 /main.js 文件里添加对 readItem.js 的引用:

// Modules
// ...
const readItem = require('./readItem')

// ...

// Listen for new item request
ipcMain.on('new-item', (e, itemUrl) => {

  // remove all codes here.

  // Get new item and send back to renderer
  readItem( itemUrl, item => {
    e.sender.send('new-item-success', item)
  })
})
相关标签: WEB前端*