Userscript to always show LW comments in context vs at the top

The out of context top-level display of comments when I navigate to them always bothered me, but up until recently I haven’t realized there is a way to go to the actual comment via a simple URL change.

From https://​​www.lesswrong.com/​​posts/​​<postid>/​?commentId=<commentid>
To https://​​www.lesswrong.com/​​posts/​​<postid>#<commentid>

Here is a quick gpt4 generated userscript that does this.

// ==UserScript==
// @name         Always show in-context comments
// @namespace    http://​​tampermonkey.net/​​
//​ @version      0.1
//​ @description  Redirect from ‘?commentId=’ format to ‘#’
//​ @author       Vlad Sitalo
//​ @match        https://​​www.lesswrong.com/​​*
//​ @grant        none
//​ ==/​UserScript==


(function() {
    ‘use strict’;

    var checkAndRedirect = function() {
        var url = window.location.href;
        if(url.includes(”?commentId=”)){
            var newUrl = url.split(”?commentId=”).join(“#”);
            window.location.href = newUrl;
        }
    };

    //​ Run on page load
    checkAndRedirect();

    //​ Run on URL change
    var pushState = history.pushState;
    history.pushState = function() {
        pushState.apply(history, arguments);
        checkAndRedirect();
    };

    var replaceState = history.replaceState;
    history.replaceState = function() {
        replaceState.apply(history, arguments);
        checkAndRedirect();
    };

    window.addEventListener(‘popstate’, checkAndRedirect);
})();