So I'm relatively new to JavaScript, although I've been doing HTML/CSS UI frontend work forever (blasphemy, I know) and am in the process of developing my own boilerplates for use with future projects. I'm also fairly new to the idea of securing code from XSS, CodeInjection etc.
The following is a fully working excerpt that I've been working on. In production, the JavaScript will be minified and loaded from an external file, not loaded inline, it's just for the example for ease of use.
I'm wondering if by creating variable output as plain text and inserting it via document.getElementById("x").href, leaves an opening to vulnerabilities such as CSS attacks. There is a ton of information regarding these types of vulnerabilities, but as a relative newcomer to the secure code environment, it's daunting and a bit overwhelming.
PS, the <p></p>
is also just for testing.
Thanks to all in advance!
For the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Title</title>
<!-- required CSS -->
<!-- conditional CSS -->
<link rel="stylesheet" type="text/css" href="assets/css/mq/null" id="mediaquery" />
</head>
<body>
<p id="test"></p>
<script type="text/javascript">
(function setCSS() {
if (window.matchMedia("screen and (max-width: 767px)").matches) {
layout = "mobile";
} else if (window.matchMedia("screen and (min-width: 768px) and (max-width: 1024px)").matches) {
layout = "tablet";
} else if (window.matchMedia("screen and (min-width: 1025px) and (max-width: 1280px)").matches) {
layout = "desktop";
} else if (window.matchMedia("screen and (min-width: 1281px)").matches) {
layout = "xldesktop";
}
window.addEventListener('resize', setCSS, false);
document.getElementById("test").innerHTML = layout;
document.getElementById("mediaquery").href = 'assets/css/mq/device.'+layout+'.css';
})();
</script>
</body>
</html>