Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

179
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda