Here is code to sort comments “oldest first” for new comments block 2024:
<script>
document.addEventListener("DOMContentLoaded", function () {
// Flag to avoid duplicate sorting
let isSortingScheduled = false;
// Store the original open method
const originalOpen = XMLHttpRequest.prototype.open;
// Override the open method to capture all AJAX requests
XMLHttpRequest.prototype.open = function(method, url) {
// Store the original send method for later use
const originalSend = this.send;
// Check if the request URL matches the patterns of interest
if (url.includes('/v2/comments')) {
// Add a custom property to the request to identify it later
this._intercepted = true;
// Override the send method to detect request completion
this.send = function(body) {
// Set up a handler for when the request completes
this.addEventListener('load', function() {
if (this._intercepted) {
// Only schedule sorting if not already scheduled
if (!isSortingScheduled) {
isSortingScheduled = true;
// Run sorting script after a 1-second delay
setTimeout(() => {
runSortingScript();
isSortingScheduled = false; // Reset the flag after sorting
}, 1000);
}
}
});
// Call the original send method
originalSend.call(this, body);
};
}
// Call the original open method
return originalOpen.apply(this, arguments);
};
// Define the sorting script
function runSortingScript() {
// Select the comments container
const commentsContainer = document.querySelector('.sw-js-comments-container');
if (commentsContainer) {
// Select all individual comments blocks
const commentBlocks = Array.from(commentsContainer.querySelectorAll('.MuiStack-root[data-resourceid]'));
// Ensure there are comments to sort
if (commentBlocks.length > 0) {
// Reverse the order of comment blocks
commentBlocks.reverse();
// Clear the container and append the reversed comments
commentsContainer.innerHTML = '';
commentBlocks.forEach(block => commentsContainer.appendChild(block));
}
}
}
});
</script>