问题
I'm trying to pre-render a MathJax html file using PhantomJS. For example, suppose in math.html
I have:
<!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>
My (broken) render script currently looks like:
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();
});
});
});
I've attempted to write the page to standard out and exit after the MathJax render command is called from the queue. But it seems I'm in the "page"'s context rather than the top-level Phantom context. The variable page
can't be found: ReferenceError: Can't find variable: page
.
It I hack in a setTimeout
instead of using the flag:
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);
});
then I get the desired output, but of course the wait time 10000
ms will depend on the content.
How can I let PhantomJS know that MathJax is done rendering?
Is this a sandbox issue?
回答1:
Try the following:
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();
}
);
});
});
This will queue the console output and phantom.exit()
calls to occur immediately after the typesetting occurs. I haven't tested the code, but this is the way to synchronize something with MathJax's process.
UPDATE
Try this:
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
});
});
来源:https://stackoverflow.com/questions/40669585/how-can-i-force-phantomjs-to-wait-until-mathjax-is-finished