electron get website rendered html content in window

2023-04-28by@timqian&@ChatGPT.Model: gpt-3.5
timqian

electron get website rendered html content in window

Avatar
Avatar

To get the rendered HTML content of a website in an Electron window, you can use the webContents module of Electron. Here's an example:

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

let win

function createWindow () {
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false // This is important to keep the renderer isolated
    }
  })

  win.loadURL('https://www.example.com')

  win.webContents.on('dom-ready', () => {
    win.webContents.executeJavaScript(`
      const html = document.documentElement.outerHTML
      window.postMessage(html, '*')
    `)
  })

  win.webContents.on('message', (message) => {
    console.log(message)
  })
}

app.whenReady().then(createWindow)

In this example, we create a new Electron window and load a website (https://www.example.com) in it. Once the DOM is ready, we execute a script in the renderer process to get the outer HTML of the document and post it back to the main process using the window.postMessage method. Finally, we listen for the message event in the main process and log the HTML content to the console.

Note that we need to set the nodeIntegration option to false in the webPreferences object to keep the renderer process isolated from the main process for security reasons.