Javascript

    Poor man's redirect in a static site

    I just moved my blog to Micro.blog. My domain name, rickardlindberg.me, now points to the new blog. I have not yet migrated all pages from my old blog. But it is still available at http://archive.rickardlindberg.me/.

    But what about existing links to my blog? They won’t work. I could configure the web server to redirect requests to the archived site for pages that I have not yet migrated or that have migrated to a new URL. However, as far as I can tell, there is no way on Micro.blog to easily configure many redirects. (You have to to it manually one by one, which is tedious for hundreds of URLs.)

    Then I came across Sven Dahlstrand’s blog, which is also hosted on Micro.blog. When I tried visiting a page that did not exist, I saw this:

    That got me thinking that I could provide a textual explanation that the page has not yet been migrated on my 404 error page. (You can customize the 404 error page on Micro.blog.)

    But, how is this possible? Micro.blog hosts static sites, and there is no way for a static site to render dynamic HTML depending on the URL.

    Then I did what I first did when I learned to program 20+ years ago: I hit “View Page Source”.

    I realized that the dynamic part was rendered with Javascript:

    <p>Sorry, <span id="this-page-text">this page</span> could not be found. Don&rsquo;t worry, you didn&rsquo;t break the internet. It&rsquo;s probably my fault. 😅</p>
    ...
    <script module>
    const thisPageText = document.querySelector('#this-page-text');
    thisPageText.innerText = `${thisPageText.innerText} (${window.location.pathname})`;
    </script>
    

    I was confused by <script module> and the backtick syntax. Most likely Javascript has changed a bit since I last worked with it.

    I put together something similar, with more familiar Javascript, for my 404 error page:

    This page has probably not been imported to my new blog yet.
    
    <p>In the meantime, you can find it here: <a id="here-link"
    href="http://archive.rickardlindberg.me">http://archive.rickardlindberg.me</a>.</p>
    
    <script type="text/javascript">
    var hereLink = document.getElementById("here-link");
    var path = window.location.pathname;
    var archiveUrl = "http://archive.rickardlindberg.me" + path;
    hereLink.href = archiveUrl;
    hereLink.innerHTML = archiveUrl;
    </script>
    

    (The <p> tag in the second paragraph seems to be needed. Otherwise the Micro.blog Markdown processing will turn the link in the “a-body” into another link tag so we end up with nested links which makes the Javascript not work.)

    Thank you @sod for showing me that this was possible, and for making me re-live the experience of first learning to program. I wish more environments had a “View Page Source” function.