Is there a better way to attach methods to the browser's console object?

javascript

#1

Hi all, I’m working on a side project: a library that adds visual and fun methods to the browser’s console object. Right now I’m attaching the methods directly to the console object, like so:

console.newMethod = () => { 
   // code
};

I feel unsure about doing it like this, but can’t fully articulate why. I know it could potentially overwrite existing console methods, but I feel like that’s easy enough to avoid. What are other potential issues with doing it this way? Is there a better or more preferred way to attach methods to the console object?

The code is available on GitHub if you’d like a look: https://github.com/sajoy/console-dot-lol
It’s also open source, so if you’re interested in contributing, let me know!


#2

I’m not sure for better, but here’s a thought. console is really window.console. One thing you could consider doing is to build a wrapper around the original console and replace console on window with your wrapper, maybe keeping the original console on a console_ or similar property on `window.

Another thought is that, since JavaScript can run outside the browser in Node.js and you might want to build your library to be cross-platform, you could build your thing to take in the object your modifying, be it window or console or whatever, as an argument rather than assuming the thing you’re looking for will be in the global namespace.

As for setting properties, you might consider setting them on the prototype instead of the instance. e.g.

console.__proto__.__defineGetter__('newMethod', () => {
  // code
});

This may not be particularly important for your use case since I’m not sure there’s a way to construct a new Console object in web browser based JS. But it would mean that any newly constructed Console would also have the methods you defined on it.


#3

Thanks so much for your thoughts!

Another thought is that, since JavaScript can run outside the browser in Node.js and you might want to build your library to be cross-platform,

I’ve given this a tiny bit of thought, so thanks for bringing it up! I think for now I want to keep it just in the browser - mainly because I have 0 clue how you style text in a terminal/Node environment (I don’t think it would be with CSS like it is in the browser) and I think there are existing libraries that are focused on being used in the terminal/Node.

As for setting properties, you might consider setting them on the prototype instead of the instance. … This may not be particularly important for your use case since I’m not sure there’s a way to construct a new Console object in web browser based JS.

Yeah, I also am not sure if there’s a way to create a new Console instance - it doesn’t seem like it. But this is useful to think about for sure! I’m now wondering how important it is that I attach these methods to the console, or would a completely different object be worth creating.