-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
54 lines (49 loc) · 1.32 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
export default (fallbackToNone: Boolean = true) => {
const testId = `test_${Math.random()
.toString(36)
.substring(2)}`;
const css: HTMLStyleElement = document.createElement("style");
const testElement: HTMLDivElement = document.createElement("div");
testElement.innerHTML = "Test element";
testElement.setAttribute("id", testId);
css.innerHTML = /* css */ `
html {
content: "";
}
@media (prefers-contrast: high) {
html {
content: "high";
}
}
@media (prefers-contrast: low) {
html {
content: "low";
}
}
@media (prefers-contrast: no-preference) {
html {
content: "no-preference";
}
}
`;
// Append CSS and test element
if (document.head || document.documentElement) {
(document.head || document.documentElement).appendChild(css);
}
if (document.body) {
document.body.appendChild(testElement);
}
// Fetch computed value
const value =
getComputedStyle(document.documentElement)
.getPropertyValue("content")
.replace(/"/g, "") || (fallbackToNone ? "no-preference" : "unknown");
// Remove appended items from the DOM
if (testElement.parentNode) {
testElement.parentNode.removeChild(testElement);
}
if (css.parentNode) {
css.parentNode.removeChild(css);
}
return value;
};