How to Find the Text on Page in ElectronJS?


Overview

A find text on a page is a feature which helps a user to find a word on the page. An electronJs is an open source framework which creates a desktop application which can run on every operating system with its cross platform compatibility. The electronJs has many predefined instance methods with their respective functionality. So to build this feature of find text on page the electronJs provides a "findInPage" method which takes the current focused window and scans all the text on the page.

Syntax

For finding the text on page, the electronJs provides the below Syntax for finding the text and clearing the search on the page −

  • findInPage − In the below Syntax the "findInPage" is a method which takes two parameters as a text and an options. The text is a word which is to be found on the page and another parameter is an option which is the limitation to the findInPage method according to which the text is scanned on the page.

  • currentFocusedWindow − It is a current window reference variable in which the "getFocusedWindow()" returns the current window on which the text is to be scanned. It is a method of the BrowserWindow object.

  • WebContents − It Is an electronJs module, it is a pack of methods which provides the access to manipulate browser windows. It allows the user to make changes to the browser page.

currentFocusedWindow.webContents.findInPage(text, options);
  • stopFindPage − The "stopFindPage" is a method of electronJs which makes the page clear by stopping the findInPage process by clearing out the highlighted words from the text on the page. The stopFindInPage also takes a single parameter as input which is "clearSelection", this parameter is passed to the method to clear the page highlights.

currentFocusedWindow.webContents.stopFindInPage('clearSelection');

Algorithm

  • Step 1 − Create a folder as "electronApp" and open the folder in the text editor such as VS Code.

  • Step 2 − Now open the integrated terminal of the code editor or open your powershell.

  • Step 3 − Check whether your system has node installed or not by using the following command. If not then visit the official website of NodeJs and download it for your compatible system.

node --version
  • Step 4 − Now create a 'package.json' file using the command shown below.

npm init
  • Step 5 − Now install the electron dependencies to the package.json file by using the below command.

npm install electron –-save
  • Step 6 − After installing, create a "main.js" in the folder and use the below code to create a browser window and "main.js" is the entry point of your desktop application. Also check the package.json file and check the main as "main.js".

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

var win;

function createWindow() {
   win = new BrowserWindow({
      width: 800,
      height: 600,
      webPreferences: {
         nodeIntegration: true
      }
   });
   win.loadFile('src/index.html')
   win.webContents.openDevTools()
}

app.whenReady().then(() => {
   createWindow()
})

app.on('window-all-closed', () => {
   if (process.platform !== 'darwin') {
      app.quit()
   }
})

app.on('activate', () => {
   if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
   }
})
  • Step 7 − Now create a src folder inside your parent folder and create two files in it as "index.html" and "index.js".

  • Step 8 − Open the index.html file and add the HTML boilerplate to the file.

  • Step 9 − Now add a meta tag to the head tag of the file, which adds the "Content Security Policy" for the page.

<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  • Step 10 − Now create a div container which contains an input tag and two buttons with the value and their id name as "search" and "clearSearch".

<div id="searchPannel">
   <input id="enter" type="text" placeholder="type word to search...">
   <button id="search">Find in Text</button>
   <button id="clearSearch">Clear Selection</button>
</div>
  • Step 11 − Now create another div container which contains a sample text for the search.

<div>
   This is a sample text to search for any word. Tutorialspoint is a great platform which provides information regarding each and every domain. We also provide training courses to level up your skills. Vist tutorialspoint.com to get more information about our platform. Also you can read articles regarding any topic.
</div>
  • Step 12 − Now link the "index.js" to the HTML file, which contains the functionality to search text on a page.

<script src="index.js"></script>
  • Step 13 − Now open the index.js file and import the "BrowserWindow" from electron module.

const electron = require('electron')
const BrowserWindow = electron.remote.BrowserWindow;
  • Step 14 − Now create an object as "option" which contains some constraints for finding the text.

var options = {
   forward: true,
   findNext: false,
   matchCase: false,
   wordStart: false,
   medialCapitalAsWordStart: false
}
  • Step 15 − Now access the "find" button and "clear" button to the reference variable by HTML DOM.

var search = document.getElementById('search');
var clearSearch = document.getElementById('clearSearch');
  • Step 16 − Now use the addEventListener follow up with the click event listener for finding the text on page.

