launch method

Future<Browser> launch({
  1. String? executablePath,
  2. bool? headless,
  3. bool? devTools,
  4. String? userDataDir,
  5. bool? noSandboxFlag,
  6. DeviceViewport? defaultViewport = LaunchOptions.viewportNotSpecified,
  7. bool? ignoreHttpsErrors,
  8. Duration? slowMo,
  9. List<String>? args,
  10. dynamic ignoreDefaultArgs,
  11. Map<String, String>? environment,
  12. List<Plugin>? plugins,
  13. Duration? timeout,
  14. bool? waitForInitialPage,
})

This method starts a Chrome instance and connects to the DevTools endpoint.

If executablePath is not provided and no environment variable PUPPETEER_EXECUTABLE_PATH is present, it will download the Chromium binaries in a local folder (.local-chromium by default).

main() async {
  var browser = await puppeteer.launch();
  await browser.close();
}

Parameters:

  • ignoreHttpsErrors: Whether to ignore HTTPS errors during navigation. Defaults to false.
  • headless: Whether to run browser in headless mode. Defaults to true unless the devtools option is true.
  • executablePath: Path to a Chromium or Chrome executable to run instead of the bundled Chromium. . BEWARE: Puppeteer is only guaranteed to work with the bundled Chromium, use at your own risk.
  • slowMo Slows down Puppeteer operations by the specified duration. Useful so that you can see what is going on.
  • defaultViewport: Sets a consistent viewport for each page. Defaults to an 1280x1024 viewport. null disables the default viewport.
  • args Additional arguments to pass to the browser instance. The list of Chromium flags can be found here.
  • environment Specify environment variables that will be visible to the browser. Defaults to Platform.environment.
  • devtools Whether to auto-open a DevTools panel for each tab. If this option is true, the headless option will be set false.
  • ignoreDefaultArgs <boolean|List<string>> If true, then do not use `puppeteer.defaultArgs()`. If a list is given, then filter out the given default arguments. Dangerous option; use with care. Defaults to false.
  • userDataDir <string> Path to a User Data Directory.
  • timeout Maximum time to wait for the browser instance to start. Defaults to 30 seconds.
  • waitForInitialPage: Whether to wait for the initial page to be ready. Useful when a user explicitly disables that (e.g. --no-startup-window for Chrome).

Implementation

Future<Browser> launch({
  String? executablePath,
  bool? headless,
  bool? devTools,
  String? userDataDir,
  bool? noSandboxFlag,
  DeviceViewport? defaultViewport = LaunchOptions.viewportNotSpecified,
  bool? ignoreHttpsErrors,
  Duration? slowMo,
  List<String>? args,
  /* bool | List */ dynamic ignoreDefaultArgs,
  Map<String, String>? environment,
  List<Plugin>? plugins,
  Duration? timeout,
  bool? waitForInitialPage,
}) async {
  devTools ??= false;
  headless ??= !devTools;
  timeout ??= Duration(seconds: 30);
  waitForInitialPage ??= true;

  var chromeArgs = <String>[];
  var defaultArguments = defaultArgs(
      args: args,
      userDataDir: userDataDir,
      devTools: devTools,
      headless: headless,
      noSandboxFlag: noSandboxFlag);
  if (ignoreDefaultArgs == null) {
    chromeArgs.addAll(defaultArguments);
  } else if (ignoreDefaultArgs is List) {
    chromeArgs.addAll(
        defaultArguments.where((arg) => !ignoreDefaultArgs.contains(arg)));
  } else if (args != null) {
    chromeArgs.addAll(args);
  }

  if (!chromeArgs.any((a) => a.startsWith('--remote-debugging-'))) {
    chromeArgs.add('--remote-debugging-port=0');
  }

  Directory? temporaryUserDataDir;
  if (!chromeArgs.any((a) => a.startsWith('--user-data-dir'))) {
    temporaryUserDataDir =
        await Directory.systemTemp.createTemp('puppeteer_dev_profile-');
    chromeArgs.add('--user-data-dir=${temporaryUserDataDir.path}');
  }

  executablePath ??= await _inferExecutablePath();

  var launchOptions =
      LaunchOptions(args: chromeArgs, defaultViewport: defaultViewport);

  var allPlugins = this.plugins.toList();
  if (plugins != null) {
    allPlugins.addAll(plugins);
  }
  for (var plugin in allPlugins) {
    launchOptions = await plugin.willLaunchBrowser(launchOptions);
  }

  _logger.info('Start $executablePath with $chromeArgs');
  var chromeProcess = await Process.start(executablePath, launchOptions.args,
      environment: environment);

  // ignore: unawaited_futures
  var chromeProcessExit = chromeProcess.exitCode.then((exitCode) {
    _logger.info('Chrome exit with $exitCode.');
    if (temporaryUserDataDir != null) {
      try {
        _logger.info('Clean ${temporaryUserDataDir.path}');
        temporaryUserDataDir.deleteSync(recursive: true);
      } catch (error) {
        _logger.info('Delete temporary file failed', error);
      }
    }
  });

  var webSocketUrl = await _waitForWebSocketUrl(chromeProcess)
      .then<String?>((f) => f)
      .timeout(timeout, onTimeout: () => null);
  if (webSocketUrl != null) {
    var connection = await Connection.create(webSocketUrl, delay: slowMo);

    var browser = await createBrowser(chromeProcess, connection,
        defaultViewport: launchOptions.computedDefaultViewport,
        closeCallback: () async {
      await BrowserApi(connection).close().catchError((error) async {
        await _killChrome(chromeProcess);
      });

      return chromeProcessExit;
    }, ignoreHttpsErrors: ignoreHttpsErrors, plugins: allPlugins);

    Future<Target>? initialWait;
    if (waitForInitialPage) {
      initialWait = browser.waitForTarget((target) => target.type == 'page');
    }

    await attachBrowser(browser);

    if (waitForInitialPage) {
      try {
        await initialWait;
      } catch (e) {
        await browser.close();
        rethrow;
      }
    }

    return browser;
  } else {
    throw Exception('Not able to connect to Chrome DevTools');
  }
}