2020-02-13 12:23:19 +03:00
|
|
|
/* eslint-env node */
|
|
|
|
|
2019-01-29 18:18:42 +03:00
|
|
|
"use strict";
|
|
|
|
|
2019-12-02 18:39:51 +03:00
|
|
|
// Node.js script to test basic CDP behaviors against Firefox and Chromium.
|
|
|
|
//
|
|
|
|
// Install chrome-remote-interface, the npm package for a CDP client in node:
|
|
|
|
//
|
|
|
|
// % npm install chrome-remote-interface
|
|
|
|
//
|
|
|
|
// Run Firefox or Chromium with server turned on:
|
|
|
|
//
|
|
|
|
// % ./mach run --remote-debugging-port 9222
|
|
|
|
// % firefox --remote-debugging-port 9222
|
|
|
|
// % chromium-browser --remote-debugging-port=9222
|
|
|
|
//
|
|
|
|
// Then run this script:
|
|
|
|
//
|
|
|
|
// % node demo.js
|
|
|
|
|
2019-01-29 18:18:42 +03:00
|
|
|
const CDP = require("chrome-remote-interface");
|
|
|
|
|
|
|
|
async function demo() {
|
|
|
|
let client;
|
|
|
|
try {
|
|
|
|
client = await CDP();
|
2020-02-13 12:23:19 +03:00
|
|
|
const { Log, Page, Runtime } = client;
|
2019-06-19 01:05:56 +03:00
|
|
|
|
|
|
|
// Bug 1553756, Firefox requires `contextId` argument to be passed to
|
|
|
|
// Runtime.evaluate, so fetch the current context id it first.
|
|
|
|
Runtime.enable();
|
|
|
|
const { context } = await Runtime.executionContextCreated();
|
|
|
|
const contextId = context.id;
|
|
|
|
|
|
|
|
let { result } = await Runtime.evaluate({
|
|
|
|
expression: "this.obj = {foo:true}; this.obj",
|
|
|
|
contextId,
|
|
|
|
});
|
2019-05-13 19:10:20 +03:00
|
|
|
console.log("1", result);
|
2019-06-19 01:05:56 +03:00
|
|
|
({ result } = await Runtime.evaluate({
|
|
|
|
expression: "this.obj",
|
|
|
|
contextId,
|
|
|
|
}));
|
2019-05-13 19:10:20 +03:00
|
|
|
console.log("2", result);
|
2019-06-19 01:05:56 +03:00
|
|
|
({ result } = await Runtime.evaluate({
|
|
|
|
expression: "this.obj.foo",
|
|
|
|
contextId,
|
|
|
|
}));
|
2019-05-13 19:10:20 +03:00
|
|
|
console.log("3", result);
|
|
|
|
|
2019-01-29 18:18:42 +03:00
|
|
|
// receive console.log messages and print them
|
|
|
|
Log.enable();
|
2020-02-13 12:23:19 +03:00
|
|
|
Log.entryAdded(({ entry }) => {
|
|
|
|
const { timestamp, level, text, args } = entry;
|
|
|
|
const msg = text || args.join(" ");
|
2019-02-12 17:06:33 +03:00
|
|
|
console.log(`${new Date(timestamp)}\t${level.toUpperCase()}\t${msg}`);
|
2019-01-29 18:18:42 +03:00
|
|
|
});
|
|
|
|
|
|
|
|
// turn on navigation related events, such as DOMContentLoaded et al.
|
|
|
|
await Page.enable();
|
|
|
|
|
2019-06-19 01:05:56 +03:00
|
|
|
const onLoad = Page.loadEventFired();
|
2020-02-13 12:23:19 +03:00
|
|
|
await Page.navigate({
|
|
|
|
url:
|
|
|
|
"data:text/html,test-page<script>console.log('foo');</script><script>'</script>",
|
|
|
|
});
|
2019-06-19 01:05:56 +03:00
|
|
|
await onLoad;
|
2019-01-29 18:18:42 +03:00
|
|
|
} catch (e) {
|
|
|
|
console.error(e);
|
|
|
|
} finally {
|
|
|
|
if (client) {
|
|
|
|
await client.close();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
demo();
|