Skip to content

Instantly share code, notes, and snippets.

@firedfox
Created April 24, 2012 02:12
Show Gist options
  • Save firedfox/2475509 to your computer and use it in GitHub Desktop.
Save firedfox/2475509 to your computer and use it in GitHub Desktop.
phantomjs onDOMContentLoaded
const PHANTOM_FUNCTION_PREFIX = '/* PHANTOM_FUNCTION */';
var page = require('webpage').create();
page.onConsoleMessage = function(msg) {
if (msg.indexOf(PHANTOM_FUNCTION_PREFIX) === 0) {
eval('(' + msg + ')()');
} else {
console.log(msg);
}
};
page.onInitialized = function() {
page.evaluate(function(domContentLoadedMsg) {
document.addEventListener('DOMContentLoaded', function() {
console.log(domContentLoadedMsg);
}, false);
}, PHANTOM_FUNCTION_PREFIX + page.onDOMContentLoaded);
};
page.onDOMContentLoaded = function() {
// your code here
console.log('DOMContentLoaded');
phantom.exit();
};
page.open('http://phantomjs.org/');
@mirlord
Copy link

mirlord commented Dec 23, 2012

Starting from phantomjs-1.6 there is a better solution accessible:

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

page.onInitialized = function() {
  page.evaluate(function(domContentLoadedMsg) {
    document.addEventListener('DOMContentLoaded', function() {
      window.callPhantom('DOMContentLoaded');
    }, false);
  });
};

page.onCallback = function(data) {
  // your code here
  console.log('DOMContentLoaded');
  phantom.exit(0);
};

page.open('http://phantomjs.org/');

@riston
Copy link

riston commented Mar 8, 2016

Any visitors who come on this page just mention, that the second example is not working with phantom v2.x.

@aaronorosen
Copy link

I tried both of these solutions and it seems like both of them end up getting stuck in a loop and crashing?

DOMContentLoaded
RangeError: Maximum call stack size exceeded.

undefined:0 in evaluateJavaScript
phantomjs://platform/webpage.js:390 in evaluate
phantomjs://code/v2.js:16 in onInitialized
:0 in exit
:4
RangeError: Maximum call stack size exceeded.

undefined:0 in exit
:4
RangeError: Maximum call stack size exceeded.

undefined:0 in exit
:4
PhantomJS has crashed. Please read the bug reporting guide at
http://phantomjs.org/bug-reporting.html and file a bug report.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment