2016-11-18 75 views
2

我正在尝试预呈现使用PhantomJS的MathJax html文件。例如,假设在math.html我:如何强制PhantomJS等待MathJax完成?

<!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毫秒将取决于内容。

我该如何让PhantomJS知道MathJax完成了渲染?

这是沙箱问题吗?

+1

JavaScript是单线程的。您无法使用异步事件停止无限循环,因为在线程可用之前该事件被阻止。 – 4castle

+0

嗯,我太快地读到这个答案:http://stackoverflow.com/a/22125915/148668 –

+1

确切地说,不是在回调中设置一个标志,而是在回调中放置要执行的语句。 – 4castle

回答

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进程同步的方式。


UPDATE

试试这个:

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 
    }); 
}); 
+0

似乎沙盒正在挫败这一点。我得到'ReferenceError:无法找到变量:页面。 –

+0

我用新版本更新了我的答案以尝试。您可能还会在几年前查看[我提供的代码](https://groups.google.com/forum/#!msg/mathjax-users/nQXVaFi4IKQ/AwZ-UrRhiDAJ),以便通过phantom.js从MathJax生成SVG(这已经被mathjax-node取代,正如彼得所建议的那样)。我从早先的代码示例中挑选了上面的代码。 –

+0

更新的代码有效。这是一个很好的解决方法,我不会想到以这种方式使用警报。 –