Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute JavaScript commands without a browser?

How can I run JavaScript headlessly?

I am looking for an option like Scratchpad (present in Firefox) that could run JavaScript and make DOM operations on specific websites without a browser and preferably executed from the command line.

like image 754
Clone Avatar asked Jun 17 '18 12:06

Clone


People also ask

How do I run a JavaScript file manually?

To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.

Can you run JavaScript locally?

If you save your JavaScript in it's own file, you can run the entire file at once with nodejs by typing node <filename> where filename is the file you want to run. If you have node installed and you are using a text editor to write JavaScript in separate files you can use your editor to run your code.

Can JavaScript be used outside of a browser?

JavaScript was initially created as a browser-only language, but it is now used in many other environments as well.

What allows JavaScript to be executed outside of a browser?

Node. js allows JavaScript to be run outside of the browser. To help manage external dependencies, the installation comes with NPM.


2 Answers

I found a similar post that has a relatively up to date answer for your question - Run DOM-based Javascript from command line

The main issue is that the browser is actually what creates the DOM that you want to interact with. So without some sort of "browser" running, we have no DOM. But there are some tools available (like Selenium) that can automate/simulate firing up a browser, creating the DOM, and running your javascript.

like image 98
Tim Hoffman Avatar answered Oct 13 '22 11:10

Tim Hoffman


I've seen scratchpad mentioned a lot here (and alternatives like scratch js), but your answer specifically asks for an alternative. Node.js will work well for this purpose, but can't, by default, manipulate the DOM. There are two options for packages that do a slightly different job at this point. One is called jsdom, and allows you manipulate the DOM from given source code. Since you said you were looking for a solution like scratchpad, puppeteer might also work. It uses headless chromium and will let you control chromium programatically. I think you want puppeteer, but that technically uses a browser, so you might want jsdom.

Steps:

  1. Download and install nodejs from https://nodejs.org/
  2. Choose if you want to use puppeteer or jsdom (detailed above).
  3. Make a directory for your project and change into it: mkdir javascript && cd javascript
  4. Initialize the directory with npm (the node package manager): npm init -y
  5. If you choose puppeteer:
    • Install puppeteer: npm install puppeteer
    • Create and edit index.js to have the following:
      const puppeteer = require('puppeteer');
      
      (async () => {
        const browser = await puppeteer.launch();
      
        const page = await browser.newPage();
        await page.goto('https://example.com');
      
        await page.addScriptTag({content:`
          document.querySelector('div>h1').textContent = 'Example Puppeteer'
        `})
        await page.evaluate(() => {
          document.querySelector('div>p').textContent = "Just another way to do things."
        });
        // this ^ is slightly different because in the
        // first the javascript is being injected as a
        // script tag, while in the second the div>p is
        // actually being manipulated. The first would
        // probably be closer to scratchpad though.
      
        await page.screenshot({path: 'screenshot.png'});
        await browser.close();  
      })();
      
    • Run node index.js
    • The screenshot at screenshot.png should be of the manipulated DOM
  6. If you choose jsdom:
    • Install jsdom: npm install jsdom
    • Create and edit index.js:
      const { JSDOM } = require('jsdom')
      const { document } = (new JSDOM(`<!DOCTYPE html><html><head></head><body><p>Hello</p></body></html>`)).window
      document.querySelector('p').textContent = 'Hello World!'
      console.log(document.querySelector('p').textContent) // Will output 'Hello World!'
      
    • Run node index.js
    • You should see "Hello World!" in your console.
like image 21
Nathan Chu Avatar answered Oct 13 '22 11:10

Nathan Chu