How do I search text in a single page reactjs/elec

2019-09-08 04:37发布

问题:

I have a react electron application and I want to add ctrl+f functionality to it. I added a globalshortcut that responds to ctrl+f and shows a text box, then on the textbox, I gave it a listener for changes which calls window.find(). Unfortunately this never searches in the page, it always returns false. I'm assuming this has something to do with the react components, is there a way to search and highlight text of all the components on the page?

code:

  mainWindow.on('focus', () => {
    globalShortcut.register('CmdorCtrl+F', () => {
      mainWindow.webContents.send('find_request', 'search');
    });
});
   ipcRenderer.on('find_request', (event, arg) => {
 const modalbox = document.getElementById('modalbox');
 if (modalbox.style.display === 'block') {
   modalbox.style.display = 'none';
 } else {
    modalbox.style.display = 'block';
 }
});
searchPage(event) {
  console.log(event)
  console.log(window.find(event.value));
}

回答1:

I figured this out and feel like a complete idiot: In main.js

mainWindow.webContents.on('found-in-page', (event, result) => {
if (result.finalUpdate) {
  mainWindow.webContents.stopFindInPage('keepSelection');
}
});
ipcMain.on('search-text', (event, arg) => {
  mainWindow.webContents.findInPage(arg);
});

In the page:

static searchPage(event) {
if (event.target.value.lenght > 0) {
    ipcRenderer.send('search-text', event.target.value);
 }
}


回答2:

To give you an alternative, there are components doing this for you so you don't need to build it yourself. Had the same problem, and first fixed by using electron-in-page-search, but this component doesn't work properly with Electron 2 or greater.

Then finally found electron-find resolved my problem. Using with Electron 4.

You just add the component to your project:

npm install electron-find --save

Add a global shortcut in your Electron main process to send an event to the renderer in a ctrl+f:

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

And then you can add this to your page (the renderer process)

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()
})

Hope that helps.