How to send search text to findInPage in Electron

2019-08-19 03:17发布

问题:

I try using contents.findInPage. I have code in index.js:

  const { webContents } = require('electron')
  webContents.on('found-in-page', (event, result) => {
    if (result.finalUpdate) webContents.stopFindInPage('clearSelection')
  })

  const requestId = webContents.findInPage('api')
  console.log(requestId)

And code in component:

searchText(value){
    this.query = value;
    if (this.query.length > 0) {
        ipcRenderer.send('api', this.query);
    }
}

I wrote this code on the example of this answer. But function find not work. I do not understand how I can send the text to be searched and the word to be searched.

How I can use function findInPage ?

回答1:

sorry my answer to the other question wasn't clear enough (it was 2 years ago! I don't remember it that well but I'll give it a shot)

This is the documentation for webcontents and IPCMain

Here's what I have in my main.development.js (globals for the mainWindow and ipc communication):

mainWindow.on('focus', () => {
globalShortcut.register('CmdorCtrl+F', () => {
  mainWindow.webContents.send('find_request', '');
  });
});

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

mainWindow.on('blur', () => {
   globalShortcut.unregister('CmdorCtrl+F');
});

Then I made an ipc listener for CmdorCtrl+F:

ipcRenderer.on('find_request', () => {
  const modalbox = document.getElementById('modalbox');
 if (modalbox.style.display === 'block') {
   modalbox.style.display = 'none';
} else {
  modalbox.style.display = 'block';
 }
});

Then I made a modal searchbox:

const searchBox = (
  <div
    id="modalbox"
    style={{ display: 'none', position: 'fixed', zIndex: 1 }}
  ><input type="text" onChange={Calls.searchPage} />
  </div>);

The onchange sends the input text to the ipc listener:

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

I hope this is enough for you to get it fixed :)



标签: electron