Exposing variables from PhantomJS call to injectJS

故事扮演 提交于 2019-12-03 14:05:01

The following works for me, maybe some other part of your app logic is wrong:

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

Result:

> 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

or if you prefer JavaScript (they're auto-generated and a little ugly):

`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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!