Search code examples
javascriptw3cw3c-validationadobe-brackets

W3C Validator offline on localhost by ajax


I use to programming Brackets text editor and I have already installed W3C validator but it working while I'm online but offine not. I try install https://validator.w3.org/docs/install.html and I running to localhost:8888 but brackets's extension connecting only via ajax (javascript). Is possible send ajax like to original W3C website?


Solution

  • Maintainer of the W3C HTML checker (validator) here. Yes it is possible to send an ajax request to a local instance of the current checker. To use Fetch to do it and get JSON-formatted results back:

    var checkerUrl = "http://localhost:8888/?out=json"
    fetch(document.location.href)
    .then(function(currentDoc) { return currentDoc.text(); })
    .then(function(htmlSource) {
        fetch(
            checkerUrl, {
            method: "POST",
            mode: "cors",
            body: htmlSource,
            headers: new Headers({ "Content-Type": "text/html;charset=utf-8" })
        })
        .then(function(checkerResponse) { return checkerResponse.json(); })
        .then(function(jsonOutput) {
            console.dir(jsonOutput.messages);
        })
    });
    

    That shows the basic steps to follow to deliver the request in the way the checker expects:

    • send a document to the checker as the body of a POST (in this example, the current doc)
    • tell the checker to format its results as JSON (out=json)
    • make text/html;charset=utf-8 the media type of the POST body you send to the checker

    The checker also supports multipart/form-data for giving it the HTML source to be checked, but giving it the source as a POST body instead is the preferred (and better) way for doing it.

    If instead of using fetch() you want to use JQuery $.ajax(…), here’s an example:

    var checkerUrl = "http://localhost:8888/?out=json"
    $.get(document.location.href,
    function(htmlSource)
    {
        $.ajax({
            url: checkerUrl,
            type: "POST",
            crossDomain: true,
            data: htmlSource,
            contentType: "text/html;charset=utf-8",
            dataType: "json",
            success: function (jsonOutput) {
                console.dir(jsonOutput.messages);
            }
        });
    });
    

    And if instead of either fetch() or JQuery $.ajax(…) you want to use old-school XHR but it’s not clear how to handle the details in that case, let me know and I can post an example of that too.

    In all cases, the .messages JSON output is an array of objects that each contain something like:

    firstColumn: 1
    lastColumn: 6
    lastLine: 4
    message: "Unclosed element “span”."
    type: "error"
    

    The documentation for the checker JSON format gives more details of the JSON the checker emits.