Skip to content

Latest commit

 

History

History
356 lines (277 loc) · 13.8 KB

API.md

File metadata and controls

356 lines (277 loc) · 13.8 KB

API v0.9

This is a pre-release API, so it is a subject to change. Please use it at your own risk. Once API is validated, it will be bumped to v1.0 and preserved for backwards compatibility.

Table of Contents

carlo.enterTestMode()

Enters headless test mode. In the test mode, Puppeteer browser and pages are available via App.browserForTest() and Window.pageForTest() respectively. Please refer to the Puppeteer documentation for details on headless testing.

carlo.launch([options])

  • options <Object> Set of configurable options to set on the app. Can have the following fields:
    • width <number> App window width in pixels.
    • height <number> App window height in pixels.
    • top: <number> App window top offset in pixels.
    • left <number> App window left offset in pixels.
    • bgcolor <string> Background color using hex notation, defaults to '#ffffff'.
    • channel <Array<string>> Browser to be used, defaults to ['stable']:
      • 'stable' only uses locally installed stable channel Chrome.
      • 'canary' only uses Chrome SxS aka Canary.
      • 'chromium' downloads local version of Chromium compatible with the Puppeteer used.
      • 'rXXXXXX' a specific Chromium revision is used.
    • icon <Buffer|string> Application icon to be used in the system dock. Either buffer containing PNG or a path to the PNG file on the file system. This feature is only available in Chrome M72+. One can use 'canary' channel to see it in action before M72 hits stable.
    • title <string> Application title.
    • userDataDir <string> Path to a User Data Directory. This folder is created upon the first app launch and contains user settings and Web storage data. Defaults to '.profile'.
    • executablePath <string> Path to a Chromium or Chrome executable to run instead of the automatically located Chrome. If executablePath is a relative path, then it is resolved relative to current working directory. Carlo is only guaranteed to work with the latest Chrome stable version.
    • args <Array<string>> Additional arguments to pass to the browser instance. The list of Chromium flags can be found here.
  • return: <Promise<App>> Promise which resolves to the app instance.

Launches the browser.

class: App

event: 'exit'

Emitted when the App window closes.

App.browserForTest()

  • return: <Browser> Puppeteer browser object for testing.

App.createWindow([options])

  • options <Object> Set of configurable options to set on the app. Can have the following fields:
    • width <number> Window width in pixels, defaults to app width.
    • height <number> Window height in pixels, defaults to app height.
    • top <number> Window top in pixels, defaults to app top.
    • left <number> Window left in pixels, defaults to app left.
    • bgcolor <string> Background color using hex notation, defaults to app bgcolor.
  • return: <Promise<Window>> Promise which resolves to the window instance.

Creates a new app window.

App.evaluate(pageFunction[, ...args])

Shortcut to the main window's Window.evaluate(pageFunction[, ...args]).

App.exit()

Closes the browser window.

App.exposeFunction(name, carloFunction)

Shortcut to the main window's Window.exposeFunction(name, carloFunction)

App.load(uri[, ...params])

Shortcut to the main window's Window.load(uri[, ...params]).

App.mainWindow()

  • return: <Window> Returns main window.

Running app guarantees to have main window. If current main window closes, a next open window becomes the main one.

App.serveFolder(folder[, prefix])

  • folder <string> Folder with web content to make available to Chrome.
  • prefix <string> Prefix of the URL path to serve from the given folder.

Makes the content of the given folder available to the Chrome web app.

An example of adding a local www folder along with the node_modules:

main.js

const carlo = require('carlo');

carlo.launch().then(async app => {
  app.on('exit', () => process.exit());
  app.serveFolder(`${__dirname}/www`);
  app.serveFolder(`${__dirname}/node_modules`, 'node_modules');
  await app.load('index.html');
});

www/index.html

<style>body { white-space: pre; }</style>
<script>
fetch('node_modules/carlo/package.json')
    .then(response => response.text())
    .then(text => document.body.textContent = text);
</script>

App.serveOrigin(base[, prefix])

  • base <string> Base to serve web content from.
  • prefix <string> Prefix of the URL path to serve from the given folder.

Fetches Carlo content from the specified origin instead of reading it from the file system, eg http://localhost:8080. This mode can be used for the fast development mode available in web frameworks.

An example of adding the local http://localhost:8080 origin:

const carlo = require('carlo');

carlo.launch().then(async app => {
  app.on('exit', () => process.exit());
  app.serveOrigin('http://localhost:8080');  // <-- fetch from the local server
  app.serveFolder(__dirname);  // <-- won't be used
  await app.load('index.html');
});

