Skip to content

Commit 00eca5f

Browse files
committed
Fix XSS vulnerability using safe DOM methods
1 parent 4c94c76 commit 00eca5f

2 files changed

Lines changed: 23 additions & 13 deletions

File tree

File renamed without changes.

fetch/programmer-humour/script.js

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
function fetchComic() {
22
const container = document.getElementById("comic-container");
3-
const loading = document.getElementById("loading");
43

54
fetch("https://xkcd.now.sh/?comic=latest")
65
.then(response => {
@@ -12,22 +11,33 @@ function fetchComic() {
1211
.then(data => {
1312
console.log(data);
1413

15-
if (loading) loading.remove();
14+
// CLEAR OLD CONTENT
15+
container.innerHTML = "";
1616

17-
container.innerHTML = `
18-
<h2>${data.title}</h2>
19-
<img src="${data.img}" alt="${data.alt}" />
20-
<p>${data.alt}</p>
21-
`;
17+
// SAFE ELEMENT CREATION (FIXES XSS)
18+
const title = document.createElement("h2");
19+
title.textContent = data.title;
20+
21+
const img = document.createElement("img");
22+
img.src = data.img;
23+
img.alt = data.alt;
24+
25+
const desc = document.createElement("p");
26+
desc.textContent = data.alt;
27+
28+
container.appendChild(title);
29+
container.appendChild(img);
30+
container.appendChild(desc);
2231
})
2332
.catch(error => {
24-
console.error(error);
33+
container.innerHTML = "";
34+
35+
const errorMsg = document.createElement("p");
36+
errorMsg.textContent = "Error loading comic 😢";
2537

26-
if (loading) {
27-
loading.textContent = "Error loading comic 😢";
28-
} else {
29-
container.innerHTML = `<p>Error loading comic 😢</p>`;
30-
}
38+
container.appendChild(errorMsg);
39+
40+
console.error(error);
3141
});
3242
}
3343

0 commit comments

Comments
 (0)