0

I've been trying to make custom console commands with JavaScript with no success. There seem to be no sources about my question.

When I say "JavaScript Console Commands" I mean I'd like to make my own commands from the console. For example, if the visitor types "custom.command()" in my website's console area, I want the output to be: console.log("This is my custom command");.

2
  • 1
    Write a function. Commented Mar 19, 2022 at 12:08
  • @tkausl, Thank's for reaching out! Can you be a little more spesific? What is the function? Commented Mar 19, 2022 at 12:10

1 Answer 1

1

You don't have to do anything special; just create an object at global scope with functions on it, and the user will be able to use it from the devtools console.

For instance (in a script, not a module):

const custom = {
    command() {
        console.log("This is my custom command.");
    },
};

Using it:

custom.command();

Because that's at global scope, it creates a global, and so it is accessible in the console when your page is open.

(It doesn't have to be an object; you could just create a function at global scope, but your example usage was using an object.)


If you wanted to do this from a module, since the top level of a module isn't global scope, you'd have to do the same kind of thing you have to do to create a global in a function, which is covered by the answers to this question. In your case, it's: assign to a property on window: window.custom = { /*...*/ }; Or in modern browsers, use can use globalThis (which refers to the same object): globalThis.custom = { /*...*/ }; (unlike window, globalThis is available in non-browser environments).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.