cft

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

Know another way to make console logs wait until after a page reloads?


user

Ty Mick

3 years ago | 2 min read

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? Let me know in the comments below—I’d love to hear about it!

Originally published here.

Upvote


user
Created by

Ty Mick

Software developer, former RV nomad.


people
Post

Upvote

Downvote

Comment

Bookmark

Share


Related Articles