Browser JavaScript API Reference for axe DevTools for Web

Link to Browser JavaScript API Reference for axe DevTools for Web copied to clipboard

Discusses the Browser JavaScript APIs for axe DevTools for Web and their usage

Introduction

The axe DevTools API is designed to be an improvement over the previous generation of accessibility APIs. It provides the following benefits:

  • Runs in any modern browser
  • Designed to work with existing testing infrastructure
  • Runs locally; no connection to a third-party server is necessary
  • Performs violation checking on multiple levels of nested iframes
  • Provides a list of rules and elements that passed accessibility checking, ensuring rules have been run against the entire document

Getting Started

This section briefly describes how to use the axe DevTools APIs to analyze web page content and return a JSON object that lists any accessibility violations found.

The axe DevTools API can be used as part of a broader process that is performed on many, if not all, pages of a website. The API analyzes web page content and returns a JSON object that lists any accessibility violations found. Here is how to get started:

  1. Load page in the testing system
  2. Optionally, set configuration options for the JavaScript API (AxeDevTools.configure)
  3. Call analyze JavaScript API (AxeDevTools.run)
  4. Either assert against results or save them for later processing

API Reference

Overview

The axe DevTools APIs are provided in the JavaScript file axe-devtools.js. It must be included in the web page under test. Parameters are sent as JavaScript function parameters. Results are returned in JSON format.

API Notes

  • A Rule test is made up of sub-tests. Each sub-test is returned in an array of 'checks'
  • The "helpUrl" in the results object links to a broader description of the accessibility issue and suggested remediation. All of the links point to the Deque University help pages.

AxeDevTools.init

note

This API is not available through any of the language-specific bindings such as @axe-devtools/script-builder, as those bindings have their own APIs for achieving the same thing.

Purpose

Initialize the axe DevTools API to utilize one of the built-in standard rule sets.

Description

Initializes the axe DevTools engine, overriding the default rule set and enabling one of the standard rule subsets.

note

You should use either AxeDevTools.configure or AxeDevTools.init but not both, as they will overwrite each other.

Synopsis

AxeDevTools.init(ruleSetID);

Parameters

  • ruleSetID - optional String identifying the rule set. Current valid values are:

    • 508
    • en301549
    • ttv5
    • wcag2
    • wcag21
    • wcag22
    • wcag2aaa
    • wcag21aaa
    • wcag22aaa

Returns: undefined

AxeDevTools.ruleSets

note

This API is not available through any of the language-specific bindings such as @axe-devtools/script-builder as those bindings have their own APIs for achieving the same thing.

Purpose

An array of the standard rule set definitions

Description

Gives direct access to the standard rule set definition array. The array consists of JavaScript objects with the following structure:

{
  id: String identifier for the rule set,
  defn: Object containing the rule set definition
}

Example One

How to filter the array to find the WCAG 2 level A and AA rule set definition.

var rsets = AxeDevTools.ruleSets;
var wcag2 = rsets.filter(function (item) {
  return item.id === 'wcag2';
})[0].defn;

AxeDevTools.getRules

Purpose

To get information on all the rules in the system

Description

Returns a list of all rules with their ID and description.

Synopsis

AxeDevTools.getRules([Tag Name 1, Tag Name 2...]);

Parameters

  • tags - optional Array of tags used to filter returned rules. If omitted, it will return all rules.

Returns: Array of rules that match the input filter with each entry having a format of {ruleId: <id>, description: <desc>}

The current set of tags supported are listed in the following table:

Tag Name Accessibility Standard
wcag2a WCAG 2.0 Level A
wcag2aa WCAG 2.0 Level AA
wcag2aaa WCAG 2.0 Level AAA
wcag21a WCAG 2.1 Level A
wcag21aa WCAG 2.1 Level AA
wcag21aaa WCAG 2.1 Level AAA
wcag22a WCAG 2.2 Level A
wcag22aa WCAG 2.2 Level AA
wcag22aaa WCAG 2.2 Level AAA
section508 Section 508
EN-301-549 EN 301 549
TTv5 Trusted Tester v5
best-practice Best practices endorsed by Deque

