从PhantomJS中调用变量调用injectJS

Fel*_*lix 8 phantomjs

我已经按照从入门页面注入jQuery的示例,这很好用.我在同一目录中有一个jQuery的本地副本,并执行类似...

if(page.injectJs('jquery.min.js')) {
  page.evaluate(function(){
    //Use jQuery or $ 
  }
}
Run Code Online (Sandbox Code Playgroud)

当我尝试注入自己的脚本时,我没有任何函数可用.假设我有一个名为myScript.js的脚本

function doSomething() {
  // doing something...
}
Run Code Online (Sandbox Code Playgroud)

我不能再使用doSomething ...

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

我试过了

window.doSomething = function() {};
Run Code Online (Sandbox Code Playgroud)

document.doSomething = function() {};
Run Code Online (Sandbox Code Playgroud)

同时没有运气,以及尝试在随后的page.evaluate()中使用window.doSomething()或document.doSomething()调用它们.

Poo*_*imi 7

以下对我有用,也许你的app逻辑的其他部分是错误的:

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()
Run Code Online (Sandbox Code Playgroud)

do.coffee:

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

结果:

> 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
Run Code Online (Sandbox Code Playgroud)

或者如果您更喜欢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);
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)