javascriptnode.jsjsdom

Fetching a jsdom window variable


I'm trying to access a variable inside a jsom instance, from outside:

Here's an example:

<!doctype html>
<html lang="en">
<head>
  ...
  <script>
    window.foo = "hello world";
  </script>
</head>
  ....
</html>

And then trying to access the foo variable from "outside" jsdom:

let dom = new JSDOM(...);
dom.window.onload = () => { console.log(dom.window.foo); }; // prints undefined

This issue seems to describe an identical GitHub issue where the author solved it by removing the resources option. However, I cannot do that because I need external scripts to run.

Is there any way I can call a function or access some variable that exists within a jsdom instance, with resources set to usable?


Solution

  • See the documentation which says:

    jsdom's most powerful ability is that it can execute scripts inside the jsdom. … this is also highly dangerous … the ability to execute scripts embedded in the HTML is disabled by default … To enable executing scripts inside the page, you can use the runScripts: "dangerously" option

    Thus:

    const jsdom = require("jsdom");
    const { JSDOM } = jsdom;
    
    const dom = new JSDOM(`<!doctype html>
    <html lang="en">
    <head>
      ...
      <script>
        window.foo = "hello world";
      </script>
    </head>
      ....
    </html>
    `, { runScripts: "dangerously", resources: "usable" });
    
    dom.window.onload = () => { console.log(dom.window.foo); };