Created
February 25, 2024 03:23
-
-
Save carcigenicate/c0713dfa5d3ff87a792346f5b48358ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ==UserScript== | |
// @name Reply Saver | |
// @namespace http://tampermonkey.net/ | |
// @version 0.1 | |
// @description Saves unposted top-level replies to localStorage, and restores them on nav back to the page. | |
// @author carcigenicate | |
// @match https://old.reddit.com/r/*/comments/* | |
// @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== | |
// @grant none | |
// ==/UserScript== | |
(function() { | |
'use strict'; | |
console.time('Reply Saver Userscript'); | |
const CACHE_TIME_HOURS = 72; | |
const PARENT_KEY = 'COMMENT_SAVER_CACHE'; | |
function isExpired(timestamp) { | |
const saveDate = new Date(timestamp); | |
const now = new Date(); | |
return (now - saveDate) >= (CACHE_TIME_HOURS * 3600000); | |
} | |
function handleExpiredEntries() { | |
const rawEntries = localStorage.getItem(PARENT_KEY); | |
const parsed = JSON.parse(rawEntries) ?? {}; | |
for (const [key, {timestamp}] of Object.entries(parsed)) { | |
if (isExpired(timestamp)) { | |
delete parsed[key]; | |
} | |
} | |
localStorage.setItem(PARENT_KEY, JSON.stringify(parsed)); | |
} | |
if (localStorage.getItem(PARENT_KEY) === null) { | |
localStorage.setItem(PARENT_KEY, "{}"); | |
} | |
handleExpiredEntries(); | |
const commentBox = document.querySelector('.usertext-edit textarea'); | |
const pathPieces = document.location.href.split('/'); | |
const commentIndex = pathPieces.indexOf('comments'); | |
const subreddit = pathPieces[commentIndex - 1]; | |
const postId = pathPieces[commentIndex + 1]; | |
const cacheKey = `${subreddit}:${postId}`; | |
const rawCache = localStorage.getItem(PARENT_KEY); | |
const cache = JSON.parse(rawCache); | |
const existingEntry = cache[cacheKey]; | |
let populatedComment = ''; | |
if (existingEntry) { | |
commentBox.value = existingEntry.comment; | |
populatedComment = existingEntry.comment; | |
} | |
addEventListener('beforeunload', () => { | |
const currentComment = commentBox.value; | |
if (currentComment || populatedComment) { | |
// Refetching to avoid multiple tabs having their own "cached cache" in memory causing write issue. | |
const unloadRawCache = localStorage.getItem(PARENT_KEY); | |
const unloadCache = JSON.parse(unloadRawCache); | |
unloadCache[cacheKey] = { comment: currentComment, timestamp: new Date() }; | |
localStorage.setItem(PARENT_KEY, JSON.stringify(unloadCache)); | |
} | |
}); | |
console.timeEnd('Reply Saver Userscript'); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment