exposeFunction method

Future<void> exposeFunction(
  1. String name,
  2. Function callbackFunction
)

The method adds a function called name on the page's window object. When called, the function executes puppeteerFunction in Dart and returns a Promise which resolves to the return value of puppeteerFunction.

If the puppeteerFunction returns a Future, it will be awaited.

NOTE Functions installed via page.exposeFunction survive navigations.

An example of adding an md5 function into the page:

import 'dart:convert';
import 'package:puppeteer/puppeteer.dart';
import 'package:crypto/crypto.dart' as crypto;

void main() async {
  var browser = await puppeteer.launch();
  var page = await browser.newPage();
  page.onConsole.listen((msg) => print(msg.text));
  await page.exposeFunction('md5',
      (String text) => crypto.md5.convert(utf8.encode(text)).toString());
  await page.evaluate(r'''async () => {
            // use window.md5 to compute hashes
            const myString = 'PUPPETEER';
            const myHash = await window.md5(myString);
            console.log(`md5 of ${myString} is ${myHash}`);
          }''');
  await browser.close();
}

An example of adding a window.readfile function into the page:

import 'dart:io';
import 'package:puppeteer/puppeteer.dart';

void main() async {
  var browser = await puppeteer.launch();
  var page = await browser.newPage();
  page.onConsole.listen((msg) => print(msg.text));
  await page.exposeFunction('readfile', (String path) async {
    return File(path).readAsString();
  });
  await page.evaluate('''async () => {
            // use window.readfile to read contents of a file
            const content = await window.readfile('test/assets/simple.json');
            console.log(content);
          }''');
  await browser.close();
}

Parameters:

  • name: Name of the function on the window object

Implementation

//- [puppeteerFunction]: Callback function which will be called in Dart's context.
Future<void> exposeFunction(String name, Function callbackFunction) async {
  if (_pageBindings.containsKey(name)) {
    throw Exception(
        'Failed to add page binding with name $name: window["$name"] already exists!');
  }
  _pageBindings[name] = callbackFunction;

  var expression = evaluationString(_addPageBinding, [name]);
  await devTools.runtime.addBinding(name);
  await devTools.page.addScriptToEvaluateOnNewDocument(expression);
  await Future.wait(
      frameManager.frames.map((frame) => frame.evaluate(expression)));
}