我正在尝试使用 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 渲染命令从队列中调用。但似乎我在“页面”的上下文中,而不是在顶级 Phantom 上下文中。找不到变量 page
:ReferenceError:找不到变量: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 已完成渲染?
这是沙盒问题吗?
最佳答案
尝试以下操作:
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
});
});
关于javascript - 我怎样才能强制 PhantomJS 等到 MathJax 完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40669585/