How to use phantom - 10 common examples

To help you get started, we’ve selected a few phantom examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sffc / socketio-file-upload / test / browser-phantom.js View on Github external
async function run(port) {
	// Return value: first error on the client
	let clientError = null;

	// Page will alert when done or failure
	let resolveDonePromise;
	let donePromise = new Promise((resolve) => {
		resolveDonePromise = resolve;
	});

	const instance = await phantom.create();
	const page = await instance.createPage();
	await page.on("onResourceRequested", (requestData) => {
		console.info("requesting:", requestData.url);
	});
	await page.on("onConsoleMessage", (message) => {
		console.log("browser:", message);
	});
	await page.on("onError", (message, trace) => {
		if (!clientError) {
			let traceString = "";
			for (let i=0; i
github skratchdot / color-palette / lib / cli.js View on Github external
// get size and quality
['size', 'quality'].forEach(function (key) {
	program[key] = parseInt(program[key], 10);
	if (!program[key]) {
		console.error('The palette ' + key + ' must be a positive integer.');
		process.exit();
	}
});

var toHexColor = function (rgbArray) {
	var parsedColor = onecolor('rgb(' + (rgbArray || []).join(',') + ')');
	return parsedColor && parsedColor.isColor ? parsedColor.hex() : '';
};

phantom.create('--web-security=false', '--ignore-ssl-errors=true', '--ssl-protocol=TLSv1', {
	path: path.dirname(phantomjs.path) + path.sep,
	onStdout: function () {},
	onStderr: function () {},
	onExit: function () {}
}, function (ph) {
	ph.createPage(function (page) {
		page.set('viewportSize', {width: 1024, height: 1024}, function () {
			page.open(output.uri, function (success) {
				output.success = success === 'success';
				page.renderBase64('png', function (imageBase64) {
					var html;
					// setup image data uri
					imageBase64 = 'data:image/png;base64,' + imageBase64;
					// cheap hack
					html = [
						'',
github amir20 / phantomjs-node / bin / phantom.js View on Github external
(async function main() {
  const instance = await phantom.create();
  const page = await instance.createPage();
  await page.on('onResourceRequested', (requestData) => {
    console.info('Requesting', requestData.url); // eslint-disable-line
  });

  await page.open(url);
  const content = await page.property('content');
  console.log(content); // eslint-disable-line

  await instance.exit();
}());
github brandon93s / spectre / lib / farm / worker.js View on Github external
const debug = log.debugger('worker:' + process.pid);

let _ready = false;
let _ph;

/* Phantom Process Creation
 *
 * spins up a child phantom process and stores a reference
 */
function phantomExitHandler(err) {
  if (err) log.error(err);
  debug('Phantom process exit.');
  process.exit(1);
}

phantom.create().then(ph => {
  _ph = ph;
  _ready = true;

  _ph.process.on('exit', phantomExitHandler);
  _ph.process.on('SIGINT', phantomExitHandler);
  _ph.process.on('uncaughtException', err => {
    log.error(err);
    _ph.process.exit(1);
  });
});

/* Worker Process Exit Handlers
 *
 * cleanup the associated phantom process if the worker dies
 */
function workerExitHandler(err) {
github hacksalot / HackMyResume / src / gen / html-pdf-generator.js View on Github external
phantom: function( markup, fOut ) {
      require('phantom').create( function( ph ) {
        ph.createPage( function( page ) {
          page.setContent( markup );
          page.set('paperSize', {
            format: 'A4',
            orientation: 'portrait',
            margin: '1cm'
          });
          page.set("viewportSize", {
            width: 1024, // TODO: option-ify
            height: 768 // TODO: Use "A" sizes
          });
          page.set('onLoadFinished', function(success) {
            page.render( fOut );
            ph.exit();
          });
        },
github petecoop / phantasma / index.js View on Github external
return new this.promise(function (resolve, reject) {
    phantom.create(function (ph) {
      self.ph = ph;
      ph.createPage(function (page) {
        self.page = page;
        // map phantom callback to signals
        page.set('onAlert', function (msg) {
          self.emit('onAlert', msg);
        });
        page.set('onConsoleMessage', function (msg, lineNum, sourceId) {
          self.emit('onConsoleMessage', msg, lineNum, sourceId);
        });
        page.set('onError', function (msg, trace) {
          self.emit('onError', msg, trace);
        });
        page.set('onLoadFinished', function (status) {
          self.emit('onLoadFinished', status);
        });
github Canop / miaou / plugins / webshot / plugin.js View on Github external
async function onCommand(ct){
	const urlMatch = ct.args.match(/\bhttps?:\/\/\S+/);
	if (!urlMatch) throw new Error("This command needs an URL as argument");
	const url = urlMatch[0];
	console.log('!!webshot url:', url);
	let width = WIDTH;
	let height = HEIGHT;
	const sizeMatch = ct.args.match(/\b(\d+)\s*(?:x|\*)\s*(\d+)\b/);
	if (sizeMatch) {
		width = sizeMatch[1];
		height = sizeMatch[2];
		if (width<10) throw new Error("invalid width");
		if (height<10) throw new Error("invalid height");
		if (height*width>3000*2000) throw new Error("requested size too big");
	}
	const instance = await phantom.create();
	try {
		const page = await instance.createPage();
		await page.property('viewportSize', {width, height});
		const status = await page.open(url);
		console.log('status:', status);
		if (status=="fail") {
			throw new Error("URL fetching failed");
		}
		let image = {
			bytes: await page.renderBase64("png"),
			uploader: ct.shoe.publicUser.id,
			ext: 'png'
		};
		let data = await storeImage(image);
		if (!data.url) { // should not happen, I think (because handled in "upload" lib)
			if (data.error) {
github mwbrooks / web2splash / lib / web2splash.js View on Github external
exports._renderImages = function(input, output, images, callback) {
    /* Create a PhantomJS browser instance called `page`. */
    require('phantom').create(function(phantom) {
        phantom.createPage(function(page) {
            /*
             * Open a new page to the input HTML document. A new page should
             * be opened for each splash screen, otherwise temporal data
             * (e.g. CSS animations) may be carried between each splash screen.
             */
            async.forEach(
                images,
                /* 
                 * For each image:
                 *     - resize the page viewport to the splash screen size
                 *     - open the page to the HTML template
                 *     - render the page to an image file
                 *     - iterate to the `next()` image
                */
                function(image, next) {
github zipfworks / ember-prerender / lib / engines / phantom.js View on Github external
PhantomEngine.prototype.init = function(appUrl, initCallback, errorCallback, beforeInitCallback) {
  var _this = this;

  this.initializationCallback = initCallback;
  this.hasInitializationCallback = true;
  this.contentReadyTimer = null;

  this.engineSettings.onExit = function(code, signal) {
    if (code !== 0) {
      errorCallback("Erroneous exit code: " + code, signal);
    }
  };

  this.phantom = phantom.create("--load-images=false", "--ignore-ssl-errors=true", "--ssl-protocol=any", this.engineSettings, function(ph) {
    _this.phantom.ph = ph;
    _this.phantom.ph.createPage(function(phantomPage) {
      _this.phantom.page = phantomPage;

      _this.phantom.page.set('onConsoleMessage', function(msg) {
        _this.logger.log('debug', '>>>', msg);
      });

      _this.phantom.page.set('onCallback', _.bind(_this.onPageReady, _this));

      _this.phantom.page.set('onError', function(msg) {
        errorCallback("Phantom encountered an error: " + msg);
      });

      // FIXME: Uncomment after resolving issue in phantomjs-node (https://github.com/sgentle/phantomjs-node/issues/203)
      //_this.phantom.page.set('onResourceRequested', function(requestData, networkRequest) {
github travist / jquery.go.js / lib / jquery.go.js View on Github external
// Include the libraries.
var phantomjs = require('phantomjs')
var phantom =   require('phantom');
var async = require('async');
var _ = require('underscore');
var go = require('asyncgo');

// The current page.
var page = null;
var pageQueue = [];
var instance = null;
var loading = true;

// Create the phantom connection.
phantom.create("--web-security=false", "--ignore-ssl-errors=true", "--ssl-protocol=any", function(ph) {

  // Save the instance.
  instance = ph;

  // Create the page.
  return ph.createPage(function(pg) {

    // Set the page.
    page = pg;

    // Num resources outstanding.
    var resources = 0;

    // Whether page has loaded.
    var ready = false;

phantom

PhantomJS integration module for NodeJS

ISC
Latest version published 5 years ago

Package Health Score

55 / 100
Full package analysis

Popular phantom functions