📜  如何在 ElectronJS 中查找页面上的文本?

📅  最后修改于: 2021-10-29 04:41:23             🧑  作者: Mango

ElectronJS是一个开源框架,用于使用能够在 Windows、macOS 和 Linux 操作系统上运行的 HTML、CSS 和 JavaScript 等 Web 技术构建跨平台原生桌面应用程序。它将 Chromium 引擎和NodeJS 组合成一个单一的运行时。

在某些桌面应用程序中,开发人员希望提供一种功能,其中用户可以在网页内容中找到自定义文本选择。就像 Chromium 浏览器中Ctrl+F触发的搜索功能一样。 Electron 提供了一种方法,我们可以使用内置BrowserWindow对象的 Instance 方法和事件以及webContents属性在页面内容中成功找到自定义文本。本教程将演示如何在 Electron 的页面内容中查找文本。

我们假设您熟悉上述链接中介绍的先决条件。为了让 Electron 正常工作,需要在系统中预装nodenpm

  • 项目结构:
    项目结构

示例:我们将按照给定的步骤构建基本的电子应用程序。

  • 步骤 1:导航到空目录以设置项目,然后运行以下命令,
    npm init

    生成package.json文件。如果没有安装Electron,请使用 npm 安装它。

    npm install electron --save

    此命令还将创建package-lock.json文件并安装所需的node_modules依赖项。成功安装 Electron 后,打开package.json文件并在scripts键下执行必要的更改。
    包.json:

    {
      "name": "electron-find",
      "version": "1.0.0",
      "description": "Find Text in Electron",
      "main": "main.js",
      "scripts": {
        "start": "electron ."
      },
      "keywords": [
        "electron"
      ],
      "author": "Radhesh Khanna",
      "license": "ISC",
      "dependencies": {
        "electron": "^8.3.0"
      }
    }
    
  • 第二步:根据项目结构创建一个main.js文件。该文件是主进程并充当应用程序的入口点。复制以下链接中给出的main.js文件的样板代码。我们已经修改了代码以适应我们的项目需要。

    主要.js:

    const { app, BrowserWindow } = require('electron')
      
    function createWindow () {
      // Create the browser window.
      const win = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true
        }
      })
      
      // Load the index.html of the app.
      win.loadFile('src/index.html')
      
      // Open the DevTools.
      win.webContents.openDevTools()
    }
      
    // This method will be called when Electron has 
    // finished initialization and is ready to create
    // browser windows. Some APIs can only be used 
    // after this event occurs. This method is 
    // equivalent to 'app.on('ready', function())'
    app.whenReady().then(createWindow)
      
    // Quit when all windows are closed.
    app.on('window-all-closed', () => {
      
      // On macOS it is common for applications and 
      // their menu bar to stay active until the user 
      // quits explicitly with Cmd + Q
      if (process.platform !== 'darwin') {
        app.quit()
      }
    })
      
    app.on('activate', () => {
        // On macOS it's common to re-create a window in the 
        // app when the dock icon is clicked and there are no 
        // other windows open.
      if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
      }
    })
      
    // In this file, you can include the rest of your 
    // app's specific main process code. You can also 
    // put them in separate files and require them here.
    
  • 第 3 步:src目录中创建index.html文件和index.js文件。我们还将从上述链接复制index.html文件的样板代码。我们已经修改了代码以适应我们的项目需要。

    索引.html:

    
    
      
        
        Hello World!
        
        
      
      
        

    Hello World!

        We are using node      , Chrome      , and Electron      .                
  • 输出:此时,我们的基本电子应用程序已设置。要启动 Electron 应用程序,请运行以下命令:
    npm start

    图形用户界面输出

在 Electron 中查找页面上的文本: BrowserWindow实例和webContents属性是Main Process 的一部分。为了在Renderer Process 中导入和使用BrowserWindow ,我们将使用 Electron远程模块。

webContents.findInPage(text, options)方法启动一个请求,以在BrowserWindow页面的内容中查找文本的所有正匹配。此方法返回一个整数,表示用于请求的requestID 。请求的结果可以通过订阅found-in-page Instance Event 来获得,下面将详细解释。此方法会自动突出显示每个正匹配的内容中的文本。如果有多个匹配项,内容的多个部分将用匹配的文本突出显示。在我们的代码中,这是由Find in Text按钮触发的。它接受以下参数。

  • text: String此值不能为空。该值表示要在BrowserWindow实例中搜索的内容。
  • 选项:对象(可选)它接受以下参数,
    • forward: Boolean (可选)该值表示是从页面内容的开头向前还是从页面内容的结尾向后执行搜索操作。默认值为true 。此属性会影响从found-in-page Instance Event 中获得的结果Object。
    • findNext:Boolean (可选)此值表示搜索操作是第一个请求操作还是后续操作。默认值为false 。如果此值设置为true ,搜索操作将按预期工作,但我们将无法获取和显示从found-in-page Instance Event 获得的结果对象。
    • matchCase: Boolean (可选)此值表示搜索操作是否应区分大小写。默认值为false
    • wordStart:Boolean (可选)该值表示搜索操作是否应仅查看单词的开头。默认值为false 。此属性与medialCapitalAsWordStart属性结合使用。
    • medialCapitalAsWordStart: Boolean (可选)wordStart属性结合使用时,如果匹配以大写字母开头,后跟小写字母或非字母,则它允许搜索操作接受单词中间的匹配。它接受其他几种字内匹配组合,包括字母数字字符。默认值为false

