JSDOM - 硬核方式 - 添加外部脚本并使用它
JSDOM - Hardcore way - Add external script and use it
我开始使用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 和测试的内容。
但问题是当我开始以硬核方式(如文档所述硬核)执行此操作时:
我执行以下操作:
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)。
我很确定它会起作用。
相关文章:
- 如何将脚本添加到<头部>标记
- 将Google Adwords脚本添加到Vaadin应用程序中
- 如何以编程方式将内容脚本添加到 iframe 文档
- 使用java脚本添加图像进行测验
- 我如何向这个脚本添加一个点击按钮循环URL函数(按给定顺序在URL之间切换),或者这可能吗
- 我在向jquery脚本添加延迟时遇到问题
- 如何使用java脚本添加链接
- 如何将自定义脚本添加到运行javascript文件的package.json文件中
- 取消绑定由加载jQuery'的外部脚本添加的事件;s的getScript函数
- 如何最好地将跟踪脚本添加到您的网站
- 如何将谷歌地图脚本添加到wordpress帖子中
- 如何让我的重定向脚本添加一个随机后缀来选择网站
- 星云脚本添加在 EasyPHP 上
- ASP.Net 将脚本添加到脚本管理器时,更新进度中断
- 从脚本添加的输入框中获取值
- 向此 jQuery 脚本添加动画
- 如何使用我的 jQuery 日期选择器脚本添加 dd-mm-yy 的日期格式
- 使用脚本添加两个同名的数组值
- 让 Modernizr.load() 将脚本添加到页面末尾
- 将脚本添加到 asp.net 内容页面