I'm trying create a JSDom document that contains a global var and then trying to change it's value programatically and then print the output again.
My code is the following:
const { JSDOM } = require('jsdom');
const dom = new JSDOM(`
<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<body>
<script>
var myGlobalVar = 'foo';
</script>
</body>
</html>`,
{ runScripts: 'dangerously' });
dom.window.myGlobalVar = 'bar';
console.log(dom.serialize())
I would expect the output to be the same document but with the value of myGlobalVar
updated to "bar"
. This is not happening and myGlobalVar
is still "foo"
.
Does anyone know what I'm doing wrong and if what I want is possible?
Thanks in advance for any help.
dom.window.myGlobarVar = “bar”
sets a property on the window object it doesn’t change the content of the DOM you have provided to the JSDom constructor. If you console.log(dom.window.myGlobalVar)
, you should see the output as bar
.