Book Image

PhantomJS Cookbook

By : Rob Friesel
Book Image

PhantomJS Cookbook

By: Rob Friesel

Overview of this book

Table of Contents (15 chapters)
PhantomJS Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a custom module for PhantomJS


In this recipe, we will learn how to create a custom module for PhantomJS that can be imported into our script using the require function.

Getting ready

For this recipe, we will only need a text editor. Some knowledge of CommonJS modules is useful but not strictly necessary.

How to do it…

In our text editor, we write the script that will be our module. As PhantomJS adheres to the CommonJS module system, the contents of this file will not pollute the global execution context after being imported; the only aspects of the script that are exposed will be those items attached to the exports object, and even then it must be assigned to a variable after the require expression.

For example, we could create our module in the following way:

function parseValue(v) {
  if (typeof v === 'undefined') {
    return true;
  } else {
    try {
      return JSON.parse(v);
    } catch (e) {
      return v;
    }
  }
}

function parseArguments(args) {
  return args.reduce(function...