Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavascriptSave Pages as HTML in ElectronJS

Save Pages as HTML in ElectronJS

ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.

All Chromium browsers support saving webpages as HTML files onto the native system. Usually, this functionality is triggered by a simple Ctrl+S Keyboard shortcut on any webpage in the Chromium Browser. Electron also exhibits this behaviour and allows us to save the BrowserWindow Instances as HTML files on the native System using the instance methods of the BrowserWindow Object and the webContents property. Every BrowserWindow instance runs in its own individual Renderer Process. Every Renderer Process is isolated and has its own HTML, CSS and JavaScript files associated with it. We can either save only the HTML file or we can save the HTML and its associated CSS and JS files respectively depending upon the options provided to the instance method of the webContents property. This tutorial will demonstrate how to save BrowserWindow instances as HTML files on the native System in Electron.

We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.

  • Project Structure:

Project Structure

Example: Follow the Steps given in Desktop Operations in ElectronJS to setup the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to setup the Electron application remain the same. 
 

package.json: 

{
  "name": "electron-html",
  "version": "1.0.0",
  "description": "Save HTML Page in Electron",
  "main": "main.js",
  "scripts": {
    "start": "electron ."
  },
  "keywords": [
    "electron"
  ],
  "author": "Radhesh Khanna",
  "license": "ISC",
  "dependencies": {
    "electron": "^8.3.0"
  }
}

Create the assets folder according to the project structure. We will be using the assets folder as the default path to save the HTML and its associated files generated by the application. Create the index.css file according to the project structure. This file is created only for demo purposes and we are going to keep this file blank. 
Output: At this point, our basic Electron Application is set up. Upon launching the application, we should see the following result. 

Saving HTML files in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module.

  • index.html: Add the following snippet in that file.  The Save This Page as HTML and Save GeeksForGeeks Page as HTML buttons do not have any functionality associated with them yet.

html




<head>
    <link rel="stylesheet" href="index.css">
</head>
 
<body>
  <h3>Save Pages as HTML file</h3>
    <button id="save">
      Save This Page as HTML
    </button>
    <button id="load">
      Save GeeksForGeeks Page as HTML
    </button>
</body>


 
 

  • index.js: Add the following snippet in that file.

 

javascript




const electron = require('electron');
const path = require('path');
// Importing BrowserWindow using Electron remote
const BrowserWindow = electron.remote.BrowserWindow;
 
let win = BrowserWindow.getFocusedWindow();
// let win = BrowserWindow.getAllWindows()[0];
 
// Specifying the assets folder as the default path
const filepathlocal = path.join(__dirname, '../assets/page.html');
const filepathload = path.join(__dirname, '../assets/neveropen.html');
 
var save = document.getElementById('save');
save.addEventListener('click', () => {
    // Works for the Local Page
    win.webContents.savePage(filepathlocal, 'HTMLComplete').then(() => {
        console.log('Page was saved successfully.')
    }).catch(err => {
        console.log(err);
    });
});
 
var load = document.getElementById('load');
load.addEventListener('click', (event) => {
    // Creating a New BrowserWindow Instance, Loading GeeksForGeeks.org
    // And Saving it as an External Page
    let window = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            nodeIntegration: true
        }
    });
    window.loadURL('https://www.geeksforgeeks.org/');
    window.webContents.openDevTools();
    window.webContents.on('did-finish-load', async () => {
        window.webContents.savePage(filepathload, 'HTMLOnly').then(() => {
            console.log('Page was saved successfully.')
        }).catch(err => {
            console.log(err)
        });
    });
});


The win.webContents.savePage(filepath, saveType) Instance method is used to save the current BrowserWindow Instance as HTML file onto the native System depending upon the saveType parameter. It returns a Promise and it resolves when the webpage is saved successfully. It takes in the following parameters. 

  • filepath: String This parameter cannot be empty. It specifies the filepath where we would like to save the generated HTML and associated files on the native system. In our code, we have specified the filepath to the assets folder along with the name of the files using the path module.
  • saveType: String This parameter cannot be empty. It specifies the type of save operations that needs to be performed on the BrowserWindow Instance. It can take in any one of the following values.
    • HTMLOnly: This value of the saveType property saves only the HTML file of the current BrowserWindow Instance without any associated files.
    • HTMLComplete: This value of the saveType property saves the complete webpage of the current BrowserWindow Instance including the HTML file and the associated JavaScript and CSS files respectively at the specified filepath. This value creates a new folder page_files within the specified filepath. This folder contains the additional CSS and JS files of the saved webpage.
    • MHTML: This value of the saveType property saves the HTML file of the BrowserWindow Instance as MHTML. It stands for MIME HTML and it is a MIME encapsulation of the aggregate HTML document. It is a web page format which is used to combine the HTML code and its resources (such as images, audio, video files, etc) that are represented by external hyperlinks in the code, into a single HTML file. The contents of the MHTML file are encoded using  the MIME content type multipart/related.

The did-finish-load Instance Event belongs to the webContents Property. It is emitted when the navigation of the webpage (specified by the window.loadURL() Instance method) is done and the page is completely loaded. This happens when the spinner of the page has stopped spinning, and the onload event has been dispatched. In our code, we have used this Instance event to wait for the GeeksForGeeks.org website to completely load into our BrowserWindow Instance before we can save the HTML file onto our System.
To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object. 

  • BrowserWindow.getAllWindows(): This method returns an Array of active/opened BrowserWindow Instances. In this application, we have only one active BrowserWindow Instance and it can be directly referred from the Array as shown in the code.
  • BrowserWindow.getFocusedWindow(): This method returns the BrowserWindow Instance which is focused in the Application. If no current BrowserWindow Instance is found, it returns null. In this application, we only have one active BrowserWindow Instance and it can be directly referred using this method as shown in the code.

Output: Saving the current BrowserWindow Instance by specifying win.webContents.savePage(filepathlocal, ‘MHTML’), Generated MHTML Output file. 
 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments