2016-11-18 78 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

更新的代碼有效。這是一個很好的解決方法,我不會想到以這種方式使用警報。 –