我开始使用 JSDOM,并且它可以正常工作:
jsdom.env(
'<p><a class="the-link" href="https://github.com/tmpvar/jsdom">jsdom\'s Homepage</a></p>',
["http://127.0.0.1:8080/js/test.js"],
function (errors, window) {
//console.log("contents of a.the-link:", window.$("a.the-link").text());
console.log(errors);
console.log(window.myVar);
console.log(window.test);
});
Test.js 脚本非常简单:
console.log("testing testing testing");
window.myVar = "myVar Content";
var test = "test content";
执行脚本时会显示myVar和test的内容。
但问题是当我开始以硬核方式进行时(硬核如文档所述):
我执行以下操作:
var jsdom = require("jsdom").jsdom;
var document = jsdom("<html><head></head><body>hello world</body></html>");
var window = document.parentWindow;
var script = document.createElement("SCRIPT");
script.src = "http://127.0.0.1:8080/js/test.js";
var head= window.document.getElementsByTagName('head')[0];
head.appendChild(script);
var window = document.parentWindow;
console.log("myVar Content: " + window.myVar);
在这种情况下,window.myVar 是未定义的。
我错过了什么?
谢谢。
最佳答案
我找到了方法:
var jsdom = require("jsdom").jsdom;
var document = jsdom("<html><head></head><body>hello world</body></html>");
var window = document.parentWindow;
var script = document.createElement("script");
script.type = "text/javascript";
var fs = require("fs");
var requireJSFile = fs.readFileSync("test.js","utf8");
script.innerHTML = requireJSFile;
var head= window.document.getElementsByTagName('head')[0];
head.appendChild(script);
var window = document.parentWindow;
console.log(document.innerHTML);
console.log("myVar Content: " + window.myVar);
我将在 var 中添加一个函数,然后看看是否可以将其用作:window.myVar(param1, param2, param3)。
我很确定它会起作用。
关于javascript - JSDOM - 硬核方式 - 添加外部脚本并使用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19490572/