function init() { const loc = window.location.href; const isLocalFile = loc.startsWith("file://"); // Check if the document has a valid doctype let hasValidDoctype = checkDoctype(); if (!hasValidDoctype) { console.warn("Warning: This document does not have a declaration."); addWarningFooter(); } if (isLocalFile) { // Local file case: Include the DOCTYPE manually if necessary const pageContent = `\n` + document.documentElement.outerHTML; fetch("https://validator.w3.org/nu/?out=json", { method: "POST", headers: { "Content-Type": "text/html; charset=utf-8" }, body: pageContent }) .then(response => response.json()) .then(data => { renderValidationResults(data); }) .catch(error => { console.warn(error); renderErrorFooter(); }); } else { // Hosted file case: Use URL-based validation fetch("https://validator.w3.org/nu/?out=json&doc=" + encodeURIComponent(loc), { method: "GET" }) .then(response => response.json()) .then(data => { renderValidationResults(data); }) .catch(error => { console.warn(error); renderErrorFooter(); }); } } // Function to check if the document has a valid function checkDoctype() { if (document.doctype) { // Check if the name of the doctype is "html" (case-insensitive) return document.doctype.name.toLowerCase() === "html"; } return false; } // Helper function to add a warning to the footer if is missing function addWarningFooter() { let footer = document.querySelector('footer'); if (!footer) { footer = document.createElement('footer'); document.body.appendChild(footer); } footer.innerHTML += `

Warning: The document is missing a declaration. Validation results may not be accurate.

`; } // Helper function to render validation results function renderValidationResults(data) { console.log(data); let isHTMLValid = data.messages.length === 0; let ValidatorHTML = `

HTML/CSS`; if (!isHTMLValid) { ValidatorHTML += " NOT"; } ValidatorHTML += ` Valid!

`; ValidatorHTML += `

Validate HTML | Validate CSS

`; if(window.location.href.startsWith("file://") && !isHTMLValid) { ValidatorHTML += `

There might be multiple errors. Here is the first one:

Code Error Description
${data['messages'][0]['extract'].replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''')} ` + data['messages'][0]['message'] + `
` } let footer = document.querySelector('footer'); if (!footer) { footer = document.createElement('footer'); document.body.appendChild(footer); } footer.innerHTML += ValidatorHTML; } // Helper function to render an error message in the footer function renderErrorFooter() { let footer = document.querySelector('footer'); if (!footer) { footer = document.createElement('footer'); document.body.appendChild(footer); } footer.innerHTML += `

HTML/CSS validation could not be performed due to an error.

`; } // Call the init function when the DOM is fully loaded document.addEventListener('DOMContentLoaded', init); 3