How to make a browser console log wait until after a page reload
Ever wanted to create a browser console log that persists after a page reloads? Sure, that isn’t a problem if you enable the “preserve log” option in your developer console, but hear me out.
Say you have a JavaScript framework with a development server that usually
hot-reloads when you update files while the server is running. In the few cases
where hot reloading isn’t possible and the page has to fully reload, you want to
warn your users and explain why this is happening. It’d be nice to just log a
warning to the console with console.warn()
, but the moment it shows up in the
console, wouldn’t you know, the page reloads, and the browser clears it. Even
if your user is eagle-eyed enough to notice your warning flash on the screen
for a fraction of a second, it certainly isn’t there long enough to actually
read.
You could say that if any of your users don’t know where the “preserve log” button is then that’s their problem, but you’re kinder than that. You’d rather help them fall into the Pit of Success.
As it happens, that’s the very issue I ran into the other day when strolling through my favorite open source project, Next.js.
In my naïveté, I first tried just moving the console.warn()
to the line
after window.location.reload()
and crossing my fingers, but that didn’t
help. I tried googling things like “console log after page reload”, but that
only gave me instructions for how to turn on “preserve log”, which I already
knew how to do.
Here’s what worked. Where the console.warn()
statement stood before, I instead
saved the text content of the warning to the window’s
sessionStorage
in a key called "consoleWarnAfterReload"
:
sessionStorage.setItem(
"consoleWarnAfterReload",
"Dear me, the page had to fully reload!"
);
Then, near the top of a file involved in the loading of a new page, I added a
few lines that check that same sessionStorage
key. If the key exists, it logs
the contents of the warning to the console and then removes the item from
sessionStorage
:
if (sessionStorage && sessionStorage.getItem("consoleWarnAfterReload")) {
console.warn(sessionStorage.getItem("consoleWarnAfterReload"));
sessionStorage.removeItem("consoleWarnAfterReload");
}
That did the trick!
Know another way to make console logs wait until after a page reloads? I’d love to hear about it on Twitter, Facebook, or LinkedIn.
Found an error or typo in this post you’d like to fix? Send me a pull request on GitHub!
Want to publish this article on your blog, in your magazine, or anywhere else? This post, like most of the content on my website, is licensed under a Creative Commons Attribution license, so you’re welcome to share it wherever and however you please, as long as you cite me as the author. I’d also enjoy hearing from you if you do publish this somewhere, but that’s totally up to you.