我正在尝试使用PhantomJS 预渲染 MathJax html文件。例如,假设在math.html
我有:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="MathJax/MathJax.js"></script>
<script src="ConfigMathJax.js"></script>
</head>
<body>
<span class="math">\(e = m c^2\)</span>
</body>
</html>
我的(损坏的)渲染脚本目前看起来像:
var page = require('webpage').create();
var system = require('system');
var fs = require('fs');
page.open(system.args[1], function () {
page.evaluate(function(){
var flag = false;
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
MathJax.Hub.Queue(function(){
console.log(page.content);
phantom.exit();
});
});
});
我尝试将页面写入标准输出并退出after从队列中调用MathJax渲染命令。但似乎我在“页面”的上下文而不是顶级幻影上下文。无法找到变量page
:ReferenceError: Can't find variable: page
。
我在setTimeout
而不是使用旗帜
var page = require('webpage').create();
var system = require('system');
var fs = require('fs');
page.open(system.args[1], function () {
page.evaluate(function(){
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
});
setTimeout(function(){
console.log(page.content);
phantom.exit();
},10000);
});
然后我得到了所需的输出,但当然等待时间10000
ms将取决于内容。
如何让PhantomJS知道MathJax已完成渲染?
这是沙箱问题吗?
答案 0 :(得分:1)
尝试以下方法:
var page = require('webpage').create();
var system = require('system');
var fs = require('fs');
page.open(system.args[1], function () {
page.evaluate(function () {
MathJax.Hub.Queue(
["Typeset",MathJax.Hub],
function () {
console.log(page.content);
phantom.exit();
}
);
});
});
这将使控制台输出和phantom.exit()
调用排队,在排版发生后立即发生。我还没有对代码进行测试,但这是与MathJax进程同步的方法。
<强>更新强>
试试这个:
var page = require('webpage').create();
var system = require('system');
var fs = require('fs');
page.open(system.args[1], function () {
page.onAlert = function (msg) {
if (msg === "MathJax Done") {
console.log(page.content);
} else if (msg === "MathJax Timeout") {
console.log("Timed out waiting for MathJax");
} else {console.log(msg)}
phantom.exit();
};
page.evaluate(function () {
MathJax.Hub.Queue(
["Typeset",MathJax.Hub],
[alert,'MathJax Done']
);
setTimeout(function () {alert("MathJax Timeout")},10000); // timeout after 10 seconds
});
});