• Stars
    star
    1,644
  • Rank 28,333 (Top 0.6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 12 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

WebPageTest API wrapper for NodeJS

WebPageTest Logo

Learn about more WebPageTest API Integrations in our docs

WebPageTest API Wrapper for NodeJS

Build Status NPM Version NPM Downloads

WebPageTest API Wrapper is a NPM package that wraps WebPageTest API for NodeJS as a module and a command-line tool.

For a better understanding of WebPageTest API Wrapper, here are some sample Node Recipies

Getting started

npm install webpagetest -g

Basics

Command line

webpagetest test https://docs.webpagetest.org/api/integrations/

Docker

Build

docker build -t webpagetest-api .

Run

docker run -it --rm webpagetest-api -k YOURAPIKEY test https://docs.webpagetest.org/api/integrations/

Module

const WebPageTest = require("webpagetest");

const wptServer = "www.webpagetest.org";
const wpt = new WebPageTest(wptServer, "YOUR_API_KEY");

const siteToTest = "https://docs.webpagetest.org/api/integrations/";
wpt.runTest(siteToTest, (err, data) => {
  console.log(err || data);
});

Command Line

Help

webpagetest --help

Commands

  • status [options] <id>: check test status
  • results [options] <id>: get test results
  • locations [options]: list locations and the number of pending tests
  • testers [options]: list testers status and details
  • test [options] <url_or_script>: run test, <url_or_script> can also be a path to a script file
  • testAndWait [options] <url_or_script>: run test and waits for the result, <url_or_script> can also be a path to a script file
  • testBalance [options]: get remaining tests for the account
  • restart <id>: restart test
  • cancel <id>: cancel running/pending test
  • har <id>: get the HTTP Archive (HAR) from test
  • pagespeed [options] <id>: get the Google Page Speed results (if available) from test
  • utilization [options] <id>: get the CPU, bandwidth and memory utilization data from test
  • request [options] <\id>: get the request data from test
  • timeline [options] <id>: get the Chrome Developer Tools Timeline data (if available) from test
  • netlog [options] <id>: get the Chrome Developer Tools Net log data (if available) from test
  • chrometrace [options] <id>: get the Chrome Trace data (if available) from test
  • console [options] <id>: get the browser console log data (if available) from test
  • testinfo <id>: get test request info/details
  • history [days]: get history of previously run tests
  • googlecsi [options] <id>: get Google CSI data (Client Side Instrumentation)
  • response [options] <id>: get response body for text resources
  • waterfall [options] <id>: get the waterfall PNG image
  • screenshot [options] <id>: get the fully loaded page screenshot in JPG format (PNG if in full resolution)
  • video [options] <tests>: create a video from <tests> (comma separated test ids)
  • player <id>: get a html5 player for a video <id>
  • listen [options] [port]: start webpagetest-api server on port [7791]
  • batch <file>: run commands in batch, i.e. one command per line from <file> in parallel

Options

Common (works for all commands)

  • -s, --server <server>: the WPT server URL [https://www.webpagetest.org]
  • -d, --dryrun: just return the RESTful API URL
  • -o, --out <file>: place the output into <file>. Defaults to stdout

The default WPT server can also be specified via environment variable WEBPAGETEST_SERVER

Test (works for test command only)

  • -l, --location <location>: location to test from
  • -y, --connectivity <profile>: connectivity profile -- requires location to be specified -- (Cable|DSL|3GSlow|3G|3GFast|4G|LTE|Edge|2G|Dial|FIOS|Native|custom) [Cable]
  • -r, --runs <number>: number of test runs [1]
  • -f, --first: skip the Repeat View test
  • -v, --video: capture video
  • -p, --private: keep the test hidden from the test log
  • -L, --label <label>: label for the test
  • -i, --onload: stop test at document complete. typically, tests run until all activity stops
  • -S, --noscript: disable javascript (IE, Chrome, Firefox)
  • -C, --clearcerts: clear SSL certificate caches
  • -R, --ignoressl: ignore SSL certificate errors, e.g. name mismatch, self-signed certificates, etc
  • -T, --standards: forces all pages to load in standards mode (IE only)
  • -u, --tcpdump: capture network packet trace (tcpdump)
  • -O, --bodies: save response bodies for text resources
  • -K, --keepua: do not add PTST to the original browser User Agent string
  • -m, --dom <element>: DOM element to record for sub-measurement
  • -N, --duration <seconds>: minimum test duration in seconds
  • --injectScript <string>: JavaScript to run after the document has started loading
  • -E, --tester <name>: run the test on a specific PC (name must match exactly or the test will not run)
  • -W, --mobile: (experimental) emulate mobile browser: Chrome mobile user agent, 640x960 screen, 2x scaling and fixed viewport (Chrome only)
  • --device <string>: device name from mobile_devices.ini to use for mobile emulation (only when --mobile is specified to enable emulation and only for Chrome)
  • -M, --timeline: capture Developer Tools Timeline (Chrome only)
  • -J, --callstack: set between 1-5 to include the JS call stack. must be used in conjunction with timeline (increases overhead) (Chrome only)
  • -q, --chrometrace: capture chrome trace (about://tracing) (Chrome only)
  • --tracecategories <categories>>: trace categories (when chrometrace enabled) (Chrome only)
  • -G, --netlog: capture Network Log (Chrome only)
  • -Q, --datareduction: enable data reduction on Chrome 34+ Android (Chrome only)
  • -x, --useragent <string>: custom user agent string (Chrome only)
  • -X, --cmdline <switches>: use a list of custom command line switches (Chrome only)
  • -g, --login <username>: username for authenticating tests (http authentication)
  • -w, --password <password>: password for authenticating tests (http authentication)
  • -t, --sensitive: discard script and http headers in the result
  • -H, --noheaders: disable saving of the http headers (as well as browser status messages and CPU utilization)
  • -b, --block <urls>: space-delimited list of urls to block (substring match)
  • -Z, --spof <domains>: space-delimited list of domains to simulate failure by re-routing to blackhole.webpagetest.org to silently drop all requests
  • -c, --custom <script>: execute arbitrary javascript at the end of a test to collect custom metrics
  • -a, --authtype <type>: type of authentication: 0 = Basic, 1 = SNS [0]
  • -n, --notify <e-mail>: e-mail address to notify with the test results
  • -B, --pingback <url>: URL to ping when the test is complete (the test ID will be passed as an "id" parameter)
  • -D, --bwdown <bandwidth>: download bandwidth in Kbps (used when specifying a custom connectivity profile)
  • -U, --bwup <bandwidth>: upload bandwidth in Kbps (used when specifying a custom connectivity profile)
  • -bw, --browserwidth <pixels>: Browser window width (in display pixels)
  • -bh, --browserheight <pixels>: Browser window height (in display pixels)
  • -vh, --viewportheight <pixels>: Viewport Height in css pixels
  • -vw, --viewportwidth <pixels>: Viewport Width in css pixels
  • -dpr, --devicetopixelratio <ratio>: Device To Pixel Ratio
  • -au, --appendua <string>: String to append to the user agent string. This is in addition to the default PTST/ver string
  • -tt, --testtype <string>: For running alternative test types, can specify traceroute or lighthouse
  • -pr, --profiler <number>: Set to 1 to enable the V8 sampling profiler (Chromium only)
  • -avif, --disableAVIF <number>: Set to 1 to disable AVIF support (Chromium 88+)
  • -webp, --disableWEBP <number>: Set to 1 to disable WEBP support (Chromium 88+)
  • -jxl, --disableJXL <number>: Set to 1 to disable JXL support (Chromium 88+)
  • -dts, --dtShaper <number>: Set to 1 to use Chrome's built-in traffic-shaping instead of the packet-level netem shaping usually used by the test agents
  • -Y, --latency <time>: first-hop Round Trip Time in ms (used when specifying a custom connectivity profile)
  • -P, --plr <percentage>: packet loss rate - percent of packets to drop (used when specifying a custom connectivity profile)
  • -z, --noopt: disable optimization checks (for faster testing)
  • -I, --noimages: disable screen shot capturing
  • -F, --full: save a full-resolution version of the fully loaded screen shot as a PNG
  • -j, --jpeg <level>: jpeg compression level (30-100) for the screen shots and video capture
  • -A, --medianvideo: store the video from the median run when capturing video is enabled
  • --htmlbody: save the content of only the base HTML response
  • --tsview <id>: test name to use when submitting results to tsviewdb (for private instances that have integrated with tsviewdb)
  • --tsviewconfigs <string>: configs to use when submitting results to tsviewdb (for private instances that have integrated with tsviewdb)
  • --affinity <string>: string to hash test to a specific test agent. tester will be picked by index among available testers
  • --priority <number>: change test priority (0-9) [enforced by API key, otherwise 5]
  • --continuous: capture video continuously (unstable/experimental, may cause tests to fail)
  • --spdy3: force SPDY version 3 (Chrome only)
  • --swrender: force software rendering, disable GPU acceleration (Chrome only)
  • --poll <interval>: poll for results after test is scheduled at every seconds [5]
  • --wait <hostname:port>: wait for test results informed by agent once complete listening on : [hostname:first port available above 8000]
  • --timeout <seconds>: timeout for polling and waiting results [no timeout]
  • --lighthouse: perform lighthouse test (Chrome only, Linux agent only)
  • -thc, --throttleCPU <number>: custom cpu throttle

API Key (works for test, restart,locations, testBalance and cancel commands)

  • -k, --key <api_key>:API key (if assigned). Contact the WebPageTest server administrator for a key if required or request an API key for limited testing at webpagetest.org/getkey.php

Request (works for status, results, locations, testers and test commands)

  • -e, --request <id>: echo request ID, useful to track asynchronous requests

Results (works for results and test commands)

  • -b, --breakdown: include the breakdown of requests and bytes by mime type
  • -D, --domains: include the breakdown of requests and bytes by domain
  • -p, --pagespeed: include the PageSpeed score in the response (may be slower)
  • -R, --requests: include the request data in the response (slower and results in much larger responses)
  • -m, --median <metric>: set the metric used to calculate median for multiple runs tests [loadTime]
  • --medianrun <metric>: set the run used for median for multiple runs tests [median]
  • -S, --specs <json_or_file>: set the specs for performance test suite
  • -r, --reporter <name>: set performance test suite reporter output: [dot]|spec|tap|xunit|list|progress|min|nyan|landing|json|doc|markdown|teamcity

Run (works for pagespeed, utilization, request, timeline, netlog, chrometrace, console, googlecsi, response, waterfall and screenshot commands)

  • -r, --run <number>: which run number on a multiple runs test [1]
  • -c, --cached: get the Repeat View (cached view) instead of default First View (primed cache)

Image (works for waterfall and screenshot commands)

  • -t, --thumbnail: get the thumbnail of actual image
  • -u, --uri: return the base64 string representation (inline) of actual image

Screenshot (works for screenshot command only)

  • -f, --full: get full resolution screenshot in PNG format if available
  • -n, --render: get the page screenshot at the Start Render point (i.e.: when something was first displayed on screen)
  • -p, --complete: get the page screenshot at the Document Complete point (i.e.: when window.onload was fired)

Waterfall (works for waterfall command only)

  • -T, --type <chart>: set the chart type: waterfall or connection [waterfall]
  • -M, --mime: set chart coloring by MIME type [false]
  • -w, --width <px>: chart image width in px (300-2000) [930]
  • -m, --max <seconds>: set maximum time in seconds [automatic]
  • -R, --requests <items>: filter requests (e.g.:1,2,3,4-9,8) [all]
  • -C, --nocpu: hide CPU utilization [false]
  • -b, --nobandwidth: hide bandwidth utilization [false]
  • -e, --noellipsis: hide ellipsis (...) for missing items [false]
  • -l, --nolabels: hide labels for requests (URL) [false]

Video (works for video command only)

  • -e, --end <end_point>: frame comparison end point: [visual]=visually complete | all=last change | doc=document complete | full=fully loaded

Response (works for response command only)

  • -R, --request <number>: the request number [1]

Listen (works for listen command only)

  • -k, --key <file>: private key file to use for SSL
  • -c, --cert <file>: public x509 certificate file to use for SSL

Examples

1. Get all available locations

$ webpagetest locations
{
  "response": {
    "statusCode": 200, "statusText": "Ok",
    "data": {
      "location": [
        ...
        {
          "id": "SanJose_IE9",
          "Label": "San Jose, CA USA (IE 9,Chrome,Firefox)",
          "location": "SanJose_IE9",
          "Browser": "IE 9",
          "PendingTests": {
            "p1": 0, "p2": 0, "p3": 0, "p4": 0, "p5": 2, "p6": 2, "p7": 0,
            "p8": 0, "p9": 0, "Total": 7, "HighPriority": 2, "LowPriority": 4,
            "Testing": 1, "Idle": 0
          }
        },
        ...
      ]
    }
  }
}

2. Get API available locations

webpagetest locations --key 1F2A3K4E5
{
  "response": {
    "statusCode": 200, "statusText": "Ok",
    "data": {
      "location": [
        ...
        {
          "id": "SanJose_IE9",
          "Label": "San Jose, CA USA (IE 9,Chrome,Firefox)",
          "location": "SanJose_IE9",
          "Browser": "IE 9",
          "PendingTests": {
            "p1": 0, "p2": 0, "p3": 0, "p4": 0, "p5": 2, "p6": 2, "p7": 0,
            "p8": 0, "p9": 0, "Total": 7, "HighPriority": 2, "LowPriority": 4,
            "Testing": 1, "Idle": 0
          }
        },
        ...
      ]
    }
  }
}

3. Run test on https://docs.webpagetest.org/api/integrations/ from San Jose on IE9

webpagetest test https://docs.webpagetest.org/api/integrations/ --key 1F2A3K4E5 --location SanJose_IE9
{
  "statusCode": 200,
  "statusText": "Ok",
  "data": {
    "testId": "121025_PT_N8K",
    "ownerKey": "868cb2813a0f376a977dd1a24ab041b4f12361b3",
    "jsonUrl": "https://www.webpagetest.org/results.php?test=121025_PT_N8K&f=json",
    "xmlUrl": "https://www.webpagetest.org/xmlResult.php?test=121025_PT_N8K",
    "userUrl": "https://www.webpagetest.org/results.php?test=121025_PT_N8K",
    "summaryCSV": "https://www.webpagetest.org/csv.php?test=121025_PT_N8K",
    "detailCSV": "https://www.webpagetest.org/csv.php?test=121025_PT_N8K&amp;requests=1"
  }
}

4. Check current test status

webpagetest status 121025_PT_N8K
{
  "statusCode": 101,
  "statusText": "Test Pending",
  "data": {
    "statusCode": 101,
    "statusText": "Test Pending",
    "testId": "121025_PT_N8K",
    "runs": 1,
    "fvonly": 0,
    "location": "SanJose_IE9"
  }
}

5. Get test results

webpagetest results 121025_PT_N8K
{
  "response": {
    "statusCode": 200, "statusText": "Ok",
    "data": {
      "testId": "121025_PT_N8K",
      "summary": "https://www.webpagetest.org/result/121025_PT_N8K/",
      "testUrl": "https://docs.webpagetest.org/api/integrations/",
      "location": "SanJose_IE9",
      "connectivity": "DSL",
      "bwDown": 1500, "bwUp": 384, "latency": 50, "plr": 0,
      "completed": "Thu, 25 Oct 2012 23:42:11 +0000",
      "runs": 1, "successfulFVRuns": 1,
      "average": {
        "firstView": {
          "loadTime": 3942, "TTFB": 1518,
          "bytesIn": 963405, "bytesInDoc": 431612,
          "requests": 32, "requestsDoc": 19,
          "render": 2509, "fullyLoaded": 7765,
          "docTime": 3942, "domTime": 0,
          "titleTime": 1641, "avgRun": 1
        }
      },
      ...
    }
  }
}

6. Get test waterfall thumbnail from repeat view as data URI

webpagetest waterfall 121025_PT_N8K --thumbnail --cached --uri
{
  "type": "image/png",
  "data": "iVBORw0KGgoAAAANSUhEUgA...RK5CYII="
}

7. Get remaining tests count for the account

webpagetest testBalance --key 1F2A3K4E5
{
    "data": {
        "remaining": 1175
    }
}

Run test on https://docs.webpagetest.org/api/integrations/ and poll results every 5 seconds timing out in 60 seconds

webpagetest test https://docs.webpagetest.org/api/integrations/ --poll 5 --timeout 60

Or run test on https://docs.webpagetest.org/api/integrations/ and wait for results listening on localhost* port 8000**

webpagetest test https://docs.webpagetest.org/api/integrations/ --wait 8000
{
  "response": {
    "statusCode": 200, "statusText": "Ok",
    "data": {
      "testId": "121025_PT_N8K",
      "testUrl": "https://docs.webpagetest.org/api/integrations/",
      ...
      "median": {
        "firstView": {
          "loadTime": 3942, "TTFB": 1518,
          "render": 2509, "fullyLoaded": 7765,
          ...
        }
      },
      ...
    }
  }
}

* hostname and port are optional, defaults to <system hostname>:<8000> ** localhost and port must be reacheable from WebPageTest server

Module

Methods and options (including the one letter shorthands) are the same when using as a Node module, however a more verbose version of both commands (methods) and options (parameters) are available and encouraged to use for code clarity.

Methods

  • getTestStatus(id, options, callback)
  • getTestResults(id, options, callback)
  • getLocations(options, callback)
  • getTesters(options, callback)
  • getTestBalance(options, callback)
  • runTest(url_or_script, options, callback)
  • runTestAndWait(url_or_script, options, callback)
  • restartTest(id, options, callback)
  • cancelTest(id, options, callback)
  • getHARData(id, options, callback)
  • getPageSpeedData(id, options, callback)
  • getUtilizationData(id, options, callback)
  • getRequestData(id, options, callback)
  • getTimelineData(id, options, callback)
  • getNetLogData(id, options, callback)
  • getChromeTraceData(id, options, callback)
  • getConsoleLogData(id, options, callback)
  • getTestInfo(id, options, callback)
  • getHistory(days, options, callback)
  • getGoogleCsiData(id, options, callback)
  • getResponseBody(id, options, callback)
  • getWaterfallImage(id, options, callback)
  • getScreenshotImage(id, options, callback)
  • createVideo(tests, options, callback)
  • getEmbedVideoPlayer(id, options, callback)
  • listen(port, options, callback)
  • scriptToString(script)

Parameters

  • id: test ID string required
  • options: parameters object optional, see below
  • callback: the callback (error, data) _optional=> _
  • url_or_script: decoded url or script string required
  • port: port number optional [default: 7791]
  • script: script array in the format:
[
  {command1: 'value1'},
  {command2: 123},
  {command3: ['value1', 'value2', ... , 'valueN']},
  ...
  'commandN'}
]

Notes

  • getWaterfallImage and getScreenshotImage callback function has a third parameter info which is an object with {type: 'image/jpeg or png', encoding: 'utf8 or binary'}
  • scriptToString script array values 1-N are optional. e.g:
const script = wpt.scriptToString([
  { logData: 0 },
  { navigate: "http://foo.com/login" },
  { logData: 1 },
  { setValue: ["name=username", "johndoe"] },
  { setValue: ["name=password", "12345"] },
  { submitForm: "action=http://foo.com/main" },
  "waitForComplete",
]);

wpt.runTest(script, (err, data) => {
  console.log(err || data);
});

Options

Common (works for all methods with options parameter)

  • dryRun: Boolean, if true, method does not make an actual request to the API Server but rather returns an object with url which contains the actual URL to make the GET request to WebPageTest API Server
  • server: String, if specified, overrides the WebPageTest server informed in the constructor only for that method call

Test (works with runTest and runTestAndWait)

  • location: String, location to test from
  • connectivity: String, connectivity profile -- requires location to be specified -- (Cable|DSL|3GSlow|3G|3GFast|4G|LTE|Edge|2G|Dial|FIOS|Native|custom) [Cable]
  • runs: Number, number of test runs [1]
  • firstViewOnly: Boolean, skip the Repeat View test
  • video: Boolean, capture video
  • private: Boolean, keep the test hidden from the test log
  • label: String, label for the test
  • stopAtDocumentComplete: Boolean, stop test at document complete. typically, tests run until all activity stops
  • disableJavaScript: Boolean, disable JavaScript (IE, Chrome, Firefox)
  • clearCerts: Boolean, clear SSL certificate caches
  • ignoreSSL: Boolean, ignore SSL certificate errors, e.g. name mismatch, self-signed certificates, etc
  • disableCompatibilityView: Boolean, forces all pages to load in standards mode (IE only)
  • tcpDump: Boolean, capture network packet trace (tcpdump)
  • saveResponseBodies: Boolean, save response bodies for text resources
  • keepOriginalUserAgent: Boolean, do not add PTST to the original browser User Agent string
  • domElement: String, DOM element to record for sub-measurement
  • minimumDuration: Number, minimum test duration in seconds
  • tester: String, run the test on a specific PC (name must match exactly or the test will not run)
  • emulateMobile: Boolean, (experimental) emulate mobile browser: Chrome mobile user agent, 640x960 screen, 2x scaling and fixed viewport (Chrome only)
  • device: String, device name from mobile_devices.ini to use for mobile emulation (only when emulateMobile=true is specified to enable emulation and only for Chrome)
  • timeline: Boolean, capture Developer Tools Timeline (Chrome only)
  • timelineCallStack: Boolean, set between 1-5 to include the JS call stack. must be used in conjunction with timeline (increases overhead) (Chrome only)
  • chromeTrace: Boolean, capture chrome trace (about://tracing) (Chrome only)
  • netLog: Boolean, capture Network Log (Chrome only)
  • dataReduction: Boolean, enable data reduction on Chrome 34+ Android (Chrome only)
  • userAgent: String, custom user agent string (Chrome only)
  • commandLine: String, use a list of custom command line switches (Chrome only)
  • login: String, username for authenticating tests (http authentication)
  • password: String, password for authenticating tests (http authentication)
  • sensitive: Boolean, discard script and http headers in the result
  • disableHTTPHeaders: Boolean, disable saving of the http headers (as well as browser status messages and CPU utilization)
  • block: String, space-delimited list of urls to block (substring match)
  • spof: String, space-delimited list of domains to simulate failure by re-routing to blackhole.webpagetest.org to silently drop all requests
  • customMetrics: String, execute arbitrary JavaScript at the end of a test to collect custom metrics
  • authenticationType: Number, type of authentication: 0 = Basic, 1 = SNS [0]
  • notifyEmail: String, e-mail address to notify with the test results
  • pingback: String, URL to ping when the test is complete (the test ID will be passed as an "id" parameter)
  • bandwidthDown: String, download bandwidth in Kbps (used when specifying a custom connectivity profile)
  • bandwidthUp: String, upload bandwidth in Kbps (used when specifying a custom connectivity profile)
  • browserwidth: String, Browser window width (in display pixels)
  • browserheight: String, Browser window height (in display pixels)
  • viewportheight: String, Viewport Height in css pixels
  • viewportwidth: String, Viewport Width in css pixels
  • devicetopixelratio: String, Device To Pixel Ratio
  • appendua: String, String to append to the user agent string. This is in addition to the default PTST/ver string
  • testtype: String, For running alternative test types, can specify traceroute or lighthouse
  • profiler: Number, Set to 1 to enable the V8 sampling profiler (Chromium only)
  • disableAVIF: Number, Set to 1 to disable AVIF support (Chromium 88+)
  • disableWEBP: Number, Set to 1 to disable WEBP support (Chromium 88+)
  • disableJXL: Number, Set to 1 to disable JpegXL support (Chromium 88+)
  • dtShaper: Number, Set to 1 to use Chrome's built-in traffic-shaping instead of the packet-level netem shaping usually used by the test agents
  • latency: String, first-hop Round Trip Time in ms (used when specifying a custom connectivity profile)
  • packetLossRate: Number, packet loss rate - percent of packets to drop (used when specifying a custom connectivity profile)
  • disableOptimization: Boolean, disable optimization checks (for faster testing)
  • disableScreenshot: Boolean, disable screen shot capturing
  • fullResolutionScreenshot: Boolean, save a full-resolution version of the fully loaded screen shot as a PNG
  • jpegQuality: Number, jpeg compression level (30-100) for the screen shots and video capture
  • medianVideo: Boolean, store the video from the median run when capturing video is enabled
  • htmlBody: Boolean, save the content of only the base HTML response
  • tsView: String, test name to use when submitting results to tsviewdb (for private instances that have integrated with tsviewdb)
  • tsViewConfigs: String, configs to use when submitting results to tsviewdb (for private instances that have integrated with tsviewdb)
  • affinity: String, string to hash test to a specific test agent. tester will be picked by index among available testers
  • priority: Number, change test priority (0-9) [enforced by API key, otherwise 5]
  • blockAds: Boolean, block ads defined by http://adblockplus.org
  • continuousVideoCapture: Boolean, capture video continuously (unstable/experimental, may cause tests to fail)
  • forceSpdy3: Boolean, force SPDY version 3 (Chrome only)
  • forceSoftwareRendering: Boolean, force software rendering, disable GPU acceleration (Chrome only)
  • pollResults: Number, poll for results after test is scheduled at every seconds [5]
  • waitResults: String, wait for test results informed by agent once complete listening on : [hostname:first port available above 8000]
  • timeout: String, timeout for polling and waiting results [no timeout]
  • lighthouse: Boolean, perform lighthouse test (Chrome only, Linux agent only)
  • throttleCPU: Number, custom cpu throttling

API Key (works for runTest, runTestAndWait, restartTest and cancelTest methods)

  • key: String, API key (if assigned). Contact the WebPageTest server administrator for a key if required

Request (works for getTestStatus getResults getLocations getTesters runTest and runTestAndWait methods)

  • requestId: String, echo request ID, useful to track asynchronous requests

Results (works for getResults runTest and runTestAndWait methods)

  • breakDown: Boolean, include the breakdown of requests and bytes by mime type
  • domains: Boolean, include the breakdown of requests and bytes by domain
  • pageSpeed: Boolean, include the PageSpeed score in the response (may be slower)
  • requests: Boolean, include the request data in the response (slower and results in much larger responses)
  • medianMetric: String, set the metric used to calculate median for multiple runs tests (default: loadTime)
  • specs: String, set the specs for performance test suite
  • reporter: String, set performance test suite reporter output: [dot]|spec|tap|xunit|list|progress|min|nyan|landing|json|doc|markdown|teamcity

Run (works for getPageSpeedData, getUtilizationData, getRequestData, getTimelineData, getNetLogData, getChromeTraceData, getConsoleLogData, getGoogleCsiData, getResponseBody, getWaterfallImage and getScreenshotImage methods)

  • run: Number, the test run number for multiple runs tests (default: 1, first test)
  • repeatView: Boolean, if true returns the repeat view (cached) data

Image (works for getWaterfallImage and getScreenshotImage methods)

  • thumbnail: Boolean, returns the thumbnail of actual image
  • dataURI: Boolean, returns the base64 string representation (inline) of actual image

Screenshot (works for getScreenshotImage method only)

  • fullResolution: Boolean, returns the full resolution screenshot in PNG format if available
  • startRender: Boolean, returns the page screenshot at the Start Render point (i.e.: when something was first displayed on screen)
  • documentComplete: Boolean, returns the page screenshot at the Document Complete point (i.e.: when window.onload was fired)

Waterfall (works for getWaterfallImage method only)

  • chartType: String, set the chart type: waterfall or connection [waterfall]
  • colorByMime: Boolean, set chart coloring by MIME type [false]
  • chartWidth Number: chart image width in px (300-2000) [930]
  • maxTime Number: set maximum time in seconds [automatic]
  • requests String: filter requests (e.g.:1,2,3,4-9,8) [all]
  • noCPU: Boolean, hide CPU utilization [false]
  • noBandwidth: Boolean, hide bandwidth utilization [false]
  • noEllipsis: Boolean, hide ellipsis (...) for missing items [false]
  • noLabels: Boolean, hide labels for requests (URL) [false]

Video (works for createVideo method only)

  • comparisonEndPoint String: frame comparison end point: [visual]=visually complete | all=last change | doc=document complete | full=fully loaded

Response (works for getResponseBody method only)

  • request Number: the request number [1]

Listen (works for listen method only)

  • key String: private key file path to use for SSL
  • cert String: public x509 certificate file path to use for SSL

Location (works for getLocations method only)

  • allLocations Boolean: if true, returns all available locations irrespective of API availability

Examples

1. Instantiating

const WebPageTest = require("webpagetest");

const wpt = new WebPageTest("my-wpt.foo.com"); // default: www.webpagetest.org
const wptPublic = new WebPageTest("www.webpagetest.org", "MY_API_KEY");

2. Get available locations

wpt.getLocations((err, data) => {
  console.log(err || data);
});

3. Run test on https://docs.webpagetest.org/api/integrations/ from San Jose on IE9

wpt.runTest(
  "https://docs.webpagetest.org/api/integrations/",
  { location: "SanJose_IE9" },
  (err, data) => {
    console.log(err || data);
  }
);

4. Check current test status

wpt.getTestStatus("121025_PT_N8K", (err, data) => {
  console.log(err || data);
});

5. Get test results

wpt.getTestResults("121025_PT_N8K", (err, data) => {
  console.log(err || data);
});

6. Get test waterfall thumbnail from repeat view as data URI

wpt.getWaterfallImage(
  "121025_PT_N8K",
  {
    thumbnail: true,
    repeatView: true,
    dataURI: true,
  },
  (err, data, info) => {
    console.log(err || data, info);
  }
);

Run test on https://docs.webpagetest.org/api/integrations/ and poll results every 5 seconds timing out in 60 seconds

wpt.runTest(
  "https://docs.webpagetest.org/api/integrations/",
  { pollResults: 5, timeout: 60 },
  (err, data) => {
    console.log(err || data);
  }
);

Or run test on https://docs.webpagetest.org/api/integrations/ and wait results listening on localhost* port 8000**

wpt.runTest(
  "https://docs.webpagetest.org/api/integrations/",
  { waitResults: "localhost:8000" },
  (err, data) => {
    console.log(err || data);
  }
);

* hostname and port are optional, defaults to <system hostname>:<8000>

** localhost:8000 must be reacheable from WebPageTest server

Server mode

WebPageTest API Wrapper comes with a handy RESTful API proxy

Command Line

webpagetest listen 8080 --server wpt.foo.com
server listening on port 8080
http://localhost:8080
curl http://localhost:8080/help
curl http://localhost:8080/test/webpagetest.org/?location=SanJose_IE9
webpagetest listen 8443 --key key.pem --cert cert.pem --server wpt.foo.com
server listening on port 8443
https://localhost:8443

Notes

  • port 8080 is optional, default port is 7791
  • wpt.foo.com is overriding the default www.webpagetest.org server but can still be overridden with server option
  • when --key and --cert are provided, HTTPS is used instead of default HTTP server

Module

const server = wpt.listen(8080, (err, data) => {
  if (err) throw err;
  console.log("listening on " + data.url);
}); // listen on port 8080 (optional), default port is 7791

setTimeout(() => {
  server.close(() => {
    console.log("server closed");
  });
}, 10000); // wait for 10s before stop listening

Batch

Batch command is available as command line only and loads a batch file containing one WebPageTest CLI command with options per line. It runs all commands in parallel, but returns an array of results in order as they appear in the batch file once all results are ready. The exit status code is the sum of all individual commands' exit status code.

By running

webpagetest batch commands.txt

where commands.txt contains:

test https://docs.webpagetest.org/api/integrations/ --first --location foo
test https://docs.webpagetest.org/api/integrations/ --first --location bar

It schedules the 2 tests above returning an array of size 2 in the same order as in commands.txt file:

[
  {
    "statusCode": 200, "statusText": "Ok",
    "data": {
      "testId": "130715_AB_C1D",
      ...
    }
  },
  {
    "statusCode": 200, "statusText": "Ok",
    "data": {
      "testId": "130715_CD_E2F",
      ...
    }
  }
]

With exit status 0 in case none of commands returns an error:

echo $?
0

By running multiple sync tests, i.e. with either --poll or --wait, all tests are scheduled and results are polled or wait in parallel; meaning, if tests are set to run in different locations or same location with multiple agents, the final result might come together, but the result array will only return once all tests are done. e.g.:

commands.txt:

test https://docs.webpagetest.org/api/integrations/ --first --location foo --poll --timeout 60
test https://docs.webpagetest.org/api/integrations/ --first --location bar --poll --timeout 60

Test Specs (Continuous Integration)

WebPageTest API Wrapper provides a simple seamless way to integrate WebPageTest with Continuous Integration tools.

See dedicated page

Tests

npm test

Issues

Have a bug/feature request? Please create an issue here on GitHub!

https://github.com/WebPageTest/webpagetest-api/issues

Author

WebPageTest

License

Copyright 2013 Twitter Inc. Copyright 2020 Google Inc. Copyright 2020 Marcel Duran and other contributors

Licensed under the MIT License


Learn about more WebPageTest API Integrations in our docs

More Repositories

1

WebPageTest

Official repository for WebPageTest
PHP
3,047
star
2

workflow-telemetry-action

Github action to collect metrics (CPU, memory, I/O, etc ...) from your workflows to help you debug and optimize your CI/CD pipeline
TypeScript
264
star
3

WebPageTest.bulk-tester

Google App Script for spreadsheet that uses the WPT API to bulk test URLs
JavaScript
259
star
4

WebPageTest.agent

Cross-platform WebPageTest agent
Python
210
star
5

WebPageTest.RUM-SpeedIndex

Calculate SpeedIndex measurements from the field
JavaScript
200
star
6

WebPageTest.github-action

Automatically test code changes in WebPageTest and enforce performance budgets
JavaScript
198
star
7

WebPageTest.docs

Documentation for WebPageTest
JavaScript
192
star
8

WebPageTest.visual-metrics

Calculate visual performance metrics from a video (Speed Index, Visual Complete, Incremental progress, etc)
Python
154
star
9

WebPageTest.win-shaper

Windows traffic-shaping packet filter
C++
126
star
10

WebPageTest.xrecord

Console app for capturing video on OS X (particularly from iOS devices)
Swift
122
star
11

WebPageTest.beacon-ml

Evaluate web beacon metrics for impact on business metrics
Python
75
star
12

WebPageTest.tsproxy

Traffic-shaping SOCKS5 proxy
Python
73
star
13

Pietrasanta-traceroute

C
39
star
14

Tracing.examples-kubernetes-java

Catchpoint Tracing examples for Java applications deploying to Kubernetes
Java
23
star
15

WebPageTest.slack

WebPageTest and Slack Integration
JavaScript
21
star
16

WebPageTest.api-recipes

A collection of useful recipes for the WebPageTest API
JavaScript
13
star
17

WebPageTest.agent-install

Automated scripts for installing dedicated wptagent instances
Shell
10
star
18

WebPageTest.iTether

Reverse-tether app for iOS
Python
9
star
19

WebPageTest.iWptBrowser

wkWebView browser shell for iOS WebPagetest agent (integrates with wptagent)
Swift
9
star
20

WebPageTest.server-install

Installation scripts for the WebPageTest server
Shell
9
star
21

WebPageTest.vscode-extension

JavaScript
7
star
22

foresight-test-kit-action

Action for optimizing your tests by listing test runs and with history
TypeScript
7
star
23

WebPageTest.recorder-chrome-extension

A Chrome extension for outputting user recording sessions as WebPageTest Custom Scripts
JavaScript
6
star
24

WebPageTest.pcap-parser

Parser to extract information from tcpdump pcap files for WebPageTest
Python
6
star
25

WebPageTest.recorder-to-script

Script to convert Chrome user flow recordings to WPT Custom Scripts
TypeScript
6
star
26

WebPageTest.trace-parser

Parser to extract information from Chrome Traces for WebPageTest
Python
6
star
27

foresight-issues

This is the place where the Foresight issues are put in the table
5
star
28

Integrations.SIP

Shell
5
star
29

foresight-workflow-kit-action

TypeScript
5
star
30

WebPageTest.extension-chrome

Chrome helper extension to launch WebPageTest for current URL
JavaScript
5
star
31

WebPageTest.adbwatch

Python app that monitors and kills the Android Debug Bridge when it stops working.
C++
4
star
32

WebPageTest.devtools-parser

Parse a remote dev tools event log and produce page-level and request information json files
Python
3
star
33

WebPageTest.healthcheck

HTTP Healthcheck responder for WebPageTest agents (wptagent)
Python
3
star
34

WebPageTest.etw

Windows ETW watcher for wptagent
C#
3
star
35

WebPageTest.browser-install

Automatically install and keep browsers up to date with the latest releases (on Windows)
Python
2
star
36

Community-Scripts

Repository for custom scripts.
Python
2
star
37

WebPageTest.chromehooks

Windows command-line utility to find the function offsets for SSL/TLS functions in Chrome using the public symbols
Python
2
star
38

WebPageTest.microsoft-teams-bot

JavaScript
2
star
39

Integrations.GoogleCloudMonitoring

JavaScript
2
star
40

WebPageTest.extension-firefox

Extension for Firefox to launch WebPageTest for current URL
JavaScript
2
star
41

Integrations.splunk

Python
1
star
42

Integrations.SumoLogic

1
star
43

WebPageTest.crawler

JavaScript
1
star
44

WebPageTest.battery-time

Browser-based battery life test suite. Used for measuring how long a device can run on a single charge.
1
star
45

terraform-provider-catchpoint

Go
1
star
46

foresight-client-sdk

Foresight API client SDK
Java
1
star
47

Integrations.NewRelic

New Relic Integrations uses catchpoint Test Data Webhook to send data to New Relic Platform, this is accomplished by using New Relic’s Metrics API. To complete this integration, we will rely on third party cloud function to accept the data from Catchpoint API, process it in the desired format and then push it to New Relic. With this integration we are enabling DevOps team to visualise Catchpoints digital experience data with New Relic’s Application Performance Monitoring (APM) data together.
JavaScript
1
star
48

WebPageTest.winres

Set the Windows desktop to the maximum supported by the monitor/video card. This is primarily used in a headless environment like EC2 to maximize the desktop for visual testing.
C++
1
star
49

WebPageTest.tcpdump

Windows tcpdump console app for wptagent (requires WinPCap)
C
1
star
50

Tracing.examples-kubernetes-go

Catchpoint Tracing examples for Go applications deploying to Kubernetes
Go
1
star
51

webpage-visually-complete

Visually Complete is calculated by reporting the time until roughly 80% of elements in the viewport have loaded. It references img, iframe, css, script, and subdocument elements in the Resource Timing API to determine the time from navigation to the page appearing loaded to an end user.
1
star