aria-live Announces Status Updates

A visually hidden aria-live region announces async outcomes to screen readers; clear it before writing so repeated messages are spoken again.

JavascriptData Fetching

Code

javascriptsnippet
23 lines
const region = document.querySelector("#live-status");
const saveButton = document.querySelector("#save-draft");
const priority = document.querySelector("#priority");

function announce(message, politeness = "polite") {
  // 先清空再写入:完全相同的文本不会触发第二次播报
  region.textContent = "";
  region.setAttribute("aria-live", politeness);
  // rAF 间隔确保清空已被读屏器观察到
  requestAnimationFrame(() => {
    region.textContent = message;
  });
}

saveButton.addEventListener("click", () => {
  announce("draft saved");
});

priority.addEventListener("click", () => {
  // assertive 打断当前播报:用于超时、错误等紧急提示
  announce("sync failed, retrying", "assertive");
});

How it works

aria-live Announces Status Updates comes down to the function announce.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.
  • Uses document, requestAnimationFrame, so it needs a browser context — it will not run as-is in Node without shims.

Using it

Signature: function announce(message, politeness = "polite")

Key statements

saveButton.addEventListener("click", () => {
announce("draft saved");
});
priority.addEventListener("click", () => {
// assertive 打断当前播报:用于超时、错误等紧急提示
announce("sync failed, retrying", "assertive");
});
requestAnimationFrame(() => {
region.textContent = message;
});

Interactive Tools for This Topic

FAQ

Does aria-live Announces Status Updates run in plain Node.js?
No — it touches `document` and `requestAnimationFrame`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.