Axe API documentation
Section 1: Introduction
The Axe 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 list of rules and elements that passed accessibility checking, ensuring rules have been run against entire document
- Only checks rendered content to minimize false positives (that includes visually-hidden content)
Getting Started
This section gives a quick description of how to use the axe APIs to analyze web page content and return a JSON object that lists any accessibility violations found.
The Axe API can be used as part of a broader process that is performed on many, if not all, pages of a website. The API is used to analyze web page content and return a JSON object that lists any accessibility violations found. Here is how to get started:
- Load page in testing system
- Optionally, set configuration options for the JavaScript API (
axe.configure) - Call analyze JavaScript API (
axe.run) - Either assert against results or save them for later processing
- Repeat for any inactive or non-rendered content after making it visible
Section 2: API reference
Overview
The Axe APIs are provided in the JavaScript file axe.js. It must be included in the web page under test, as well as each iframe under test. Parameters are sent as JavaScript function parameters. Results are returned in JSON format.
Full API Reference for Developers
For a full listing of API offered by axe, clone the repository and run npm run api-docs. This generates jsdoc documentation under doc/api which can be viewed using the browser.
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 is a link to a broader description of the accessibility issue and suggested remediation. These links point to Deque University help pages, which do not require a login. - Axe does not test hidden regions, such as inactive menus or modal windows. To test those for accessibility, write tests that activate or render the regions visible and run the analysis again.
Axe-core Tags
Each rule in axe-core has a number of tags. These provide metadata about the rule. Each rule has one tag that indicates which WCAG version / level it belongs to, or if it doesn’t, it has the best-practice tag. If the rule is required by WCAG, there is a tag that references the success criterion number. For example, the wcag111 tag means a rule is required for WCAG 2 success criterion 1.1.1.
The experimental, ACT, TT, and section508 tags are only added to some rules. Each rule with a section508 tag also has a tag to indicate what requirement in old Section 508 the rule is required by. For example section508.22.a.
Tag name
wcag2a
wcag2aa
wcag2aaa
wcag21a
wcag21aa
wcag22aa
best-practice
wcag2a-obsolete
wcag***
ACT
section508
section508.*.*
TTv5
TT*.*
EN-301-549
EN-9.*
RGAAv4
RGAA-*.*.*
experimental
cat.*
Accessibility standard / purpose
WCAG 2.0 Level A
WCAG 2.0 Level AA
WCAG 2.0 Level AAA
WCAG 2.1 Level A
WCAG 2.1 Level AA
WCAG 2.2 Level AA
Common accessibility best practices
WCAG 2.0 Level A, no longer required for conformance
WCAG success criterion e.g. wcag111 maps to SC 1.1.1
WCAG success criterion e.g. wcag111 maps to SC 1.1.1
Old Section 508 rules
Requirement in old Section 508
Trusted Tester v5 rules
Test ID in Trusted Tester
Rule required under EN 301 549
Section in EN 301 549 listing the requirement
Rule required under RGAA
Section in RGAA listing the requirement
Cutting-edge rules, disabled by default
Category mappings used by Deque (see below)
All rules have a cat.* tag, which indicates what type of content it is part of. The following cat.* tags exist in axe-core:
API Name: axe.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
axe.run(
{
resultTypes: ['violations', 'incomplete', 'inapplicable']
},
(err, results) => {
// ...
}
);
This example will return all the nodes for all rules that fall under the “violations”, “incomplete”, and “inapplicable” result types. Since the “passes” type was not specified, it will return at most one node for each rule that passes.
Preload Configuration in Options Parameter
The preload attribute (defaults to true) in options parameter, accepts a boolean or an object where an array of assets can be specified.
- Specifying a
booleanaxe.run({preload: true},(err, results) => {// ...}); - Specifying a
objectaxe.run({preload:{ assets: ['cssom'], timeout: 50000 }},(err, results) => {// ...});
The assets attribute expects an array of preload(able) constraints to be fetched. The current set of values supported for assets is listed in the following table:
Asset type
cssom
media
Description
This asset type preloads all CSS Stylesheets rulesets specified in the page. The stylesheets can be an external cross-domain resource, a relative stylesheet or an inline style with in the head tag of the document. If the stylesheet is an external cross-domain a network request is made. An object representing the CSS Rules from each stylesheet is made available to the checks evaluate function as preloadedAssets at run-time
This asset type preloads metadata information of any HTMLMediaElement in the specified document
The timeout attribute in the object configuration is optional and has a fallback default value (10000ms). The timeout is essential for any network dependent assets that are preloaded, where-in if a given request takes longer than the specified/ default value, the operation is aborted.
Preloading is not applicable to all rules. Even if the preload option is enabled, preloading steps may be skipped if no enabled rules require preloading.
Callback Parameter
The callback parameter is a function that will be called when the asynchronous axe.run function completes. The callback function is passed two parameters. The first parameter will be an error thrown inside of axe if axe.run could not complete. If axe 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 will return a Promise instead. Axe does not polyfill a Promise library however. So on systems without support for Promises this feature is not available. If you are unsure if the systems you will need axe on has Promise support we suggest you use the callback provided by axe.run instead.
Error Result
This will either be null or an object which is an instance of Error. If you are consistently receiving errors, please report this issue on the Github issues list of Axe.
Results Object
The callback function passed in as the third parameter of axe.run runs on the results object. This object has four components – a passes array, a violations array, an incomplete array and an inapplicable array.
The passes array keeps track of all the passed tests, along with detailed information on each one. This leads to more efficient testing, especially when used in conjunction with manual testing, as the user can easily find out what tests have already been passed.
Similarly, the violations array keeps track of all the failed tests, along with detailed information on each one.
The incomplete array (also referred to as the “review items”) indicates which nodes could neither be determined to definitively pass or definitively fail. They are separated out in order that a user interface can display these to the user for manual review (hence the term “review items”).
The inapplicable array lists all the rules for which no matching elements were found on the page.
url
The URL of the page that was tested.
timestamp
The date and time that analysis was completed.
testEngine
The application and version that ran the audit.
testEnvironment
Information about the current browser or node application that ran the audit.
Result arrays
The results of axe are grouped according to their outcome into the following arrays:
passes: These results indicate what elements passed the rulesviolations: These results indicate what elements failed the rulesinapplicable: These results indicate which rules did not run because no matching content was found on the page. For example, with no video, those rules won’t run.incomplete: Also known as “needs review,” these results were aborted and require further testing. This can happen either because of technical restrictions to what the rule can test, or because a JavaScript error occurred.
Each object returned in these arrays have the following properties:
description– Text string that describes what the rule doeshelp– Help text that describes the test that was performedhelpUrl– URL that provides more information about the specifics of the violation. Links to a page on the Deque University site.id– Unique identifier for the rule; see the list of rulesimpact– How serious the violation is. Can be one of “minor”, “moderate”, “serious”, or “critical” if the Rule failed ornullif the check passedtags– Array of tags that this rule is assigned. These tags can be used in the option structure to select which rules are run (seeaxe.runparameters for more information).nodes– Array of all elements the Rule testedhtml– Snippet of HTML of the Elementimpact– How serious the violation is. Can be one of “minor”, “moderate”, “serious”, or “critical” if the test failed ornullif the check passedtarget– Array of either strings or Arrays of strings. If the item in the array is a string, then it is a CSS selector. If there are multiple items in the array each item corresponds to one level of iframe or frame. If there is one iframe or frame, there should be two entries intarget. If there are three iframe levels, there should be four entries intarget. If the item in the Array is an Array of strings, then it points to an element in a shadow DOM and each item (except the n-1th) in this array is a selector to a DOM element with a shadow DOM. The last element in the array points to the final shadow DOM node.any– Array of checks that were made 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 idsimpact– How serious this particular check is. 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 rulemessage– Description of why this check passed or faileddata– Additional information that is specific to the type of Check which is optional. For example, a color contrast check would include the foreground color, background color, contrast ratio, etc.
relatedNodes– Optional array of information about other nodes that are related to this check. For example, a duplicate id check violation would list the other selectors that had this same duplicate id. Each entry in the array contains the following information:target– Array of selectors for the related nodehtml– HTML source of the related node
-
all– Array of checks that were made where all must have passed. Each entry in the array contains the same information as the ‘any’ arraynone– Array of checks that were made where all must have not passed. Each entry in the array contains the same information as the ‘any’ array
Example 2
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:
axe.run(document, function (err, results) {
if (err) throw err;
console.log(results);
});
passes
passes[0]…help–"Elements must have sufficient color contrast"helpUrl–"https://dequeuniversity.com/courses/html-css/visual-layout/color-contrast"id–"color-contrast"nodestarget[0]–"#js_off-canvas-wrap > .inner-wrap >.kinja-title.proxima.js_kinja-title-desktop"
passes[1]…
violations
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"nodestarget[0]–"post_5919997 > .row.content-wrapper > .column > span > iframe"target[1]–"#u_0_1 > .pluginConnectButton > .pluginButtonImage > button"
violations[1]…
passes Results Array
In the example above, the passes array contains two entries that correspond to the two rules tested. The first element in the array describes a color contrast check. It relays the information that a list of nodes was checked and subsequently passed. The help, helpUrl, and id fields are returned as expected for each of the entries 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
This indicates that the element selected by the entry in target[0] was checked for the color contrast rule and that it passed the test.
Each subsequent entry in the passes array has the same format, but will detail the different rules that were run as part of this call to axe.run().
violations Results Array
The array of violations contains one entry; this entry describes a test that check if buttons have valid alternate text (button-name). This first entry in the array has the help, helpUrl and id fields returned as expected.
The target array demonstrates how we specify the selectors when the node specified is inside of an iframe or frame. The first element in the target array – target[0] – specifies the selector to the iframe that contains the button. The second element in the target array – target[1] – specifies the selector to the actual button, but starting from inside the iframe selected in target[0].
Each subsequent entry in the violations array has the same format, but will detail the different rules that were run that generated accessibility violations as part of this call to axe.run().
Example 3
In this example, we pass the selector for the entire document, enable two additional experimental rules, and have a simple callback function that logs the entire results object to the console log:
axe.run(
document,
{
rules: {
'link-in-text-block': { enabled: true },
'p-as-heading': { enabled: true }
}
},
function (err, results) {
if (err) throw err;
console.log(results);
}
);
Example 4
This example shows a result object that points to an open shadow DOM element.
violations[0]
{
"help": "Elements must have sufficient color contrast",
"helpUrl": "https://dequeuniversity.com/rules/axe/2.1/color-contrast?application=axeAPI",
"id": "color-contrast",
"nodes": [
{
"target": [["header > aria-menu", "li.expanded"]]
}
]
}
As you can see the target array contains one item that is an array. This array contains two items, the first is a CSS selector string that finds the custom element <aria-menu> in the <header>. The second item in this array is the selector within that custom element’s shadow DOM to find the <li> element with a class of expanded.
API Name: axe.registerPlugin
Register a plugin with the axe plugin system. See implementing a plugin for more information on the plugin system.
API Name: axe.cleanup
Call each plugin’s cleanup function. See implementing a plugin.
The signature is:
axe.cleanup(resolve, reject);
resolve and reject are functions that will be invoked on success or failure respectively.
resolve takes no arguments and reject takes a single argument that must be a string or have a toString() method in its prototype.
API Name: axe.setup
Setup axe-cores internal VirtualNode tree and other required properties required to run functions in axe.commons.
The signature is:
axe.setup(DomNode);
DomNode – is an optional DOM node to use as the root of the VirtualNode tree. Default is document.documentElement.
API Name: axe.teardown
Cleanup the VirtualNode tree and internal caches. axe.run will call this function at the end of the run so there’s no need to call it yourself afterwards.
The signature is:
axe.teardown();
API Name: axe.frameMessenger
Set up an alternative communication channel between parent and child frames. By default, axe-core uses window.postMessage(). See frame-messenger.md for details.
API name: axe.runPartial / axe.finishRun
Run axe without frame communication. This is the recommended way to run axe in browser drivers such as Selenium and Puppeteer. See run-partial.md for details.
Virtual DOM Utilities
Note: If you’re writing rules or checks, you’ll have both the node and virtualNode passed in. But if you need to query the flattened tree, the documented function below should help. See the developer guide for more information.
API Name: axe.utils.querySelectorAll
Description
A querySelectorAll implementation that works on the virtual DOM and open Shadow DOM by manually walking the flattened tree instead of relying on DOM API methods which don’t step into Shadow DOM.
Note: while there is no axe.utils.querySelector method, you can reproduce that behavior by accessing the first item returned in the array.
Synopsis
axe.utils.querySelectorAll(virtualNode, 'a[href]');
Parameters
virtualNode– object, the flattened DOM tree to query against.axe._treeis available for this purpose during an audit; see below.selector– string, the CSS selector to use as a filter. For the most part, this should work seamlessly withdocument.querySelectorAll.
Returns
An Array of filtered HTML nodes.
API Name: axe.utils.getRule
Description
Get an axe-core Rule instance by ID.
Synopsis
Parameters
ruleId– The ID of the rule.
Returns
An axe-core Rule instance.
Common Functions
axe.commons.dom.getComposedParent
Get an element’s parent in the flattened tree
Synopsis
axe.commons.dom.getComposedParent(node);
Parameters
element– HTMLElement. The element for which you want to find a parent
Returns
A DOMNode for the parent
axe.commons.dom.getRootNode
Return the document or document fragment (open shadow DOM)
Synopsis
axe.commons.dom.getRootNode(node);
Parameters
element– HTMLElement. The element for which you want to find the root node
Returns
The top-level document or shadow DOM document fragment
Section 3: Example reference
This package contains examples for jasmine, mocha, qunit, and generating HTML from the violations array. Each of these examples is in the doc/examples folder. In each folder, there is a README.md file which contains specific information about each example.
See axe-webdriverjs for selenium webdriver JavaScript examples.
Section 4: Performance
Axe-core performs very well in general and if you are analyzing average complexity pages with the default settings, you should not need to worry about performance at all. There are some scenarios that can cause performance issues. This is the list of known issues and what you can do to mitigate and/or avoid them.
Very large pages
Certain rules (like the color-contrast rule) look at almost every element on a page and some of these rules also perform somewhat expensive operations on these elements including looking up the hierarchy, looking at overlapping elements, calculating the computed styles etc. It also calculates a unique selector for each element in the results and also de-duplicates elements so that you do not get duplicate items in your results.
If your page is very large (in terms of the number of Elements on the page) i.e. >50K elements on the page, then you will see analysis times that run over 10s on a relatively decent CPU.
Use resultTypes
An approach you can take to reducing the time is use the resultTypes option. By calling axe.run with the following options, axe-core will only return the full details of the violations array and will only return one instance of each of the inapplicable, incomplete and pass arrays for each rule that has at least one of those entries. This will reduce the amount of computation that axe-core does for the unique selectors.
axe.run(
{
resultTypes: ['violations']
},
(err, results) => {
// ...
}
);
Other strategies
Targeted color-contrast analysis
If you are analyzing multiple pages on a single Web site or application, chances are these pages all contain the same styles. It is therefore not adding any additional information to your analysis to analyze every page for color-contrast. Choose a small number of pages that represent the totality of you styles and analyze these with color-contrast and analyze all others without it.