Box Content Preview

JavaScript library for rendering files stored on Box

The Box Content Preview UI Element allows developers to easily embed high quality and interactive previews of Box files in their desktop or mobile web application. The library fetches information about the file and its converted representations through the Box API, chooses the appropriate viewer for the file type, dynamically loads the necessary static assets and file representations, and finally renders the file. This UI Element also allows previews of multiple files to be loaded in the same container and exposes arrows to navigate between those files.

This UI Element powers Preview in the main Box web application as well as the 'expiring embed' Box API endpoint.

Browser Support

  • Desktop Chrome, Firefox, Safari, and Edge (latest 2 versions)
  • Limited support for Internet Explorer 11 (requires Promise polyfill)
  • Limited support for mobile web (previews will render but some controls may not work)

This UI Element uses Promises. If your application supports Internet Explorer 11, please include your favorite polyfill library or a service like polyfill.io to smartly load only the polyfills your users need.

Current Version

  • Version: 1.19.1
  • Locale: en-US

https://cdn01.boxcdn.net/platform/preview/1.19.1/en-US/preview.js
https://cdn01.boxcdn.net/platform/preview/1.19.1/en-US/preview.css

Supported Locales

To use a different locale, replace en-US in the URLs above with any of the following supported locales:

en-AU, en-CA, en-GB, en-US, da-DK, de-DE, es-ES, fi-FI, fr-CA, fr-FR, it-IT, ja-JP, ko-KR, nb-NO, nl-NL, pl-PL, pt-BR, ru-RU, sv-SE, tr-TR, zh-CN, zh-TW

Supported File Types

Box Content Preview supports 120+ file types, including most document and image formats, HD video, 3D models, 360-degress images, and 360-degree videos. You can find the full list of supported file types at https://community.box.com/t5/Managing-Your-Content/What-file-types-and-fonts-are-supported-by-Box-s-Content-Preview/ta-p/327#FileTypesSupported.

Source Code

Source code for the Preview Element is hosted on GitHub. The repository contains detailed documentation for usage and development. Please file any bugs you encounter under the 'Issues' tab with clear steps to reproduce.

https://github.com/box/box-content-preview

Releases

https://github.com/box/box-content-preview/releases

Usage

You can self-host the Preview UI Element or reference the versions hosted on the Box CDN.

<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="utf-8" />
    <title>Box Content Preview Demo</title>
  
    <!-- polyfill.io only loads a Promise polyfill if your browser needs one -->
    <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Promise"></script>

    <!-- Latest version of Box Content Preview for en-US locale -->
    <script src="https://cdn01.boxcdn.net/platform/preview/1.19.1/en-US/preview.js"></script>
    <link rel="stylesheet" href="https://cdn01.boxcdn.net/platform/preview/1.19.1/en-US/preview.css" />
</head>
<body>
    <div class="preview-container" style="height:400px; width:100%;"></div>
    <script>
        var preview = new Box.Preview();
      	preview.show('93392244621', 'EqFyi1Yq1tD9mxY8F38sxDfp73pFd7FP', {
            container: '.preview-container',
            showDownload: true
        });
    </script>
</body>
</html>

CORS (Cross-Origin Resource Sharing)

For security purposes, you must whitelist your application's HTTP origin, omitting any trailing slash, in the configuration section of the Developer Console. For example, CodePen's domain is whitelisted for the demo application below.

Demo

Use the navigation arrows to preview different file types.

Authentication

UI Elements are compatible with both OAuth and JWT

The UI Elements are designed in an authentication-type agnostic way so whether you are using UI Elements for users who have Box accounts (Managed Users) or non-Box accounts (App Users), UI Elements should just work out of the box. The reason for this is that UI Elements only expect a "token" to be passed in for authentication, and Box provides two different ways to generate tokens - OAuth and JWT.

So depending on which type of app you are building, follow the linked authentication guides above on how to generate access tokens, and refer to the UI Elements documentation below how to pass along those tokens to the Content Preview UI Element.

If you have any questions, please visit our developer forum.

