chrome_dev_tools 1.1.0

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 80

chrome_dev_tools

Build Status

A Dart library to automate the Chrome browser over the DevTools Protocol.

This is a simple 1:1 mapping with the Chrome DevTools protocol.
All the code in lib/domains are generated from the browser_protocol.json and js_protocol.json.

Usage

Launch Chrome

Download the last revision of chrome and launch it.

import 'package:chrome_dev_tools/chrome_dev_tools.dart';
import 'package:chrome_dev_tools/chrome_downloader.dart';
import 'package:logging/logging.dart';

main() async {
  // Setup a logger if you want to see the raw chrome protocol
  Logger.root
    ..level = Level.ALL
    ..onRecord.listen(print);

  // Download a version of Chrome in a cache folder.
  String chromePath = (await downloadChrome()).executablePath;

  // You can specify the cache location and a specific version of chrome
  var chromePath2 =
      await downloadChrome(cachePath: '.chrome', revision: 497674);

  // Or just use an absolute path to an existing version of Chrome
  String chromePath3 =
      r'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';

  // Start the `Chrome` process and connect to the DevTools
  // By default it is start in `headless` mode
  Chrome chrome = await Chrome.start(chromePath);

  // Open a new tab
  Tab myTab = await chrome.newTab('https://www.github.com');

  // Do something (see example/ folder).

  // Kill the process
  await chrome.close();
}

Generate a PDF from a page

import 'dart:convert';
import 'dart:io';
import 'package:chrome_dev_tools/chrome_dev_tools.dart';
import 'utils.dart';

main() {
  chromeTab('https://www.github.com', (Tab tab) async {
    // Force the "screen" media or some CSS @media print can change the look
    await tab.emulation.setEmulatedMedia('screen');

    // A small helper to wait until the network is quiet
    await tab.waitUntilNetworkIdle();

    // Capture the PDF and convert it to a List of bytes.
    List<int> pdf = base64.decode(await tab.page.printToPDF(
        pageRanges: '1',
        landscape: true,
        printBackground: true,
        marginBottom: 0,
        marginLeft: 0,
        marginRight: 0,
        marginTop: 0));

    // Save the bytes in a file
    await File.fromUri(Platform.script.resolve('_github.pdf'))
        .writeAsBytes(pdf);
  });
}

Take a screenshot of a complete HTML page

import 'dart:convert';
import 'dart:io';
import 'package:chrome_dev_tools/chrome_dev_tools.dart';
import 'utils.dart';

main() {
  chromeTab('https://www.github.com', (Tab tab) async {
    // A small helper to wait until the network is quiet
    await tab.waitUntilNetworkIdle();

    var pageMetrics = await tab.page.getLayoutMetrics();

    // Set page size to the content size
    await tab.emulation.setDeviceMetricsOverride(pageMetrics.contentSize.width,
        pageMetrics.contentSize.height, 1, false);

    // Capture the screenshot
    String screenshot = await tab.page.captureScreenshot();

    // Save it to a file
    await File.fromUri(Platform.script.resolve('_github.png'))
        .writeAsBytes(base64.decode(screenshot));
  });
}

Take a screenshot of a specific node in the page

import 'dart:convert';
import 'dart:io';
import 'package:chrome_dev_tools/chrome_dev_tools.dart';
import 'package:chrome_dev_tools/domains/page.dart';
import 'package:chrome_dev_tools/domains/runtime.dart';
import 'utils.dart';

main() {
  chromeTab('https://www.github.com', (Tab tab) async {
    // A small helper to wait until the network is quiet
    await tab.waitUntilNetworkIdle();

    // Execute some Javascript to get the rectangle that we want to capture
    EvaluateResult result = await tab.runtime.evaluate(
        '''document.querySelector('form[action="/join"]').getBoundingClientRect();''');

    // Convert the `EvaluateResult` to a Map with all the javascript properties
    Map rect = await tab.remoteObjectProperties(result.result);

    Viewport clip = Viewport(
        x: rect['x'],
        y: rect['y'],
        width: rect['width'],
        height: rect['height'],
        scale: 1);

    // Capture the screenshot with the clip region
    String screenshot = await tab.page.captureScreenshot(clip: clip);

    // Save it to a file
    await File.fromUri(Platform.script.resolve('_github_form.png'))
        .writeAsBytes(base64.decode(screenshot));
  });
}

Create a static version of a Single Page Application

import 'package:chrome_dev_tools/chrome_dev_tools.dart';
import 'package:chrome_dev_tools/domains/dom_snapshot.dart';
import 'utils.dart';

main() {
  chromeTab('https://www.google.com', (Tab tab) async {
    // A small helper to wait until the network is quiet
    await tab.waitUntilNetworkIdle();

    // Take a snapshot of the DOM of the current page
    // ignore: deprecated_member_use
    GetSnapshotResult result = await tab.domSnapshot.getSnapshot([]);

    // Iterate the nodes and output some HTML.
    for (DOMNode node in result.domNodes) {
      String nodeString = '<${node.nodeName}';
      if (node.attributes != null) {
        nodeString +=
            ' ${node.attributes.map((n) => '${n.name}="${n.value}"').join(' ')}';
      }
      nodeString += '>';
      //This example needs a lot more work to output correct HTML
      print(nodeString);
    }
  });
}

Or more simply

import 'package:chrome_dev_tools/chrome_dev_tools.dart';
import 'utils.dart';

main() {
  chromeTab('https://www.google.com', (Tab tab) async {
    // A small helper to wait until the network is quiet
    await tab.waitUntilNetworkIdle();

    // Execute some javascript to serialize the document
    String pageContent =
        await tab.evaluate('document.documentElement.outerHTML');

    print(pageContent);
  });
}

Changelog

1.1.0

  • Update protocol
  • Increase default chrome version (599821)

1.0.0

  • First stable version
  • Tweak generated code to look better

0.0.5

  • Dart 2
  • Upgrade chrome to 579032
  • Update protocol

0.0.4

  • Upgrade chrome to 557152
  • Update protocol
  • Add a simple helper for "evaluate" Javascript
  • Rename classes *Manager to *Api

0.0.3+1

  • Upgrade chrome
  • Add an incognito mode

0.0.3

  • Expose the domains throught some getters in the Tab class.

0.0.2

  • Mark deprecated members with @deprecated attribute
  • Use "Chrome" word in the API instead of "Chromium".

0.0.1+2

  • Setup travis-ci

0.0.1

  • Initial version

example/example.dart

import 'package:chrome_dev_tools/chrome_dev_tools.dart';
import 'package:chrome_dev_tools/chrome_downloader.dart';
import 'package:logging/logging.dart';

// ignore_for_file: unused_local_variable

main() async {
  // Setup a logger if you want to see the raw chrome protocol
  Logger.root
    ..level = Level.ALL
    ..onRecord.listen(print);

  // Download a version of Chrome in a cache folder.
  String chromePath = (await downloadChrome()).executablePath;

  // You can specify the cache location and a specific version of chrome
  var chromePath2 =
      await downloadChrome(cachePath: '.chrome', revision: 497674);

  // Or just use an absolute path to an existing version of Chrome
  String chromePath3 =
      r'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';

  // Start the `Chrome` process and connect to the DevTools
  // By default it is start in `headless` mode
  Chrome chrome = await Chrome.start(chromePath);

  // Open a new tab
  Tab myTab = await chrome.newTab('https://www.github.com');

  // Do something (see example/ folder).

  // Kill the process
  await chrome.close();
}

Use this package as a library

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  chrome_dev_tools: ^1.1.0

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or flutter packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:chrome_dev_tools/chrome_dev_tools.dart';
  
Version Uploaded Documentation Archive
1.1.0 Oct 25, 2018 Go to the documentation of chrome_dev_tools 1.1.0 Download chrome_dev_tools 1.1.0 archive
1.0.0 Aug 10, 2018 Go to the documentation of chrome_dev_tools 1.0.0 Download chrome_dev_tools 1.0.0 archive
0.0.5 Aug 10, 2018 Go to the documentation of chrome_dev_tools 0.0.5 Download chrome_dev_tools 0.0.5 archive
0.0.4 May 16, 2018 Go to the documentation of chrome_dev_tools 0.0.4 Download chrome_dev_tools 0.0.4 archive
0.0.3 May 1, 2018 Go to the documentation of chrome_dev_tools 0.0.3 Download chrome_dev_tools 0.0.3 archive
0.0.2 Apr 27, 2018 Go to the documentation of chrome_dev_tools 0.0.2 Download chrome_dev_tools 0.0.2 archive
0.0.1+1 Apr 25, 2018 Go to the documentation of chrome_dev_tools 0.0.1+1 Download chrome_dev_tools 0.0.1+1 archive
0.0.1 Apr 25, 2018 Go to the documentation of chrome_dev_tools 0.0.1 Download chrome_dev_tools 0.0.1 archive
Popularity:
Describes how popular the package is relative to other packages. [more]
59
Health:
Code health derived from static analysis. [more]
100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100
Overall:
Weighted score of the above. [more]
80
Learn more about scoring.

We analyzed this package on Oct 26, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.0.0
  • pana: 0.12.5

Platforms

Detected platforms: Flutter, other

Primary library: package:chrome_dev_tools/chrome_dev_tools.dart with components: io.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev.69 <3.0.0
archive ^2.0.0 2.0.4
http ^0.11.3 0.11.3+17 0.12.0
logging ^0.11.3 0.11.3+2
meta ^1.1.1 1.1.6
path ^1.4.1 1.6.2
Transitive dependencies
args 1.5.0
async 2.0.8
charcode 1.1.2
collection 1.14.11
convert 2.0.2
crypto 2.0.6
http_parser 3.1.3
source_span 1.4.1
string_scanner 1.0.4
typed_data 1.1.6
Dev dependencies
dart_style ^1.1.0
shelf ^0.7.2
shelf_static ^0.2.7
test any