[英]Node.js jsdom set document root
I am trying to load local javascripts with jsdom. 我正在尝试使用jsdom加载本地javascript。 Now I am wondering how I can make jsdom loading the javascripts from "__dirname/../public". 现在,我想知道如何使jsdom从“ __dirname /../ public”加载javascript。 Can someone help me? 有人能帮我吗?
My current code is: 我当前的代码是:
var fs = require('fs');
var jsdom = require('jsdom');
jsdom.defaultDocumentFeatures = {
FetchExternalResources: ["script"],
ProcessExternalResources: ["script"],
MutationEvents : '2.0',
QuerySelector : false
};
exports.test = function(req, res) {
var html = fs.readFileSync(__dirname+'/../public/html/lame.html');
var document = jsdom.jsdom(html, null, {documentRoot: __dirname+'/../public/'});
var window = document.createWindow();
window.addEventListener('load', function () {
//window.$('script').remove();
//window.$('[id]').removeAttr('id');
res.send(window.document.innerHTML);
window.close();
});
}
The simple HTML page is: 简单的HTML页面是:
<html>
<head>
<title id="title">bum</title>
<script type="text/javascript" src="/javascripts/jquery.min.js"></script>
<script type="text/javascript" src="/javascripts/stuff.js"></script>
</head>
<body>
<h1>hello world</h1>
<h2 id="bam">XXX</h2>
</body>
</html>
I've run into the same issue and got it to work. 我遇到了同样的问题,并使其起作用。 Try these, in order: 尝试以下顺序:
documentRoot
is not documented. documentRoot
未记录。 The option which is documented is url
. 这是该选项记录为url
。 So replace documentRoot
with url
. 因此,将url
替换为documentRoot
。
If the above is not enough, then add a base
element. 如果以上还不够,请添加一个base
元素。 I've set my templates like this: 我将模板设置如下:
<head> <base href="@BASE@"></base> <!-- ... --> </head>
where @BASE@
is replaced with the same value as the one passed to url
. 其中@BASE@
被替换为与传递给url
值相同的值。
The solutions above are extracted from actual code in use in a test suite. 上面的解决方案是从测试套件中使用的实际代码中提取的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.