The Preview UI Element needs an access token to make Box API calls. You can either get an access token from the token endpoint (https://docs.box.com/reference#token) or generate a developer token on your application management page (https://blog.box.com/blog/introducing-developer-tokens/).

Tokens on the client

We strongly suggest that before you put this UI Element into production, you leverage the appropriate scope to avoid putting a fully scoped token into the client. See the Scopes section for how to choose and use scopes.

API

const { Preview } = Box;
const preview = new Preview();

/**
 * Shows a preview.
 *
 * @public
 * @param {string} fileId - File ID to preview
 * @param {string} accessToken - Box API access token
 * @param {Object} [options] - Options
 * @return {void}
 */
preview.show(fildId, accessToken, options);

/**
 * Hides the preview.
 * 
 * @return {void}
 */
preview.hide();

/**
 * Prints the current file, if printable.
 * 
 * @return {void}
 */
preview.print();

/**
 * Downloads the current file.
 * 
 * @return {void}
 */
preview.download();

/**
 * Resizes the current preview, if applicable. This function only needs to
 * be called when preview's viewport has changed while the window has not.
 * If the window is resizing, then preview will automatically resize itself.
 * 
 * @return {void}
 */
preview.resize();

/**
 * Adds an event listener to the preview. Listeners should be added
 * before calling show() so no events are missed.
 *
 * @param {string} eventName - Name of the event
 * @param {Function} listener - Callback function
 * @return {void}
 */
preview.addListener();

/**
 * Removes an event listener from the preview.
 * 
 * @param {string} eventName - Name of the event
 * @param {Function} listener - Callback function
 * @return {void}
 */
preview.removeListener(eventName, listener);

/**
 * Removes all event listeners from the preview.
 * 
 * @return {void}
 */
preview.removeAllListeners();

Parameters

Parameter
Description

fileId
string

Box File ID.

accessToken
string

Box API access token to use.

options
Object

Optional options. See below for details. For example: preview.show(FILE_ID, TOKEN, {showDownload: true}) would be used to show the download button in the header.

Options

Option
Default
Description

container
string

document.body

CSS selector of the container in which Preview should be placed.

sharedLink
string

Shared link URL, required if file is shared and the access token doesn't belong to an owner or collaborator of the file. See https://docs.box.com/reference#get-a-shared-item for more details.

sharedLinkPassword
string

Shared link password, required if shared link has a password. See https://docs.box.com/reference#get-a-shared-item for more details.

collection
array

List of file IDs to preview over. When used, this will show previews of multiple files within the same container and expose arrows to navigate between those files. Note that FILE_ID needs to be included in this list and that the SDK doesn't support collections with files that require a shared link or password.

header
string

'light'

Values that control header visibility and background color. Use 'none' for no header, 'light' for a light header and background, and 'dark' for a dark header and background.

logoUrl
string

URL of custom logo to show in header. If this value is the string box then the box logo will show.

showAnnotations
boolean

false

Whether annotation button in header and annotations on content are shown.

showDownload
boolean

false

Whether download button is shown in header. Will also control print button visibility in viewers that support print. Note that this option will not override download permissions on the access token.

Events

The preview object exposes addListener and removeListener for binding to events. Event listeners should be bound before show() is called, otherwise events can be missed.

Viewer Events

The full list of events that each individual viewer fires can be found at https://docs.box.com/docs/file-types-events.

const listener = (value) => {
    // Do something with value
};

// Attach listener before calling show otherwise events can be missed
var preview = new Box.Preview();
preview.addListener(EVENTNAME, listener);

// Show a preview
preview.show(...);

// Remove listener when needed
preview.removeListener(EVENTNAME, listener);

EVENTNAME can be one of the following

  • viewer event will be fired when we have the viewer instance first available. This will be the same object that is also a property included in the load event. Preview fires this event before load so that clients can attach their listeners before the load event is fired.

  • load event will be fired on every preview load when show() is called or if inter-preview navigation occurs. The event data will contain:

error: 'message', // Error message if any error occurred while loading
viewer: {...},    // Instance of the current viewer object if no error occurred
metrics: {...},   // Performance metrics
file: {...}       // Box file object with properties defined in file.js
  • navigate event will be fired when navigation happens. The event includes the file ID of the file being navigated to, and this event will fire before load.

  • notification event will be fired when either the preview wrapper or one of the viewers wants to notify something like a warning or non-fatal error. The event data will contain:

message: 'message', // Message to show
type: 'warning'    // 'warning', 'notice', or 'error'
  • viewerevent Each viewer will fire its own sets of events. For example, the Image viewer will fire rotate or resize, etc. while other viewers may fire another set of events. The full list of events can be found at https://docs.box.com/docs/file-types-events. The preview wrapper will also re-emit events at the preview level, with event data containing:
event: EVENTNAME,         // Event name
data: DATA,               // Event data object
viewerName: VIEWERNAME,   // Name of the viewer. See VIEWERNAME above
fileId: fileId            // The file ID

Example event usage

var preview = new Box.Preview();
preview.addListener('viewer', (viewer) => {
    viewer.addListener('rotate', () => {
        // Do something when a viewer rotates a preview
    });
});

preview.addListener('load', (data) => {
    const viewer = data.viewer;
    viewer.addListener('rotate', () => {
        // Do something when a viewer rotates a preview
    });
});

preview.addListener('viewerevent', (data) => {
    if (data.viewerName === 'Image') {
        if (data.event === 'rotate') {
            // Do something when an image preview is rotated
        }
    } else if (data.viewerName === 'Image360') {
        if (data.event === 'rotate') {
            // Do something different when a 360-degree image is rotated
        }
    } else {}
});

preview.addListener('rotate', (data) => {
    if (data.viewerName === 'Image') {
        // Do something when an image preview is rotated
    } else if (data.viewerName === 'Image360') {
        // Do something different when a 360-degree image is rotated
    } else {}
});

Scopes

If your application requires the end user to only be able to access a subset of the Content Preview functionality, you can use Token Exchange to appropriately downscope your App/Managed or Service Account token to a resulting token that has the desired set of permissions, and can thus, be securely passed to the end user client initializing Preview.

Below are a set of new UI Element-specific scopes to go alongside Token Exchange. These allow developers to enable/disable UI controls on the Content Preview by configuring the appropriate scopes on the downscoped token. To learn more, see Special Scopes for Box UI Elements.

Wish to learn more about when, why and how you can use Token Exchange with the Content Preview? See our blueprint on Customizing Access for the Box UI Elements.

Base Scope

Scope Name
What permissions does it grant?

base_preview

Allows the user to preview the file, nothing else

Feature Scopes

Scope Name
What permissions does it grant?

item_download

Allows downloading/printing the content from the generated preview

annotation_edit

Allow user to edit annotations (delete).

Note: For highlight annotations to work, the text layer on the document needs to be enabled for the user. Text layer is disabled for all users that don't have download permissions on the file.

To enable highlight annotations for a user, please ensure they have download permissions on the file.

annotation_view_all

Allows user to view all users' annotations.

annotation_view_self

Allows user to view their own annotations only.

How to enable highlight annotations with scopes

The highlight annotation is not included with annotation_edit and annotation_view_all scopes. The downscoped access token will need to include the item_download scope to enable highlighting.

Sample Scenarios

Scenario
Scope Combinations

User should only be able to preview (not download/print, annotate)

base_preview

User should be able to preview, download and print

base_preview
+ item_download

User should be able to preview and view all annotations (not download, print or create annotations)

base_preview
+ annotation_view_all

User should be able to preview, and create annotations but only view their own.

base_preview
+ annotation_view_self
+ annotation_edit

User should be able to preview,
edit annotations and view all annotations

base_preview
+ annotation_view_all
+ annotation_edit

User should be able to preview and only view their own annotations but not add/delete (ex: after review period has expired, all documents need to be stored in read only mode)v

base_preview
+ annotation_view_self

Questions

If you have any questions, please visit our developer forum or contact us via one of our available support channels.

Please file any bugs you encounter with clear steps to reproduce at https://github.com/box/box-content-preview/issues.

Box Content Preview

JavaScript library for rendering files stored on Box