App.setIcon(image)

  • image: <Buffer|string> Either buffer containing PNG or a path to the PNG file on the file system.

Specifies image to be used as an app icon in the system dock.

This feature is only available in Chrome M72+. One can use 'canary' channel to see it in action before M72 hits stable.

App.windows()

  • return: <Array<Window>> Returns all currently opened windows.

Running app guarantees to have at least one open window.

class: Window

Window.bounds()

Returns window bounds.

Window.bringToFront()

Brings this window to front.

Window.close()

Closes this window.

Window.evaluate(pageFunction[, ...args])

  • pageFunction <function|string> Function to be evaluated in the page context.
  • ...args <...Serializable> Arguments to pass to pageFunction.
  • return: <Promise<Serializable>> Promise which resolves to the return value of pageFunction.

If the function passed to the Window.evaluate returns a Promise, then Window.evaluate would wait for the promise to resolve and return its value.

If the function passed to the Window.evaluate returns a non-Serializable value, then Window.evaluate resolves to undefined.

const result = await window.evaluate(() => navigator.userAgent);
console.log(result);  // prints "<UA>" in Node console

Passing arguments to pageFunction:

const result = await window.evaluate(x => {
  return Promise.resolve(8 * x);
}, 7);
console.log(result);  // prints "56" in Node console

A string can also be passed in instead of a function:

console.log(await window.evaluate('1 + 2'));  // prints "3"
const x = 10;
console.log(await window.evaluate(`1 + ${x}`));  // prints "11"

Window.exposeFunction(name, carloFunction)

  • name <string> Name of the function on the window object.
  • carloFunction <function> Callback function which will be called in Carlo's context.
  • return: <Promise>

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

If the carloFunction returns a Promise, it will be awaited.

NOTE Functions installed via Window.exposeFunction survive navigations.

An example of adding an md5 function into the page:

main.js

const carlo = require('carlo');
const crypto = require('crypto');

carlo.launch().then(async app => {
  app.on('exit', () => process.exit());
  app.serveFolder(__dirname);
  await app.exposeFunction('md5', text =>  // <-- expose function
    crypto.createHash('md5').update(text).digest('hex')
  );
  await app.load('index.html');
});

index.html

<script>
md5('digest').then(result => document.body.textContent = result);
</script>

Window.fullscreen()

Turns the window into the full screen mode. Behavior is platform-specific.

Window.load(uri[, ...params])

  • uri <string> Path to the resource relative to the folder passed into serveFolder().
  • params <*> Optional parameters to pass to the web application. Parameters can be primitive types, <Array>, <Object> or rpc handles.
  • return: <Promise<*>> Result of the load() invocation, can be rpc handle.

Navigates the Chrome web app to the given uri, loads the target page and calls the load() function, provided by this page, in its context.

main.js

const carlo = require('carlo');
const { rpc } = require('carlo/rpc');

carlo.launch().then(async app => {
  app.serveFolder(__dirname);
  app.on('exit', () => process.exit());
  const frontend = await app.load('index.html', rpc.handle(new Backend));
  console.log(await frontend.hello('from backend'));
});

class Backend {
  hello(name) {
    console.log(`Hello ${name}`);
    return 'Backend is happy';
  }
}

index.html

<script>
class Frontend {
  hello(name) {
    console.log(`Hello ${name}`);
    return 'Frontend is happy';
  }
}

async function load(backend) {
  console.log(await backend.hello('from frontend'));
  return rpc.handle(new Frontend);
}
</script>
<body>Open console</body>

Window.maximize()

Maximizes the window. Behavior is platform-specific.

Window.minimize()

Minimizes the window. Behavior is platform-specific.

Window.pageForTest()

  • return: <Page> Puppeteer page object for testing.

Window.serveFolder(folder[, prefix])

  • folder <string> Folder with web content to make available to Chrome.
  • prefix <string> Prefix of the URL path to serve from the given folder.

Same as App.serveFolder(folder[, prefix]), but only applies to current window.

Window.serveOrigin(base[, prefix])

  • base <string> Base to serve web content from.
  • prefix <string> Prefix of the URL path to serve from the given folder.

Same as App.serveOrigin(base[, prefix]), but only applies to current window.

Window.setBounds(bounds)

  • bounds <Object> Window bounds:
    • top: <number> Top offset in pixels.
    • left <number> Left offset in pixels.
    • width <number> Width in pixels.
    • height <number> Height in pixels.
  • return: <Promise>

Sets window bounds. Parameters top, left, width and height are all optional. Dimension or the offset is only applied when specified.