Playwright 原始碼 BrowserType

华健课堂發表於2024-09-06

playwright-java 的 Browser、BrowserContext、Page 挺好理解的,唯獨這廝,就有一丟丟 ……

package com.microsoft.playwright;

/**
 * BrowserType provides methods to launch a specific browser instance or connect to an existing one. 
 *
 * BrowserType 提供啟動一個特定瀏覽器或連線到一個已存在瀏覽器的方法。
 */
public interface BrowserType {

  // 啟動瀏覽器 返回瀏覽器例項
  Browser launch(LaunchOptions options);
  
  // 透過 Chrome DevTools Protocol 連線已存在的瀏覽器 
  Browser connectOverCDP(String endpointURL, ConnectOverCDPOptions options);
  
  // 返回瀏覽器名 例如 chromium webkit firefox
  String name();
  
  // 返回可執行的瀏覽器路徑
  String executablePath();
 
  // ...
  
}

除錯以下程式碼,可看出:

BrowserType 不是簡單直譯地表示瀏覽器型別,而是表示帶有瀏覽器型別和瀏覽器可執行路徑,用來啟動或連線已啟動瀏覽器的類。

package demo;
import com.microsoft.playwright.*;

import java.util.Arrays;
import java.util.List;

public class Demo {
  public static void main(String[] args) {
    try(Playwright playwright = Playwright.create()) {
      // 三個 BrowserType
      List<BrowserType> browserTypes = Arrays.asList(
              playwright.chromium(),
              playwright.webkit(),
              playwright.firefox()
      );
      BrowserType.LaunchOptions launchOptions = new BrowserType.LaunchOptions().setHeadless(false);
      // 遍歷
      for (BrowserType browserType : browserTypes) {
        // 啟動瀏覽器
        try (Browser browser = browserType.launch(launchOptions)) {
          BrowserContext context = browser.newContext();
          Page page = context.newPage();
          page.navigate("https://localhost/");
        }
      }
    }
  }
}

好了,那上圖的 initializer 從何而來?又要到哪裡去?

一條重要的線索,漸漸浮出水面 ……

翻過這座山,越過那片海;給下面的方法都加斷點,相信,上下而求索的你,終將找到真相 ……

  • com.microsoft.playwright.impl.PlaywrightImpl#createImpl
  • com.microsoft.playwright.impl.ReaderThread#run
  • com.microsoft.playwright.impl.ChannelOwner#runUntil
  • com.microsoft.playwright.impl.Connection#processOneMessage
  • com.microsoft.playwright.impl.Connection#createRemoteObject
  • com.microsoft.playwright.impl.PlaywrightImpl#PlaywrightImpl

Huajianketang would climb every mountain, and swim every ocean, just to find you.

相關文章