Pearl Crescent
Pearl Crescent
Page Saver Toolkit Documentation
Pearl Crescent Page Saver Toolkit Documentation
Overview
The Pearl Crescent Page Saver Toolkit is an extension for Mozilla Firefox that provides APIs to allow you to leverage the page capture capabilities of Page Saver Pro.

Here are some examples of what you can do with the Toolkit:

  • Add a "Capture Page" button to your web pages to allow your internal quality assurance team to file better bug reports.
  • Add code to your web application so it automatically captures a screenshot of each page it generates during automated test runs.
  • Create a Firefox extension that captures a thumbnail image of each page you visit during a browsing session

Before you can use the Toolkit, you must install it in Firefox.  You must also install Page Saver Pro 2.5 or newer.  For more information about installing extensions, please refer to these instructions (from AccessFirefox.org).

Capturing Images from a Web Page
To make it easier to use the API, we created a small JavaScript file named pagesaver-toolkit.js which you may download and use in your own web pages.  The examples presented in this section use this file.
Download pagesaver-toolkit.js     View

Enabling Web Page Access to the API
For security reasons, unprivileged JavaScript code in a web page is not able to use the Page Saver API by default.  It should only be enabled if you are operating Firefox within a controlled environment (for example, if it is being used for automated quality assurance testing on computers that are protected by a firewall).

Page Saver Toolkit Options
Figure 1 — The Page Saver Toolkit Options Window
To allow JavaScript code within web pages to access the Page Saver API, check the box located in the Toolkit options window as shown in Figure 1.  To open the options window, choose Add-ons from Firefox's Tools menu and then double-click Pearl Crescent Page Saver Toolkit.  You may also use the about:config advanced configuration editor to set the value of the pagesaver.api.webpageaccess.enabled preference to true.
Initializing the API
The main Page Saver Toolkit API call is the PageSaverCaptureImage() function, which may be called after the API is initialized.  To initialize the API, send a PageSaverInitAPI event to the window, or use the PageSaverInitialize() function that is included in pagesaver-toolkit.js.  Example 1 shows how to call PageSaverInitialize().
<script language="JavaScript" src="pagesaver-toolkit.js"
          type="text/javascript"></script>
<script type="text/javascript">
  var havePSAPI = PageSaverInitialize();
  if (!havePSAPI)
    alert("Sorry. The Page Saver API is not available.");
</script>
Example 1 — Initializating the Toolkit

Initialization needs to be done only once.

Capturing a Page
To capture an image of a page, call the PageSaverCaptureImage() function.  You should not call PageSaverCaptureImage() function a second time until the previous page capture operation has finished.  Refer to the Using a Completion Function section to learn how to get notified when an operation has finished.

Example 2 is an HTML page that captures an image of its entire contents after it is loaded and saves the result as a JPEG file.

<html>
<head>
  <title>Page Saver Toolkit — Example 2</title>
<script language="JavaScript" src="pagesaver-toolkit.js"
        type="text/javascript"></script>
<script type="text/javascript">
function SaveAsJPEG()
{
  if (!PageSaverInitialize())
    alert("Sorry.  The Page Saver API is not available");
  else
  {
    var options = "noInteraction,format=image/jpeg@quality=90";
    PageSaverCaptureImage(null, kPageSaverPortionEntire,
                         kPageSaverDestinationLocalFile, null,
                         options, null);
   }
  }
</script>
</head>
<body onload="setTimeout('SaveAsJPEG();', 0);">
This page contains an onload handler that saves an image of this page to
a file.
<p>The file will be saved to Page Saver Pro's default file location.
</body>
</html>
Example 2 — Capturing an Image of an Entire Page

