2015-11-03 66 views
1

我有以下代碼:nightmare.js如何實現像window.callPhantom()函數的功能?

var nightmare = Nightmare(option) 
nightmare 
    .goto('some url') 
    .evaluate(() => { 
    window.callback = function(cid) { 
     // do some stuff 
     // should screenshot at this point. 
    } 
    }) 
    .screenshot('./png.png') //Doesn't get accurate png here 
    .end() 

我想是在瀏覽器中添加範圍回調,並在瀏覽器的範圍,如果它存在在某些時候我會調用回調函數。在那個回調函數中,我會調用主進程在該回調函數結束時截圖。

它像phantom.js中的window.callPhantom。但我無法找到如何在nightmare.js中做到這一點。

任何想法?

+0

從瀏覽器發送的事件和[上偵聽事件](https://github.com/segmentio/nightmare#onevent-callback)在惡夢可能是一種選擇,我還沒有嘗試過不過。還有一個圖書館[噩夢 - 自定義事件](https://github.com/rosshinkley/nightmare-custom-event)添加自定義事件。 – pcworld

回答

2

您可以使用wait(fn),fn是一個將在頁面上執行並返回true以停止等待的函數。

var nightmare = Nightmare(option) 
nightmare 
    .goto('some url') 
    .wait(function() { if(something_to_watch) return true; }) 
    .screenshot('./png.png') 
    .end() 
+0

但是,如何檢查我的回調函數是否在頁面上進行了評估?你的意思是添加一個全局變量?我曾試過這種噩夢會持續下去的方式。 – plrthink

+0

是的,一個全局變量應該工作。也許問題在於Nighmare未能正確評估你的頁面?嘗試在幾秒鐘內設置一個等待,看看你是否可以呈現你期望的,否則這將意味着惡夢無法正確處理頁面。 – Cyrbil

+0

我再次嘗試過,但仍然失敗。它像'nighmare.evaluate(()=> {window .__ screenshotReady = true})。wait(()=> {return window .__ screenshotReady})',仍然掛着調試信息'nightmare queuing action「截圖」+ 0ms ' – plrthink