-1

PhantomJS has the worst documentation ever. How do I run a simple .js against a specific html file? If I run phantomjs, I can use the REPL interface run require. How do I run that in such a fashion that window. is set as if a specific html file was the target?

I want to do something like

var $ = require('jquery');
$("div").attr('class');

and get the lists of classes... against this..

<html>
  <head><title>Hello World</title></title>
  <body>
    <div class="foo bar baz"> </div>
  </body>
</html>
Evan Carroll
  • 78,363
  • 46
  • 261
  • 468

2 Answers2

2

Based off of the numerous examples:

'use strict';

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

page.open('your-file.html', function (status) {
    if (status !== 'success') {
        console.log('Unable to load file');
        phantom.exit(1);
    }

    page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js', function () {
        page.onConsoleMessage = function (message) {
            console.log(message);
        };

        page.evaluate(function () {
            console.log($('div').attr('class'));
        });

        phantom.exit();
    });
});

I’ve never used PhantomJS before, and that took 10 minutes. Look harder!

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Except you're using .includeJs which isn't CommonJS which is what I'm trying to test... Happen to know how to get the `require('module')` in there? – Evan Carroll Jul 27 '15 at 06:56
  • 1
    @EvanCarroll Inject requireJS and then use require to require jQuery. `requre` is not available in the page context and jQuery doesn't make sense outside of the page context. – Artjom B. Jul 27 '15 at 11:53
-2

You don't have to use jquery for that. Working example:

var classes = [].map.call(document.querySelectorAll("div"),
                         function(el){ return el.className; });
swift
  • 1,108
  • 7
  • 9