PageSaverCaptureImage() Details
The PageSaverCaptureImage() function offers a high level of control over the content being captured.  Its six parameters are:
captureWindow
The window whose contents should be captured.  Pass null to capture the contents of the window your JavaScript code is running in.
capturePortion
The portion of the window to capture.  The possible values are:
kPageSaverPortionVisible (0)
Capture the visible portion.
kPageSaverPortionEntire (1)
Capture the entire page.
kPageSaverPortionSelected (2)
Capture a region of the page that is selected interactively.
destination
Specifies where the captured imaged will be saved.  The possible values are:
kPageSaverDestinationDefault (-2)
The default destination from the Page Saver Pro options.
kPageSaverDestinationClipboard (-1)
The system clipboard (available on Windows and Mac OS).
kPageSaverDestinationLocalFile (0)
A local file.
kPageSaverDestinationServer (1)
A remote file, using the FTP or HTTP server settings from the Page Saver Pro options or an URL passed in the destPathOrURI parameter.
destPathOrURI
The pathname of a local file or an URL for a server where the image should be saved.  When specifying a file pathname, use the format appropriate for the system where the browser is running; for example, on Linux you might use a path like /tmp/page.png while on Windows you might use c:\page.png.  When specifying a server location, use an ftp://, http://, or an https:// URL.  Include the password in the URL if it has not been saved in the Firefox Password Manager.

To save the captured image in the default file location, pass null for destPathOrURI and pass kPageSaverDestinationLocalFile for the destination parameter.

To save the captured image to the server that is configured in the Page Saver options, pass null for destPathOrURI and pass kPageSaverDestinationServer for the destination parameter.

options
A string that contains a comma-separated list of options that affect the capture process.  The available options are:
closeWhenDone
Close the window after the capture is complete.
exitWhenDone
Exit Firefox after the capture is complete.
noInteraction
Do not interact with the user (for example, do not display any error messages or play the “capture complete” sound).
top=pixelval
Omit from the captured image the first pixelval pixels along the top of page.
left=pixelval
Omit from the captured image the first pixelval pixels along the left side of the page.
bottom=pixelval
Crop the captured image along the bottom at pixelval pixels.  If pixelval is a negative number, crop at pixelval pixels from the bottom.
right=pixelval
Crop the captured image along the right side at pixelval pixels.  If pixelval is a negative number, crop at pixelval pixels from the right.
element=elemid
Restrict the captured image to a rectangle that encompasses the DOM element with an id of elemid.
scale=scaleval
Reduce or limit the size of the captured image.  If scaleval ends with a % character, the image is scaled to the specified percentage.  If scaleval is a simple integer, the largest dimension of the resulting image will be at most scaleval pixels.
format=content-type
Save the image using the format specified by content-type.  The supported values are image/jpeg and image/png.

For JPEG images, you can specify the quality factor by appending @quality=value.  For example: format=image/jpeg@quality=75.

For PNG images, you can omit transparency information (alpha channel) by appending @transparency=none.  For example:  format=image/png@transparency=none.

completionFunc
A string that specifies the name of a function that will be called when the image capture operation has completed (pass null if you do not need to be called back).

Your completion callback function will be passed two parameters: aResultCode and aMsg.  The aResultCode parameter is an integer that will contain one of the following values:
kPageSaverResultCodeSuccess (0)
The operation was successful.
kPageSaverResultCodeCancelled (1)
The operation was cancelled by the user.
kPageSaverResultCodeNoInteractionAllowed (2)
The noInteraction option was specified but user interaction is required (for example, to honor a request made with capturePortion == kPageSaverPortionSelected).
kPageSaverResultCodeInvalidArg (3)
An invalid parameter was passed to an API function.
kPageSaverResultCodeNoCanvas (4)
The Page Saver canvas is not available.  This could occur if both the Location Bar and Activity Indicator have been removed from the Firefox toolbar.
kPageSaverResultCodeCanvasDrawingError (5)
A error occurred while trying to draw an image of the page content.
kPageSaverResultCodeCanvasStreamError (6)
A error occurred while trying to extract the image data so it could be saved.
kPageSaverResultCodeInvalidFilePath (7)
The destination file path is invalid.
kPageSaverResultCodeFileOutputError (8)
An error occurred while writing to the destination file.
kPageSaverResultCodeUploadError (9)
An error occurred while uploading an image to a server.
kPageSaverResultCodeClipboardError (10)
An error occurred while trying to copy an image to the system clipboard.
kPageSaverResultCodeElementNotFound (11)
An element=elemid option was used but no page element exists with the ID elemid.
The aMsg parameter contains extra textual information that may be helpful in debugging failures (it may be null).  In addition, when a capture was successful (kPageSaverResultCodeSuccess) but the page was too large to capture in its entirety, aMsg will contain the text imagecropped.  For more information about image capture size limitations, see the section Known Issues and Limitations within the Page Saver documentation.
Using a Completion Function
By passing the name of a completion function to the PageSaverCaptureImage function, you can receive status information when each page capture operation finishes.

