Skip to content

Instantly share code, notes, and snippets.

@riegl-aw
Last active March 4, 2023 03:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riegl-aw/6b258499887fc3e302f0b5dbcfa7b3d9 to your computer and use it in GitHub Desktop.
Save riegl-aw/6b258499887fc3e302f0b5dbcfa7b3d9 to your computer and use it in GitHub Desktop.
Docson Offline Usage Tutorial

Docson Offline Usage Tutorial

This tutorial is about offline usage of the Docson JSON schema renderer.

Problem

The attempt to use Docson offline (i.e. not served by a web server) will result in a "Cross-Origin Request Blocked" error message when Docson loads the schema file:

Cross-Origin Request Blocked

This is fine because it fails for security reasons, but it's bad because it prevents you from including Docson in a documentation package that is supposed to be offline consumable.

Solution

If a little pre-processing of the schema file(s) is possible and acceptable, there is a simple solution: embed the schema and other required files into a HTML file by using the data URI scheme.

To do so, make a copy of public/index.html and extend the <head> section with the following script:

<script>
    var XMLHttpRequestOpen = window.XMLHttpRequest.prototype.open;
    window.XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
        if (url == "templates/box.html") {
            url = "data:text/html;base64,{{BOX_HTML}}";
        }
        else if (url == "templates/signature.html") {
            url = "data:text/html;base64,{{SIGNATURE_HTML}}";
        }
        else if (url == "schema.json") {
            url = "data:application/json;base64,{{SCHEMA_JSON}}";
        }
        return XMLHttpRequestOpen.apply(this, arguments);
    }
</script>

This script modifies the URL of certain requests so that embedded data is used instead of loading it from a file. But the script is not yet ready for use - you have to replace {{BOX_HTML}}, {{SIGNATURE_HTML}} and {{SCHEMA_JSON}} with the Base64 encoded contents of the corresponding files (the first two are located in public/templates, the last one is your schema file).

For the Base64 encoding you can use a GNU/Linux command line program:

base64 --wrap=0 schema.json

or a simple Python script:

import base64
print(base64.b64encode(open("schema.json", mode="rb").read()))

And that's all - you can now open the modified HTML file in your browser without the need for a web server:

Working Schema Rendering

Maybe there are other solutions, but this one was the easiest for me. A simple Python script with e.g. a Mako template to generate the HTML page can be easily integrated into any automated build process.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment