我正在使用 jsdom 来读取包含头部脚本的HTML文件,而脚本又包含更多脚本。我的问题是html加载中的脚本没有问题,但是它们包含的脚本没有被执行。
var fs = require('fs');
var jsdom = require('jsdom');
var doc = jsdom.jsdom(fs.readFileSync("./index.html"), null, {
features: {
FetchExternalResources : ['script'],
ProcessExternalResources : ['script'],
MutationEvents : '2.0',
}
});
var window = doc.createWindow();
// Wait for the window to load so all the scripts are available.
window.addEventListener('load', function() {
// Print all the script tags in the html
var scripts = window.document.getElementsByTagName('script');
scripts = Array.prototype.slice.call(scripts);
scripts.forEach(function(val) {
console.log(val.src);
});
// The loop above prints out
// =============================
// index.js
// another.js
// It should be
// =============================
// index.js -> In the html
// another.js -> Added by index.js
// testing.js -> Added by another.js but should not load since there is no file. That is expected.
console.log('test1: ' + window.test1); // This works! :)
console.log('test2: ' + window.test2); // This fails :(
});
<!DOCTYPE html>
<html>
<head>
<!-- This will add a script tag for another.js -->
<script src="index.js"></script>
</head>
<body>
</body>
</html>
var script = document.createElement('script');
script.src = "another.js";
document.getElementsByTagName('head')[0].appendChild(script);
window.test1 = 'hello world'; // This works
// For some reason this file is not being evaluated.
window.test2 = 'hello world';
var script = document.createElement('script');
script.src = "testing.js";
document.getElementsByTagName('head')[0].appendChild(script);
我会永远感激能帮助我的人。