Example 3 demonstrates use of a completion function, as well as capturing the contents of an embedded iframe window.  Since the destination is the system clipboard, this example requires Mac OS or Windows.

<html>
<head>
  <title>Page Saver Toolkit — Example 3</title>
  <script language="JavaScript" src="pagesaver-toolkit.js"
          type="text/javascript"></script>
<script type="text/javascript">

function CapturePage(aDestination)
{
  if (!PageSaverInitialize())
  {
    SetStatusText("The Page Saver API is not available");
    return;
  }

  var frameWindow = document.getElementById("theFrame").contentWindow;
  PageSaverCaptureImage(frameWindow, kPageSaverPortionVisible,
                        aDestination, null, null,
                        "OnCaptureComplete");
  SetStatusText("capturing...");
}

function OnCaptureComplete(aResultCode, aMsg)
{
  var text;
  if (aResultCode != kPageSaverResultCodeSuccess)
  {
    text = "capture failed: " + aResultCode;
    if (aMsg)
      text += " (" + aMsg + ")";
  }
  else
    text = "clipboard copy done.";

  SetStatusText(text);
}

function SetStatusText(aText)
{
  var e = document.getElementById("statusText");
  if (e)
    e.innerHTML = aText;
}
</script>
</head>
<body>
Click the button below to copy an image of the visible portion of the
iframe below to the system clipboard.
<p>
<form>
<input type="button" value="Copy to Clipboard"
        onclick="CapturePage(kPageSaverDestinationClipboard)">
  Status: <span id="statusText">Ready</span>
</form>
<p>
<div style="margin-bottom: 5px;">
Site: https://pearlcrescent.com/products/
</div>
<iframe id="theFrame" height="600" width="925"
        src="https://pearlcrescent.com/products/">
</body>
</html
Example 3 — Copying an Image to the Clipboard with Completion Function

Capturing Images from a Firefox Extension
The Page Saver Toolkit also allows privileged (“chrome”) JavaScript or C++ code to capture images of web pages.  This capability allows you to write a Firefox extension for private use that builds on the features provided by Page Saver Pro.
Getting Started
The Page Saver Toolkit extension provides an XPCOM component that implements an interface named pagesaverICapturePageImage.  To use Page Saver API, first create an instance of the component as shown in Example 4.
var cpiObj = Components.classes["@pearlcrescent.com/PSCapturePageImage;1"]
             .createInstance(Components.interfaces.pagesaverICapturePageImage);
Example 4 — Creating a PSCapturePageImage Component
The pagesaverICapturePageImage interface includes a readonly attribute named canCapture, a method named capturePageImage(), and several constants for use in calls to capturePageImage().  You can download or view the interface definition:
Download pagesaverICapturePageImage.idl    View

Using the canCapture Attribute
The canCapture attribute contains a Boolean value that is true if page capture capabilities are available.  For example:
var cpiObj = Components.classes["@pearlcrescent.com/PSCapturePageImage;1"]
             .createInstance(Components.interfaces.pagesaverICapturePageImage);
if (cpiObj.canCapture)
{
  // Page Saver Pro is installed and ready.
}
else
{
  // Page Saver Pro is not installed.
}
Example 5 — Checking the canCapture Attribute
Using the capturePageImage() Method
Call the capturePageImage() method to initiate a page capture operation, a portion of which will take place in the background (asynchronously).  This method accepts five parameters and is defined as:
void capturePageImage(in nsIDOMWindow aContentWindow,
                      in short aCapturePortion,
                      in short aDestination,
                      in nsISupports aDestObj,
                      in string aOptions);
