2012-04-14 34 views
8

我已經遵循了從入門頁面注入jQuery的示例,並且工作得很好。我的jQuery在同一目錄中的本地副本,這樣做......從PhantomJS調用來暴露變量injectionJS

if(page.injectJs('jquery.min.js')) { 
    page.evaluate(function(){ 
    //Use jQuery or $ 
    } 
} 

當我嘗試注入我自己的腳本(S),沒有的功能是提供給我。說我有一個名爲myScript.js腳本,只是有

function doSomething() { 
    // doing something... 
} 

我不能再使用DoSomething的喜歡...

if(page.injectJs('myScript.js')) { 
    console.log('myScript injected... I think'); 
    page.evaluate(function() { 
    doSomething(); 
    }); 
} else { 
    console.log('Failed to inject myScript'); 
} 

我已經試過

window.doSomething = function() {}; 

document.doSomething = function() {}; 

以及沒有運氣,以及試圖在隨後的page.evaluate()中用window.doSomething()或document.doSomething()調用它們。

回答

7

以下爲我的作品,也許您的應用程序邏輯的其他部分是錯誤的:

inject.coffee

page = require('webpage').create() 

page.onConsoleMessage = (msg) -> console.log msg 

page.open "http://www.phantomjs.org", (status) -> 
    if status is "success" 
    page.includeJs "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js", -> 
     if page.injectJs "do.js" 
     page.evaluate -> 
      title = echoAndReturnTitle('hello') 
      console.log title 
     phantom.exit() 

do.coffee

window.echoAndReturnTitle = (arg) -> 
    console.log "echoing '#{arg}'" 
    console.log $(".explanation").text() 
    return document.title 

結果:

> phantomjs inject.coffee 
echoing 'hello' 

      PhantomJS is a headless WebKit with JavaScript API. 
      It has fast and native support for various web standards: 
      DOM handling, CSS selector, JSON, Canvas, and SVG. 
      PhantomJS is created by Ariya Hidayat. 

PhantomJS: Headless WebKit with JavaScript API 

或者如果你喜歡的JavaScript(它們是自動生成的,有點醜):

`inject.js':

// Generated by CoffeeScript 1.3.1 
(function() { 
    var page; 

    page = require('webpage').create(); 

    page.onConsoleMessage = function(msg) { 
    return console.log(msg); 
    }; 

    page.open("http://www.phantomjs.org", function(status) { 
    if (status === "success") { 
     return page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js", function() { 
     if (page.injectJs("do.js")) { 
      page.evaluate(function() { 
      var title; 
      title = echoAndReturnTitle('hello'); 
      return console.log(title); 
      }); 
      return phantom.exit(); 
     } 
     }); 
    } 
    }); 

}).call(this); 

do.js

// Generated by CoffeeScript 1.3.1 
(function() { 

    window.echoAndReturnTitle = function(arg) { 
    console.log("echoing '" + arg + "'"); 
    console.log($(".explanation").text()); 
    return document.title; 
    }; 

}).call(this); 
+0

謝謝,這幫了我很多! – 2012-07-17 12:55:26