webContents.stopFindInPage(action) Instance 方法使用提供的action参数停止任何webContents.findInPage()活动请求以在页面内容中查找文本。在我们的代码中,这是由清除选择按钮触发的。它采用以下值,

  • action: String此参数指定结束由webContents.findInPage()方法启动的活动请求时要采取的操作。它可以采用以下任何值。
    • clearSelection:清除从found-in-page Instance Event 中获得的选择/搜索结果。它从页面内容中删除所有突出显示的搜索结果。
    • keepSelection:将从found-in-page Instance Event 获得的突出显示的选择/搜索结果转换为正常选择。
    • activateSelection:它为选择节点启用焦点和单击。它选择第一个正匹配并突出显示它。

要在Renderer Process 中获取当前BrowserWindow实例,我们可以使用BrowserWindow对象提供的一些静态方法。

  • BrowserWindow.getAllWindows():此方法返回活动/打开的BrowserWindow实例的数组。在这个应用程序中,我们只有一个活动的BrowserWindow实例,它可以直接从 Array 中引用,如代码所示。
  • BrowserWindow.getFocusedWindow():此方法返回在应用程序中聚焦的BrowserWindow实例。如果未找到当前BrowserWindow实例,则返回null 。在此应用程序中,我们只有一个活动的BrowserWindow实例,可以使用此方法直接引用它,如代码所示。

found-in-page Instance 事件属于webContents属性。当webContents.findInPage()方法完成其操作并且结果可用时发出它。它返回以下参数。

  • 事件:全局事件对象。
  • result: Object它返回以下参数,
    • requestId: Integer webContents.findInPage()方法返回的整数 ID,用于表示活动请求。
    • activeMatchOrdinal: Integer根据 Electron 官方文档,它代表第一个 Active Match 的索引。该值取决于在options对象中设置的forward属性。在单个正匹配的情况下,没有影响,但在多个匹配的情况下,该值会根据向前搜索或向后搜索而变化。
    • 匹配:整数页面内容中文本的正匹配数。
    • selectionArea:第一个匹配区域的矩形坐标。该值取决于在options对象中设置的forward属性。它返回一个包含以下参数的对象,
      • x:整数x 坐标。它是匹配文本距页面边界的左偏移量。
      • y:整数y 坐标。它是匹配文本距页面边界的顶部偏移量。
      • width: Integer匹配区域的宽度。
      • height: Integer匹配区域的高度。
    • finalUpdate: Booleanfound-in-page Instance 事件已成功发出并且内容中的最后一个正匹配已找到时,它返回true 。当该值返回为true时,我们可以成功触发webContents.stopFindInPage()实例方法。
  • index.html:在该文件中添加以下代码段。

    Find Text in Page

        
    Lorem ipsum dolor sit amet consectetur           adipisicing elit. GeeksForGeeks. Dolores          numquam quae ipsum, voluptas nisi dicta          dolorem eaque omnis nulla fuga.Provident          dolorem amet quas perferendis culpa,           vitae eius dolores facere? GeeksForGeeks.     
        

                  
  • index.js:在该文件中添加以下代码段。
    const electron = require('electron')
    // Importing BrowserWindow from Main Process
    const BrowserWindow = electron.remote.BrowserWindow;
      
    var find = document.getElementById('find');
    var clear = document.getElementById('clear');
    let win = BrowserWindow.getFocusedWindow();
    // let win = BrowserWindow.getAllWindows()[0];
      
    var options = {
        forward: true,
        findNext: false,
        matchCase: false,
        wordStart: false,
        medialCapitalAsWordStart: false
    }
      
    find.addEventListener('click', () => {
        var text = document.getElementById('enter').value;
        console.log(text);
        if (text) {
            const requestId = win.webContents.findInPage(text, options);
            console.log(requestId);
        } else {
            console.log('Enter Text to find');
        }
      
        win.webContents.on('found-in-page', (event, result) => {
            console.log(result.requestId);
            console.log(result.activeMatchOrdinal);
            console.log(result.matches);
            console.log(result.selectionArea);
        });
    });
      
    clear.addEventListener('click', () => {
        win.webContents.stopFindInPage('clearSelection');
    });
    

    输出: