1

I have some Javascript that is interacting with the DOM from a website.

document.location.href="https://www.example.com";

It works well from Chrome console, but I would like to run that code from the command line. How can I do it? NodeJS gives "document is not defined" error.

2
  • 3
    What would you like to happen when you run this code? Commented Jan 11, 2019 at 14:42
  • What would document be in Node? And what DOM would you have when running a script in a command line environment? Commented Jan 11, 2019 at 14:45

3 Answers 3

3

What you are looking for is called jsdom! https://github.com/jsdom/jsdom

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

Comments

2

In order to use command line to inject Javascript code in a browser's DOM you actually need...a browser that runs Javascript code ad has a DOM.

You can go with something like Selenium or rely on a bridged library like https://github.com/prasmussen/chrome-cli

Comments

1

When you run the code from browser the DOM api is included, so your code excutes accordingly and finds the the location object with information about the current document your on. When you try to run it from command line using node.js the DOM api is not included which is why it gives you "document is not defined" error. Node.js is for excuting server side js code.

Comments

Your Answer

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