获取 jsdom window 变量
Fetching a jsdom window variable
我正在尝试从外部访问 jsom 实例中的变量:
这是一个例子:
<!doctype html>
<html lang="en">
<head>
...
<script>
window.foo = "hello world";
</script>
</head>
....
</html>
然后尝试从 "outside" jsdom 访问 foo 变量:
let dom = new JSDOM(...);
dom.window.onload = () => { console.log(dom.window.foo); }; // prints undefined
这个问题似乎描述了一个 identical GitHub issue 作者通过删除 resources 选项解决了它。但是,我不能那样做,因为我需要 运行.
的外部脚本
有什么方法可以调用函数或访问 jsdom 实例中存在的某些变量,resources 设置为 usable ?
请参阅 the documentation 内容:
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
因此:
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); };
我正在尝试从外部访问 jsom 实例中的变量:
这是一个例子:
<!doctype html>
<html lang="en">
<head>
...
<script>
window.foo = "hello world";
</script>
</head>
....
</html>
然后尝试从 "outside" jsdom 访问 foo 变量:
let dom = new JSDOM(...);
dom.window.onload = () => { console.log(dom.window.foo); }; // prints undefined
这个问题似乎描述了一个 identical GitHub issue 作者通过删除 resources 选项解决了它。但是,我不能那样做,因为我需要 运行.
的外部脚本有什么方法可以调用函数或访问 jsdom 实例中存在的某些变量,resources 设置为 usable ?
请参阅 the documentation 内容:
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
因此:
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); };