Example 1

In this example, we pass the WCAG 2 A and AA tags into AxeDevTools.getRules to retrieve only those rules. The function call returns an array of rules.

Call: AxeDevTools.getRules(['wcag2aa', 'wcag2a']);

Returned Data:

[
  { ruleId: "area-alt", description: "Checks the <area> elements of image…" },
  { ruleId: "aria-allowed-attr", description: "Checks all attributes that start…" },
  { ruleId: "aria-required-attr", description: "Checks all elements that contain…" },]

AxeDevTools.configure

Purpose

To configure the format of the data used by axe DevTools. This can be used to add new rules, which must be registered with the library to execute.

Description

The user specifies the format of the JSON structure passed to the callback of AxeDevTools.run.

Synopsis

AxeDevTools.configure({
  branding: {
    brand: String,
    application: String
  },
  reporter: 'option',
  checks: [Object],
  rules: [Object]
});

Parameters

  • configurationOptions - Options object where the valid name/value pairs are:
    • branding - mixed (optional) Used to set the branding of the helpUrls.
      • brand - string (optional) sets the brand string--default: "worldspace"
      • application - string (optional) sets the application string--default: "AxeDevToolsAPI"
    • reporter - Used to set the output format that the AxeDevTools.run function will pass to the callback function
      • v1 to use the previous version's format: AxeDevTools.configure({ reporter: "v1" });
      • v2 to use the current version's format: AxeDevTools.configure({ reporter: "v2" });
    • checks - Used to add checks to the list of checks used by rules or to override the properties of existing checks.
      • The checks attribute is an array of check objects.
      • Each check object can contain the following attributes:
      • id - string (required). This uniquely identifies the check. If the check already exists, any supplied check properties will be overridden. The properties below marked required if new are optional when the check is overridden.
      • evaluate - function (required if new). This is the function that implements the check's functionality.
      • after - function (optional). This function gets called for checks that operate on a page-level basis to process the results from the iframes.
      • options - mixed (optional). This options object is passed to the evaluate function and is intended to be used to configure checks. It is the most common property intended to be overridden for existing checks.
      • matches - string (optional). This CSS selector string will filter the nodes passed into the evaluate function.
      • enabled - boolean (optional, default true). This indicates whether the check is on or off by default. Checks that are off are not evaluated, even when included in a rule. Overriding this is a common way to disable a particular check across multiple rules.
    • rules - Used to add rules to the existing set of rules or override existing rules' properties. The rules attribute is an array of rule objects. Each rule object can contain the following attributes:
      • id - string (required). This uniquely identifies the rule. If the rule already exists, it will be overridden with any attributes supplied. The attributes below that are marked as required are only required for new rules.
      • selector - string (optional, default *). A CSS selector used to identify the elements passed into the rule for evaluation.
      • excludeHidden - boolean (optional, default true). This indicates whether hidden elements are to be passed into the rule for evaluation.
      • enabled - boolean (optional, default true). Whether the rule is turned on (a common attribute for overriding).
      • pageLevel - boolean (optional, default false). This indicates whether the page operates only when the scope is the entire page. An example of a rule like this is the skip link rule. It is not recommended to override this property unless the implementation is also changed.
      • any - array (optional, default []). This is the list of checks that must all pass or there is a violation.
      • all - array (optional, default []). This is the list of checks that, if any fail, will generate a violation.
      • none - array (optional, default []). This is a list of the checks that, if none pass, will generate a violation.
      • tags - array (optional, default []). A list of the tags that classify the rule. In practice, you must supply some valid tags, or the default evaluation will not invoke the rule. The convention is to include the standard (WCAG 2 and/or section 508), the WCAG 2 level, the Section 508 paragraph, and the WCAG 2 success criteria. Tags are constructed by converting all letters to lowercase, removing spaces and periods, and concatenating the result. For example, WCAG 2 A success criteria 1.1.1 would become ["wcag2a", "wcag111"]
      • matches - string (optional, default *). A CSS selector that will exclude elements that do not match it.

