How to get content from another website using JavaScript

Ciprian on Friday, May 27, 2022 in AJAX and Fetching Data

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

Here’s the scenario:

One of my websites is static, and I need to maintain a changelog both on the website and on GitHub Pages. The solution is a simple JavaScript function to parse the Markdown content and display it on my website.

The content on GitHub Pages is rendered as HTML (from Markdown), so for my changelog I have headings – ⁣h2⁣ – and lists – ⁣ul/li. Also, I need to get the <body> content only.

So I’ll use the DOMParser() class, like below.

Note that I am checking for a specific element – ⁣.changelog⁣ – on my static website, so I can replace it with the retrieved changelog.

document.addEventListener('DOMContentLoaded', () => {
    if (document.querySelector('.changelog')) {
        function file_get_contents(filename) {
            fetch(filename).then((resp) => resp.text()).then(data => {
                // Optional, replace the H1 heading with nothing,
                // as I do not need it on my static website
                data = data.replace(/<h1>(.*?)<\/h1>/ig, "");

                // Initialize the document parser
                const parser = new DOMParser();
                let doc = parser.parseFromString(data, 'text/html');

                // Get the <body> element content
                let body = doc.querySelector('body').innerHTML;

                // Replace my empty element with the retrieved content
                document.querySelector('.changelog').innerHTML = body;
            });
        }

        // Call the function and point it to my GitHub Pages page
        file_get_contents('https://mypage.github.io/path/to/changelog');
    }
});

The function above is commented and self-explanatory. I did not encounter any restriction or CORS issue.

I assume that the github.io domain has no restrictions, due to the way it’s built, and this makes it ideal for these kinds of tasks.

I also assume that one could create a crude, basic CMS based on github.io and a static website. I wouldn’t recommend it, though.

Related posts

Leave a Reply

You have to agree to the comment policy.