在 Electron BrowserWindow 中进行全文搜索

Full text search in Electron BrowserWindow

Electron 应用程序框架是否有内置文本搜索?

quick-start application doesn't provide any apparent search functionality (e.g. using Ctrl-F or from the menu options). I would have expected this to be a BrowserWindow option (or an option of its WebContents),但我没有在文档中看到任何有用的信息。

尝试webContents.findInPage刚刚在最新版本中添加。

我知道这是一个旧线程,但可能仍然与其他人相关。 遇到了同样的问题,首先使用 electron-in-page-search 解决了这个问题,但是这个组件在 Electron 2 或更高版本上无法正常工作。

然后终于发现electron-find解决了我的问题。与 Electron 4 一起使用。

您只需将组件添加到您的项目中:

npm install electron-find --save

在您的 Electron 主进程中添加一个全局快捷方式,以便在 ctrl+f 中将事件发送到渲染器:

globalShortcut.register('CommandOrControl+F', () => {
    window.webContents.send('on-find');
});

然后您可以将其添加到您的页面(呈现器进程)

const remote = require('electron').remote;
const FindInPage = require('electron-find').FindInPage;

let findInPage = new FindInPage(remote.getCurrentWebContents());

ipcRenderer.on('on-find', (e, args) => {
  findInPage.openFindWindow()
})

希望对您有所帮助。

Robson Hermes 提供的解决方案存在问题。 globalShortcut 根据定义是全局的,因此即使应用未获得焦点,也会检测到快捷方式。这将导致 Ctrl+F 快捷方式从其他地方“被盗”。

我没有找到理想的解决方案(请参阅电子存储库上的 this issue),但是可以通过按照 Robson 所说并添加

来实现一个 hacky 解决方案
win.on('focus', () => {
  globalShortcut.register('CommandOrControl+F', () => windows.main.send('on-find'))
})
win.on('blur', () => {
  globalShortcut.unregister('CommandOrControl+F')
}

请注意,如 here 所示,这并不理想,可能会导致几个问题:

  1. Other applications can get a lock on the shortcut when you lose focus, i.e. the shortcut will magically stop working when you switch back to the app later.
  2. Some apps can appear on screen without taking focus (spotlight I believe has this behavior) and during the app's appearance the shortcuts will still be captured by your application.
  3. There's also gonna be those weird one in a thousand situations where somehow you switch focus and the shortcut is not removed.