Please refer to the interface definition for a detailed description of each parameter.

Like most XPCOM methods, capturePageImage() may throw exceptions (for example, if you pass it an invalid parameter).

You should not call capturePageImage() a second time until the previous page capture operation has finished.  Refer to the next section, Receiving Notifications, to learn how to be notified when an operation has finished.

Example 6 shows how to use capturePageImage().  The MyPageCapture() function shown might be called from a browser overlay to save an image of the active page to the local file identified by the aDestinationPath parameter.

function MyPageCapture(aDestinationPath)
{
  var cpiObj = Components.classes["@pearlcrescent.com/PSCapturePageImage;1"]
               .createInstance(Components.interfaces.pagesaverICapturePageImage);
  if (cpiObj.canCapture)
  {
    try
    {
      var localFile = Components.classes["@mozilla.org/file/local;1"]
                         .createInstance(Components.interfaces.nsILocalFile);
      localFile.initWithPath(aDestinationPath);

      var options = "noInteraction,format=image/png@transparency=none";
      cpiObj.capturePageImage(document.contentWindow, cpiObj.PORTION_ENTIRE,
                              cpiObj.DESTINATION_LOCALFILE,
                              localFile, options);
    }
    catch (e) {}
  }
}
Example 6 — Using capturePageImage()
Receiving Notifications
When a page capture operation completes, the Page Saver Toolkit broadcasts a message with the topic PageSaver:CaptureComplete that may be received using an observer.  The subject of the notification will be the window whose contents were captured and the data string will contain a numeric status code followed by an optional text message.  If a text message is present, it will follow the numeric status code and a - character.

The text message contains extra information that may be helpful in debugging failures.  In addition, when a capture was successful but the page was too large to capture in its entirety, it will contain the text imagecropped.  For more information about image capture size limitations, see the section Known Issues and Limitations within the Page Saver documentation.

Example 7 shows how to install a PageSaver:CaptureComplete observer.

var myObserver = {
  observe: function(aSubject, aTopic, aData)
  {
    if (aTopic == "PageSaver:CaptureComplete")
    {
      var theWindow = aSubject;
      var rc = -1;
      if (aData != null && aData.length > 0)
        rc = parseInt(aData);
      var textIndex = aData ? aData.indexOf('-') : -1;
      var text = (textIndex > 0) ? aData.substr(textIndex + 1) : null;
      alert("Page Saver Capture done:\n"
           + "window: " + theWindow + "\n"
           + "resultCode: " + rc + "\n"
           + "text: " + text + "\n");
    }
  }
};

...
var obsSvc = Components.classes["@mozilla.org/observer-service;1"]
               .getService(Components.interfaces.nsIObserverService);
obsSvc.addObserver(myObserver, "PageSaver:CaptureComplete", false);
Example 7 — Using a PageSaver:CaptureComplete Observer
Troubleshooting
If you encounter an unexpected error, please follow these suggestions:
  • Verify that the most recent versions of both the Page Saver Pro and Page Saver Toolkit extensions are installed and enabled.
  • If you are using the Page Saver API from JavaScript code running in a web page, verify that access by web pages is enabled (see the section Enabling Web Page Access to the API).
  • Check the Firefox Error Console for messages.
  • Use a completion function (if using the Toolkit from a web page) or an observer (if using the Toolkit from a Firefox extension) to check the status code reported by the Page Saver Toolkit.
Additional Assistance
If you need more help or would like to send us a suggestion, please Contact Us.
Other Information
Page Saver Toolkit Extension GUID:
e3aedca3-9871-4dc3-9be8-e175c1513616

Authors and Contributors
  • Kathleen Brade
  • Mark Smith
Subscribe to our announcement list.
Copyright © 2007-2017 Pearl Crescent, LLC.