在 Chrome 浏览器中检测高对比度扩展程序的使用

Detect High Contrast extension use in Chrome browser

我正在尝试让我的网站在高对比度模式下易于访问。为了检测何时启用高对比度模式,我创建了一个 JavaScript 方法来检测背景图像是否被禁用,因为高对比度模式会禁用背景图像。然后,如果浏览器处于高对比度模式,我会附加一个 CSS 文件来修复高对比度显示。这在 Firefox、Edge 和 IE 中工作正常,但 Chrome 使用其自己的扩展来创建高对比度,并且它不会禁用背景图像,因此在 Chrome 中 CSS不附加高对比度。

通过搜索我发现 Chrome 在网站上添加了一个过滤器,而不是 enabling/disabling/changing 网站颜色或图像本身。我找了又找,但找不到任何东西来测试 Chrome 是否正在使用高对比度模式。如果有一种方法可以检测正在使用哪些扩展程序,那也可以解决问题,但我也找不到方法来做到这一点。

我的代码实际上工作正常,我只需要能够检测 Chrome 中的高对比度模式。这是我用来检查高对比度模式的方法。

let highContrast = (options) => {

  let hcDetect = jQuery(`<div id="jQHighContrastDetect"></div>`).css('background', 'url(../uploads/c-wht-small.png)');
  hcDetect.appendTo(document.body);

  if (hcDetect.css('background-image') === 'none') {
    $('head').append('<link rel="stylesheet" href="../css/highcontrast.min.css" type="text/css" media="all">');

  }
}

Chrome 扩展程序将注入一些代码以生成高对比度 LAF。

注入可能需要 setTimeout。就我而言,这是必需的。

这对我有用:

setTimeout(function(){
   var htmlTag = document.getElementsByTagName('html');
   console.log(htmlTag[0].getAttribute('hc') != null);
}, 150);

如果您询问 Windows 高对比度模式,Chrome 不知道什么时候激活。

一般来说,如果 Windows 用户选择启用高对比度模式,则该用户正在 Microsoft Internet Explorer 或 Microsoft Edge 中浏览(因为这些浏览器支持)。它们都支持专有的 -ms-high-contrast @media 规则。

检查丢失的背景图像是一种适用于 IE/Edge 的策略,但使用媒体查询是更好的方法。尤其是 Windows High Contrast Mode will soon allow background images in Edge.

如果您希望检测特定扩展程序何时在 Chrome 中设置了自己的高对比度模式,了解哪个扩展程序会很有帮助。

例如,使用 High Contrast 扩展名,您可以在 <html> 标签上查找以下属性:hc="a3"hcx="3"(对于你,但属性应该匹配)。如果你打开浏览器开发工具,你可以看到它做的一些其他事情。但这些属性处于 DOM 的最高级别,使用起来可能是最安全的。

如果您询问 Chrome 与 Android 的关系,那也是一个不同的过程。

...all I need is to be able to detect the high-contrast mode in Chrome


解决方案 #1:

在我的 React/TypeScript 项目中,我使用了类似于 的代码,但我发现我的组件不需要超时,因为它需要几秒钟才能加载。事实上,我创建了一个演示 React 项目,在第一个加载组件中测试了扩展,没有延迟是必要的。

const htmlTag: HTMLElement = document.getElementsByTagName(
    'html'
  )[0];
const isUsingChromeHighContrastExtension: boolean =
    htmlTag.getAttribute('hc') !== null;

解决方案 #2:

使您的非高对比度代码易于访问,并且您不必首先检测 Chrome 的高对比度扩展。

来自WCAG Criterion 1.4.11: Non-text Contrast

Success Criterion 1.4.11 Non-text Contrast (Level AA): The visual presentation of the following have a contrast ratio of at least 3:1 against adjacent color(s):

User Interface Components

Visual information used to indicate states and boundaries of user interface components, except for inactive components or where the appearance of the component is determined by the user agent and not modified by the author;

Graphical Objects

Parts of graphics required to understand the content, except when a particular presentation of graphics is essential to the information being conveyed.