LoginSignup
0
0

electronアプリ内でplaywrightを動かす方法

Posted at

目的

electronアプリの中でplaywrightを使った自動操縦をコントロールしたい!

なぜこんな記事を?

つまりはpupetter-in-electronと同じことがplaywrightでしたい。

electronアプリをplaywrightで外から自動テストする記事は山ほどあるのに、
electron中でplaywrightを制御する記事が全く見つからなかったので自分で書くことにした。

必要なもの

  • nodejs
  • electron
  • playwright-core

サンプルコード

main.ts
import {BrowserWindow, app} from "electron"
import Playwright from "playwright-core"

// playwright接続用ポートをあらかじめ設定
const DEBUGGING_PORT = "8888"
app.commandLine.appendSwitch("remote-debugging-port",DEBUGGING_PORT)

app.on("ready",async()=>{
    // Chrome DevTools Porotcolでplaywrightを接続
    const playwrightBrowser:Playwright.Browser = await Playwright.chromium.connectOverCDP("http://localhost:"+DEBUGGING_PORT+"/")

    // electron側でいつものようにウインドウを作り、ページをloadFileやloadURLすれば
    await new BrowserWindow().loadURL("https://google.com/")
    // playwright側のコンテキスト0番目の、page配列にPlaywright:Pageが入ってる
    const page:Playwright.Page = playwrightBrowser.contexts()[0].pages()[0]

    // playwright側で自動操縦可能に
    await page.goto("https://google.com/")

    // もう一枚ウインドウを作れば、page配列に追加される
    const browser = new BrowserWindow({webPreferences:{preload:"./dist/preload.js"}})
    await browser.loadFile("./contens/index.html")
    const page2:Playwright.Page = playwrightBrowser.contexts()[0].pages()[1]
    // それぞれ操縦可能
    await page2.goto("https://google.com/")

})

app.on("window-all-closed",async ()=>{
    app.quit()
})

ポイント

  • electronのコマンドラインスイッチに接続ポートを設定する
main.ts
const DEBUGGING_PORT = "8888"
app.commandLine.appendSwitch("remote-debugging-port",DEBUGGING_PORT)
  • 設定したポートからCDPで接続する
main.ts
const playwrightBrowser= await Playwright.chromium.connectOverCDP("http://localhost:"+DEBUGGING_PORT+"/")

  • 自動操縦可能なPageを取得する
main.ts
const page = playwrightBrowser.contexts()[0].pages()[0]
  • electronに内蔵してる形なのでelectronアプリとして起動する
npx electron .

余談

なんでこんな珍妙な構成なのかって?

むかしむかし、遥か古より引き継がれしウィザード形式のレガシー登録システムありけり
画面上で採番ボタン押して出てきた登録番号をExcelファイルに転記してそれを次の画面で添付が必要、入力情報の諸元は別のシステムから取ってくる必要もある、とか手でやるのは正気の沙汰じゃない

自動化するしかないじゃない!

ということで、ボタンポチポチするといくつかのシステムからplaywrightでいい感じに情報取得してきて、electron画面上できれいに整えた物を選択させて、playwrightからファイル作ってレガシーシステムに放り込む、そんなデスクトップアプリケーションを作ってる
RestAPI?そんな上等なものは無い。

使ったバージョン

  • nodejs@22.1.0
  • electron@30.0.2
  • playwright-core@1.43.1
0
0
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
0
0