Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda