Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

commented Dec 1, 2016

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
You can’t perform that action at this time.