问题
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.
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/54148686/run-dom-based-javascript-from-command-line