search.addEventListener('click', () => {
   const cWin = BrowserWindow.getFocusedWindow();
   var text = document.getElementById('enter').value;
   console.log(text);
   if (text) {
      const requestId = cWin.webContents.findInPage(text, options);
      console.log(requestId);
   } else {
      console.log('Enter Text to find');
   }
   cWin.webContents.on('found-in-page', (event, result) => {
      console.log(result.requestId);
      console.log(result.activeMatchOrdinal);
      console.log(result.matches);
      console.log(result.selectionArea);
   });
});
  • Step 17 − Now use "clear" addEventListener follow up with the click event listener for stopping the process of finding the text on page.

clearSearch.addEventListener('click', () => {
   const cWin = BrowserWindow.getFocusedWindow();
   cWin.webContents.stopFindInPage('clearSelection');
   console.log("Search cleared");
});
  • Step 18 − Now check the package.json file and set the below key-value inside the "script".

"scripts": {
   "start": "electron ."
}
  • Step 19 − Now use the "npm start" command to start the desktop application.

Example

In this Example we will create a desktop application using electronJs. This desktop application will have a feature to search any text on the current window page. To build this feature we will be using the "webContents" module "findInPage" and "stopFindPage" methods in the render process of the electron app. For this we will be creating the main process of the electron app in main.js and the renderer process in the index.js. The index.html will contain the frontend of the page.

main.js

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

var win;

function createWindow() {
   win = new BrowserWindow({
      width: 800,
      height: 600,
      webPreferences: {
         nodeIntegration: true
      }
   });
   win.loadFile('src/index.html')
   win.webContents.openDevTools()
}

app.whenReady().then(() => {
   createWindow()
})

app.on('window-all-closed', () => {
   if (process.platform !== 'darwin') {
      app.quit()
   }
})

app.on('activate', () => {
   if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
   }
})

index.html

<html>
<head>
   <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
   <title> find text on page using electronjs</title>
   <style>
      body{
         background-color: white;
         color: black;
      }
   </style>
</head>
<body>
   <div id="searchPannel">
      <input id="enter" type="text" placeholder="type word to search...">
      <button id="search">Find</button>
      <button id="clearSearch">Clear</button>
   </div>
   <hr>
   <div>
      This is a sample text to search any word. Tutorialspoint is a great platform which provides information regarding each and every domain. We also provide training courses to level up your skills. Vist tutorialspoint.com to get more information about our platform. Also you can read articles regarding any topic.
   </div>
   <script src="index.js"></script>
</body>
</html>

index.js

const electron = require('electron')
const BrowserWindow = electron.remote.BrowserWindow;

var options = {
   forward: true,
   findNext: false,
   matchCase: false,
   wordStart: false,
   medialCapitalAsWordStart: false
}

var search = document.getElementById('search');
var clearSearch = document.getElementById('clearSearch');

search.addEventListener('click', () => {
   const cWin = BrowserWindow.getFocusedWindow();
   var text = document.getElementById('enter').value;
   console.log(text);
   if (text) {
      const requestId = cWin.webContents.findInPage(text, options);
      console.log(requestId);
   } else {
      console.log('Enter Text to find');
   }
    
   cWin.webContents.on('found-in-page', (event, result) => {
      console.log(result.requestId);
      console.log(result.activeMatchOrdinal);
      console.log(result.matches);
      console.log(result.selectionArea);
   });
});

clearSearch.addEventListener('click', () => {
   const cWin = BrowserWindow.getFocusedWindow();
   cWin.webContents.stopFindInPage('clearSelection');
   console.log("Search cleared");
});

Output

In the below images when a user starts the application he will get an interface which contains an input box which takes the input from the user and a search button, clear button with their respective functionality. When a user types a text in the input button and hits a "Find" button then a "findInPage" method will be triggered with an Output by highlighting the text which is on the screen as shown in the second image. When the user clicks on the clear button all the highlights from the text are removed.

Conclusion

This feature is very helpful in finding the text on the page when a large number of content is there on the page. In the above image as we can see there are some numbers in the console. They are the requested which means number of times a user has requested for the text. When a text is found on the page all the returned text are displayed with different colors as the number of times the text appears. In the clear function make sure that you must pass the "clearSelection" as the parameter otherwise you will get an error message.

Updated on: 13-Oct-2023

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements