Before you go, check out these stories!

Hackernoon logoMaking A Browser Console Log Wait Until Page Reloads [A How-To Guide] by@tywmick

Making A Browser Console Log Wait Until Page Reloads [A How-To Guide]

Author profile picture

@tywmickTy Mick

Data scientist, former RV nomad.

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 

, 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 

 to the line after 
 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 

 statement stood before, I instead saved the text content of the warning to the window’s 
 in a key called 

  "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 

 key. If the key exists, it logs the contents of the warning to the console and then removes the item from 

if (sessionStorage && sessionStorage.getItem("consoleWarnAfterReload")) {

That did the trick!

Know another way to make console logs wait until after a page reloads? Let me know in the comments below—I’d love to hear about it!


The Noonification banner

Subscribe to get your daily round-up of top tech stories!