使用PhantomJS調用page.evaluate()
時,是否可以在嵌入式JavaScript文件中引用函數?如何從evaluate()訪問注入的.js文件中的函數?
例如我想調用包含在文件my.js功能someFunctionInMyJs
:
var page = require('webpage').create();
page.injectJs('my.js')
page.open('http://...', function() {
var x = page.evaluate(function() {
var y = someFunctionInMyJs();
return y;
});
phantom.exit();
});
這是可能的/有沒有其他辦法?
my.js看起來是這樣的:
function someFunctionInMyJs() {
return 'Hi there!';
}
,我得到的錯誤是:
ReferenceError: Can't find variable: someFunctionInMyJs
my.js在於在那裏我調用PhantomJS的文件夾中。
你的例子my.js包含一個語法錯誤。請註冊['onConsoleMessage'](http://phantomjs.org/api/webpage/handler/on-console-message.html)和['onError'](http://phantomjs.org/api/webpage /handler/on-error.html)事件。也許有錯誤。如果沒有錯誤,你可以嘗試顯式地將函數定義爲'window.someFunctionInMyJs = function(){...}'。 – 2014-10-02 07:22:39
@Artjom謝謝:我已經使用http://esprima.org/demo/validate.html修復了JS,但我仍然無法獲得要識別的功能。你能否在答案中粘貼一個「窗口」的例子。下面的用法?我試過http://phantomjs.org/api/webpage/method/inject-js.html這個例子,但也有問題。我確信我在做一些愚蠢的事情。 – davek 2014-10-02 10:00:27