LoginSignup
36
32

More than 5 years have passed since last update.

Electronでページ内検索を行う

Posted at

Electronのページ内検索はcontents.findInpageを使う必要がありますが、毎度同じような処理を書くのもなんだかなという感じがしたのでモジュールにして公開しました。

electron-search-text

2016-08-18 22_38_58.gif

使い方は👇の通り。

browser.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <style>
    body {
      height: 100vh;
      margin: 0;
    }
    webview {
      height: 100%;
    }
    .search-box {
      display: none;
    }
    .state-visible {
      display: block;
    }
  </style>
  <link rel="stylesheet" href="./search.css">
</head>
<body>
<div class="search-box">
  <input type="text" class="search-input">
  <span class="search-count"></span>
</div>
<webview src="https://github.com/trending"></webview>
<script>
  const {ipcRenderer} = require('electron');

  const ElectronSearchText = require('electron-search-text');
  const searcher = new ElectronSearchText({
    target: 'webview',
    input: '.search-input',
    count: '.search-count',
    box: '.search-box',
    visibleClass: '.state-visible'
  });

  ipcRenderer.on('toggleSearch', function() {
    searcher.emit('toggle');
  });
</script>
</body>
</html>

require('electron-search-text')してnewするときに検索対象にするwebviewと、検索窓用のUIのセレクタを渡します。

newしたインスタンスで.emit('toggle')するとvisibleClassに指定したクラスをboxに対してトグルします。

あとはmain.jsCmd+Fでトグルできるようにショートカットキーを設定する。

main.js
const {app, BrowserWindow, Menu} = require('electron');

app.on('ready', () => {
  const browserWindow = new BrowserWindow();
browserWindow.loadURL(`file://${__dirname}/browser.html`);

const menuTemplate = [
  {
    submenu: [
      {
        label: 'Quit',
        accelerator: 'Cmd+Q',
        click() {
          app.quit();
        }
      }
    ]
  }, {
    label: 'Edit',
    submenu: [
      {
        label: 'Search in File',
        accelerator: 'CmdOrCtrl+F',
        click() {
          browserWindow.webContents.send('toggleSearch')
        }
      }
    ]
  }
];

const menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
});

おしまい。

36
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
36
32