Returns: Nothing

AxeDevTools.reset

Purpose

Reset the configuration to the default configuration.

Description

Override any previous calls to AxeDevTools.configure or AxeDevTools.reset and reset the configuration to the default configuration.

note

This will not unregister any new rules or checks that were registered but will reset the configuration back to the default configuration for everything else.

Synopsis

AxeDevTools.reset();

Parameters

None

Returns: undefined

AxeDevTools.run

Purpose

Analyze the currently loaded page.

Description

Runs several rules against the provided HTML page and returns the resulting issue list.

Synopsis

AxeDevTools.run(context, options, callback);

Parameters for AxeDevTools.run

  • context: (optional) Defines the scope of the analysis--the part of the DOM that you would like to analyze. This will typically be the document or a specific selector such as class name, ID, selector, etc.
  • options: (optional) Set of options passed into rules or checks, temporarily modifying them. This contrasts with AxeDevTools.configure, which is more permanent. See above for more information
  • callback: (optional) The callback function which receives either null or an error result as the first parameter, and the results object when the analysis has completed successfully or undefined if it did not.
context Parameter

By default, AxeDevTools.run will test the entire document. The context object is an optional parameter that specifies which element should and which should not be tested. It can be passed one of the following:

  1. An element reference that represents the portion of the document that must be analyzed
    • Example: To limit analysis to the <div id="content"> element: document.getElementById("content")
  2. A NodeList such as returned by document.querySelectorAll.
  3. A CSS selector that selects the portion of the document that must be analyzed. This includes:
    • A CSS selector as a class name (e.g., .classname)
    • A CSS selector as a node name (e.g., div)
    • A CSS selector of an element id (e.g., #tag)
  4. An include-exclude object (see below)
include and exclude Objects

The include-exclude object is a JSON object with two attributes: include and exclude. Either include or exclude is required. If only exclude is specified, include will default to the entire document.

  • A node, or
  • An array of arrays of CSS selectors

In most cases, the arrays will contain only one CSS selector. Multiple CSS selectors are only required if you want to include or exclude regions of a page that are inside iframes (or iframes within iframes within iframes). In this case, the first n-1 selectors select the iframe(s), and the nth selector selects the region(s) within the iframe.

context Parameter Examples
  1. Include the first item in the $fixture NodeList but exclude its first child

    {
      include: $fixture[0],
      exclude: $fixture[0].firstChild
    }
  2. Include the element with the ID of fix but exclude any divs within it

    {
      include: [['#fix']],
      exclude: [['#fix div']]
    }
  3. Include the whole document except any structures whose parent contains the class exclude1 or exclude2

    {
      exclude: [['.exclude1'], ['.exclude2']];
    }
options Parameter

The options parameter is a flexible way to configure how AxeDevTools.run operates. The different modes of operation are:

  • Run all rules corresponding to one of the accessibility standards.
  • Run all rules defined in the system except for the list of rules specified.
  • Run a specific set of rules provided as a list of rule IDs.
options Parameter Examples
  1. Run only Rules for an accessibility standard

    There are certain standards defined that can be used to select a set of rules. The defined standards and tag string are defined as follows:

    Tag Name Accessibility Standard
    wcag2a WCAG 2.0 Level A
    wcag2aa WCAG 2.0 Level AA
    wcag2aaa WCAG 2.0 Level AAA
    wcag21a WCAG 2.1 Level A
    wcag21aa WCAG 2.1 Level AA
    wcag21aaa WCAG 2.1 Level AAA
    wcag22a WCAG 2.2 Level A
    wcag22aa WCAG 2.2 Level AA
    wcag22aaa WCAG 2.2 Level AAA
    section508 Section 508
    EN-301-549 EN 301 549
    TTv5 Trusted Tester v5
    best-practice Best practices endorsed by Deque

    To run only WCAG 2.0 Level A rules, specify options as:

    {
      runOnly: {
       type: "tag",
       values: ["wcag2a"]
      }
    }

    To run both WCAG 2.0 Level A and Level AA rules, you must specify both wcag2a and wcag2aa:

    {
      runOnly: {
        type: "tag",
        values: ["wcag2a", "wcag2aa"]
      }
    }
  2. Run only a specified list of Rules

    If you only want to run certain rules, specify options as:

    {
      runOnly: {
        type: "rule",
        values: [ "ruleId1", "ruleId2", "ruleId3" ]
      }
    }

    This example will only run the rules with the id of ruleId1, ruleId2, and ruleId3. No other rule will run.

  3. Run all enabled Rules except for a list of rules

    The default operation for AxeDevTools.run is to run all WCAG 2.0 Level A and Level AA rules. If certain rules should be disabled from being run, specify options as:

    {
      "rules": {
        "color-contrast": { enabled: false },
        "valid-lang": { enabled: false }
      }
    }

    This example will disable the rules with the color-contrast or valid-lang ID. All other rules will run. The list of valid rule IDs is specified in the section below.

  4. Run a modified set of rules using tags and rule enable

    A modified set can be defined by combining runOnly with type set to the tags desired and using the rules option. This lets you include rules with unspecified tags and exclude rules with the specified tag or tags.

    {
      runOnly: {
        type: "tag",
        values: ["wcag2a"]
      },
      "rules": {
        "color-contrast": { enabled: true },
        "valid-lang": { enabled: false }
      }
    }

    This example includes all level A rules except for valid-lang, and it will also include the level AA color-contrast rule.

  5. Run only some tags, but exclude others

    The runOnly option can accept an object with an include and exclude property. Only those checks that match an included tag will run, except those that share a tag from the exclude list.

    {
      runOnly: {
        type: 'tags',
        value: {
          include: ['wcag2a', 'wcag2aa'],
          exclude: ['experimental']
        }
      }
    }

    This example first includes all wcag2a and wcag2aa rules. All rules tagged as experimental are then removed from the rules to run.

callback Parameter

The callback parameter is a function that will be called when the asynchronous AxeDevTools.run function completes. The callback function is passed two parameters. The first parameter will be an error thrown inside of Axe DevTools if AxeDevTools.run cannot complete. If axe DevTools completed correctly, the first parameter will be null, and the second parameter will be the results object.

Return Promise

If the callback was not defined, axe DevTools will return a promise instead. However, axe DevTools does not polyfill the promise library. So, on systems without support for promises, this feature is not available. If you are unsure if the systems you will need axe DevTools on have promise support, we suggest you use the callback provided by AxeDevTools.run instead.

error Result

This will either be null or an object that is an instance of Error. If you consistently receive errors, please report this issue to Deque Systems.

results Object

The callback function passed in as the third parameter of AxeDevTools.a11yCheck runs on the results object. This object has two components: a passes array and a violations array. The passes array keeps track of all the passed tests and detailed information on each test. This leads to more efficient testing, especially with manual testing, as the user can easily determine the tests already passed. Similarly, the violations array keeps track of all the failed tests and detailed information on each one.

url

The URL of the page that was tested.

timestamp

The date and time that the analysis was completed.

passes and violations array
  • description - A text string that describes what the rule does
  • help - Help text that describes the test that was performed
  • helpUrl - A URL that provides more information about the specifics of the violation. Links to a page on the Deque University site.
  • id - A unique identifier for the rule; see the list of rules
  • impact - The seriousness of the violation. Can be one of minor, moderate, serious, or critical if the rule failed or null if the check passed.
  • tags - An array of tags assigned to this rule. The tags can be used in the option object to select which rules are run (see Options Parameter above).
  • nodes - An array of all elements the rule tested
    • html - A snippet of HTML of the element
    • impact - The seriousness of the violation. Can be one of minor, moderate, serious, or critical if the test failed or null if the check passed.
    • target - An array of selectors where each element corresponds to one level of iframe or frame. If there is one iframe or frame, there should be two entries in target. If there are three iframe levels, there should be four entries in target.
    • any - An array of checks where at least one must have passed. Each entry in the array contains:
      • id - Unique identifier for this check. Check ids may be the same as rule ids.
      • impact - The seriousness of the check. Can be one of minor, moderate, serious, or critical. Each check that is part of a rule can have different impacts. The highest impact of all the checks that fail is reported for the rule.
      • message - The description of why this check passed or failed.
      • data - Additional, optional information specific to the type of check. For example, a color contrast check would include the foreground color, background color, contrast ratio, etc.
      • relatedNodes - An optional array of information about other nodes related to this check. For example, a duplicate ID check violation would list the other selectors with the same duplicate ID. Each entry in the array contains the following information:
        • target - An array of selectors for the related node
        • html - The HTML source of the related node
    • all - An array of checks made where all must have passed. Each entry in the array contains the same information as the any array.
    • none - An array of checks made where all must have not passed. Each entry in the array contains the same information as the any array.

Example Two

In this example, we will pass the selector for the entire document, pass no options, which means all enabled rules will be run, and have a simple callback function that logs the entire results object to the console log:

AxeDevTools.run(document, function (err, results) {
  if (err) throw err;
  console.log(results);
});
passes array
  • passes[0] ...

    • help - "Elements must have sufficient color contrast"
    • helpURL - "https://dequeuniversity.com/courses/html-css/visual-layout/color-contrast"
    • id - "color-contrast"
      • nodes
      • target[0] - "#js_off-canvas-wrap > .inner-wrap >.kinja-title.proxima.js_kinja-title-desktop"
  • passes[1] ...

In the example above, the passes array contains two entries corresponding to the two rules tested. The first element in the array describes a color contrast check. The help, helpUrl, and id fields are returned for each entry in the passes array. The target array has one element in it with a value of:

#js_off-canvas-wrap > .inner-wrap >.kinja-title.proxima.js_kinja-title-desktop

The element selected by target[0] was checked for the color contrast rule and passed.

Each subsequent entry in the passes array has the same format but will detail the different rules that were run.

violations array
  • violations[0]

    • help - "<button> elements must have alternate text"
    • helpURL - "https://dequeuniversity.com/courses/html-css/forms/form-labels#id84_example_button"
    • id - "button-name"
      • nodes
      • target[0]
      • "post_5919997 > .row.content-wrapper > .column > span > iframe" * target[1]
      • "#u_0_1 > .pluginConnectButton > .pluginButtonImage > button"
  • violations[1] ...

The violations array contains one entry for a test that checks if buttons have valid alternate text (the button-name rule). This first entry in the array has the help, helpUrl, and id fields.

The target array demonstrates how we specify the selectors when the node specified is inside an iframe or frame. The first element in the target array (target[0]) specifies the selector to the iframe containing the button. The second element in the target array (target[1]) specifies the selector to the actual button but starts from inside the iframe selected in target[0].

Each subsequent entry in the violations array has the same format but will detail the rules that generated accessibility violations.

Example Three

In this example, we pass the selector for the entire document, enable two additional best practice rules, and have a simple callback function that logs the entire results object to the console log:

AxeDevTools.run(
  document,
  {
    rules: {
      'heading-order': { enabled: true },
      'label-title-only': { enabled: true }
    }
  },
  function (err, results) {
    if (err) throw err;
    console.log(results);
  }
);