In JavaScript I want to get the user's font-size which is actually set in the browser's appearance settings.
Is it possible to get it in script?
In JavaScript I want to get the user's font-size which is actually set in the browser's appearance settings.
Is it possible to get it in script?
I have tried to find a way to get the font-size which is set in appearance settings and, here is the function which should work on Chrome correctly.
const defaultSize = 16;
function getBrowserFontSize() {
try {
const element = document.createElement("button");
element.style.display = "none";
element.style.fontSize = "initial";
document.body.append(element);
const fontSizeMatch = window
.getComputedStyle(element)
.getPropertyValue("font-size")
.match(/^(\d*\.?\d*)px$/);
element.remove();
if (!fontSizeMatch || fontSizeMatch.length < 1) {
return defaultSize;
}
const result = Number(fontSizeMatch[1]);
return !isNaN(result) ? result : defaultSize;
} catch (e) {
console.error(e);
return defaultSize;
}
}
console.log(getBrowserFontSize());