Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
Running a function (not from a <script> tag) in the context of JSDOM's window object

There are several descriptions of how to run html-embedded scripts with JSDOM, yet I would like to run a function declared in the normal node.js context with a global object from jsdom, like:

import { JSDOM } from 'jsdom';

function addHello() {
  document.body.innerHTML = '<p>hello</p>';
}
const html = '<html><head></head><body></body></html>';
const jsdom = new JSDOM(html, { runScripts: 'outside-only' });
jsdom.window.addHello = addHello;
jsdom.window.eval('addHello()');

According to the JSDOM documentation I thought the runScripts option does the trick, but when running the above code with node I get

  document.body.innerHTML = '<p>hello</p>';
  ^
ReferenceError: document is not defined
    at addHello (file:///.../jsdomTryout.js:4:3)

Note that addHello is only an example. In the real case, it is a method from some larger library and I would prefer to import it in the above script rather than instructing JSDOM to load that library via <script> tags.

Is there a way to get what I want with JSDOM? My suspicion is that this is not possible, because of the way the global object of a function is determined, but maybe there is some "magic" available.

EDIT: Meanwhile I learned that what I am really missing is <script type="module"> support from jsdom to let me have something like

   <script type="module">import 'some-library';</script>

in the html I pass to jsdom and go from there.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!