Introduction

Foxit Web Collaboration Add-on focuses on helping developers easily integrate real-time document collaboration into their web applications which are built based on Foxit PDF SDK for Web. It mainly contains two modules, the client and the server.

This guide will introduce the following section:

  • Getting Started: introduces the system requirements, package structure and how to quickly run the collaboration demo.

  • Web Collab-Server: illustrates the collaboration server component, including database, authentication, cluster, as well as message and notification.

  • Web Collab-Client: illustrates the collaboration client component, including installation, integration, how to create/begin/end/quit collaboration, how to get collaboration members, and how to get and update collaboration permission.

Getting Started

System Requirements

  • Node.js 16 LTS or higher
  • Postgres 9.x or higher
  • If you use Redis, please make sure the version should be 4.0 or higher.

Compatibility Requirements

Collaboration Add-on requires a compatible version of the Foxit PDF SDK for Web.

Here is the compatibility chart.

Collaboration Add-on Foxit PDF SDK for Web
1.3.0 9.2.0
1.2.0 9.1.0
1.1.0 9.0.0
1.0.0 8.5.2

Project Structures

There are two ways to get Foxit Web Collaboration Add-on.

The package contains the following folder structure:

docs                  -- API reference and developer guide
packages
  web-collab-client   -- collaboration client module
  web-collab-server   -- collaboration server module
  collab-db           -- collaboration db setup and migration
samples
  collabClientSample/ -- collaboration client demo component
  collabServerSample/ -- collaboration server demo component

Quickly Run Demo

Foxit Web Collaboration Add-on comes with a demo project for building the real-time document collaboration functionality.

To run the demo, please follows the steps as below:

  1. Install Nodejs, prefered version: nodejs 16 lts or higher. If you already have a Nodejs installed, please skip this step.

  2. Install Postgres, prefered version: 9.x or higher. If you already have a postgres database running or installed Docker, you can skip this step.

  3. To start a command prompt as an administrator, navigate to the project root, and run the command : npm install.

  4. If you are using Docker, you should set up a database with Docker.

    In the project root, install database: (The default port of the database is 5432)

    npm run collab-cli setup-local-db

  5. Run the demo.

    In the project root, start samples/collabClientSample:

    npm run start:sample-client

    In the project root, start samples/collabServerSample:

    npm run start:sample-server

After starting the collabClientSample and collabServerSample successfully, open http://localhost:3000/ on your browser, then you can see the demo entry.

Web Collaboration Server

Overview

Web Collaboration Server is available as a NPM package: @foxitsoftware/web-collab-server. You also can get it from the Collaboration Add-on Package.

Web Collaboration Server supports two modes: Simple Mode and Cluster Mode.

In simple mode, collaboration server runs on a single-instance basis, with only one collaboration server instance. The configuration is easy in this mode, you just need to configure UserService and Database.

In cluster mode, multiple collaboration servers can be started to form a cluster to handle users requests together. For more information about cluster mode, please refer to Cluster.

Simple Mode

Before running collaboration server, you need to set up the database and user service.

Set up Database

Please refer to Database to set up the database.

Set up User Service

Please refer to Authentication to set up user service, such as user authentication and user information acquisition.

Start a Collaboration Server

Install collaboration server using NPM:

npm install @foxitsoftware/web-collab-server

Create a collaboration server referring to the following code:

import {WebCollabServer, UserService} from "@foxitsoftware/web-collab-server";

// UserService should be implemented by user App
const userService: UserService = {
  getUserByToken(token) {
    // validate token and get uesr info from user system of client APP
  }
}

const databaseConfig = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  database: 'collab-db',
  user: 'foxit',
  password: '123456',
}

const server = new WebCollabServer({
  databaseConfig,
  userService,
});

server.start(8080)

Cluster Mode

To enable the clustering, provide the cluster option when creating WebCollabServer. Only serverId is required if you want to use the default implementation.

MessageQueue and MemberStateService can be implemented if you want more customization.

Notice:

The ‘serverId’ of the server instance in the same cluster should be unique. Refer to serverId for more information.

const messageQueue = new CustomMessageQueue()
const memberStateService = new CustomMemberStateService()

const server = new WebCollabServer({
  databaseConfig,
  userService,
  cluster: {
    serverId: '1',
    messageQueue, // only required if you want to use your customized MessageQueue
    memberStateService // only required if you want to use your customized MemberStateService
  }
});

Authentication

Foxit Web Collaboration Add-on does not store user-related information and the authentication service should be provided.

When integrating, on the collaboration server side, you need to implement the UserService interface. Collaboration server will call this method to authenticate and obtain the user information.

Token based authentication

In the current market, the token based authentication is used by most applications. Using the user authentication extension interfaces provided by Foxit Web Collaboration Add-on, you can easily integrate user authentication, such as OIDC, OAUTH2, etc.

In the following example, implement a custom UserSerivce, and then call a REST API to do token validation.

import axios from "axios";
import type {UserService, UserInfo} from "@foxitsoftware/web-collab-server";

/**
 * A Custom UserService to do authentication.
 */
export const userService: UserService = {
  async getUserByToken(token: string) {
    const result = await axios.request({
      url: `https://your-user-authentication-service/api/user`,
      method: 'get',
      params: {
        token
      }
    })
    return result.data as UserInfo
  }
}

const server = new WebCollabServer({
  userService,
  // other options
});

Permission

Permission is a feature of the collaboration server that controls how users can do with the collaboration. The collaboration server provides two ways to control the permission: default permission check and custom permission check.

Default permission check

The default permission check is enabled by default and follows these rules:

  • All users are allowed to create a new collaboration.
  • The collaboration creator becomes the owner and has all permissions.
  • The collaboration can be set to public or non-public by the owner.
  • If the collaboration is public, all users can join the collaboration.
  • if the collaboration is non-public, only the owner and invited users can join the collaboration.
  • The owner can invite users to join the collaboration.
  • The user who joins the collaboration becomes a member of the collaboration.
  • The owner can grant read-only or comment permission to members within the collaboration.

Custom permission check

You can override the default permission check with a custom permission check. To do this, implement the UserService.checkUserPermission interface to provide your own custom permission check.

For example:

export const userService: UserService = {
  // other interfaces omitted
  
  checkUserPermission(user, resourceType, operation, resourceId) {
    // check if the user has permission to perform the operation on the resource
    // return true if the user has permission
    // return false if the user does not have permission
    // returning null will revert to default permission check
    return null;
  }
}

const server = new WebCollabServer({
  userService,
  // other options omitted
});

The currently supported resourceType and operation are: (denoted as resourceType/operation)

  • collaboration/join: Check if the user has permission to join a collaboration. This is triggered when a user is trying to join a collaboration.
  • collaboration/comment: Check if the user has permission to comment on a PDF. This is triggered when a user is joining a collaboration, to check if the user can comment on a PDF within the collaboration.
  • collaboration/create: Check if the user has permission to create a collaboration. This is triggered when a user is trying to create a collaboration.
  • collaboration/delete: Check if the user has permission to delete a collaboration. This is triggered when a user is trying to delete a collaboration.
  • collaboration/update: Check if the user has permission to update a collaboration. This is triggered when a user is trying to update a collaboration, such as changing the default permission of the collaboration.

For example:

When a user is trying to join a collaboration, the default permission check is activated if there is no custom permission check in place. However, if a custom permission check is provided, the checkUserPermission function will be called to check if the user has permission to join. The parameters of checkUserPermission would be as follows: checkUserPermission(user, 'collaboration', 'join', collaborationId).

Database

Web Collaboration Server uses relational databases for persistence. Database-related code is provided in a standalone package: @foxitsoftware/collab-db. You can get it from the zip release file or NPM.

A simple CLI tool is provided in this package to help users quickly initialize the database.

Set up a Database for Collaboration Server

Before running collaboration server, you should set up and initialize database first.

Set up a Database Management System (DBMS)

If you already have an available DBMS, you can skip this section and start creating a Database for Collaboration Server.

You can manually install the required DBMS or use the database services provided by the cloud service provider directly.

In addition, if you already have installed Docker or Podman , you can use our CLI tool to quickly install a Postgres with Docker/Podman.

The following command will use Docker to run a Postgres in container with default port 5432.

npm run collab-cli setup-local-db -- --port 5432 --user postgres --password 123456 

In fact, the above command is equivalent to the following shell command:

docker run -d --name collab-db \
-e POSTGRES_PASSWORD=123456 \
-p 5432:5432 \
-v $HOME/foxit-collabsdk/database:/var/lib/postgresql/data \
postgres:14.3-alpine3.16

The following options are provided for setup-local-db:

Option Required Description Default
-r, --runtime <runtime> false container runtime to use: docker or podman docker
-n, --name <name> false name of container collab-db
-d, --dir <dir> false dir for database data ~/foxit-collabsdk/database
-u, --user <user> false username of database postgres
-p, --port <number> false exposed port of database 5432
-P, --password <password> false password of database 123456

For more information: npm run collab-cli help setup-local-db.

Create a Database for Collaboration Server

If your are using the setup-local-db command to set up a Database, you can skip this section and start Initialize Collaboration Server With the Database Configuration.

If you already have a running Database System, for example MySQL or Postgres, a command is provided by the CLI tool to help you do Database Migration.

You can run migration directly with the following command:

`npm run collab-cli init-db -- --type <DBMS_TYPE> --name collab-db --user <YOUR_DB_USER> --password <YOUR_DB_PASSWORD> --port <YOUR_DB_PORT>`

The <DBMS_TYPE> can be mysql or postgresql.

We are using prisma to do database migration, so you can also use prisma cli directly:

export DATABASE_URL=<DBMS_TYPE>://<YOUR_DB_USER>:<YOUR_DB_PASSWORD>@<YOUR_DB_HOST>:<YOUR_DB_PORT>/<DB_NAME>
npx prisma migrate dev --name init

The following options are provided for init-db:

Option Required Description Default
-t, --type <database type> false type of database postgresql
-h, --host <host> false host of database localhost
-p, --port <number> false exposed port of database 5432
-n, --name <db-name> false name of database collab-db
-u, --user <user> false username of database postgres
-P, --password <password> false password of database 123456

For more information: npm run collab-cli help init-db.

Initialize Collaboration Server With the Database Configuration

Next, you can use the above configuration data for database to start the collaboration service. For example:

const databaseConfig = {
  type: 'postgres',
  host: 'localhost',
  port: 5432,
  database: 'collab-db',
  user: 'foxit',
  password: '123456',
}

const server = new WebCollabServer({
  databaseConfig,
  // ... other options
});

Database logging configuration

The database logging configuration is provided by the log option. If not provided, the database logging is disabled. If you want to enable database logging, you can set a value that conforms to the LoggerOptions interface. For example, { log: ['query', 'info', 'warn', 'error'] } will output query, info, warn and error logs to stdout. You can refer to the API reference for more information.

PDF file uploading

Web Collaboration Server does not store PDF files, so applications need to implement PDF file storage service and share the files by URL. Make sure that PDFViewer can open the PDF file through the URL.

The advantages are: - Better security/privacy protection - More flexible file storage mechanism

When creating a Collaboration, users need to provide the URL of the PDF file. Collaboration server will associate this URL with the current Collaboration, and stores it in the database.

When creating a collaboration, the collaboration server only store the URL of the files.

Messaging and Notification

Internally, all collaboration-related operations are wrapped as Message and sent to MessageQueue. For more information, please refer to the API Reference of Foxit Web Collaboration Add-on.

Message can be used for message notifications, custom log storage, and so on. The default format of Message is

{
  type: MessageType,
  payload: any,
  meta: MsgMetaData
}

An extension interface MessageHandler is provided for customized message processing. For example, you can transform the original message and return a customized message format.

{
  code: "CUSTOM_MSG_CODE",
  data: "CUSTOM_MSG_DATA"
}

Usage of Message Handler

The following example shows how to customize the MessageHandler.

import { WebCollabServer, MessageHandler, Message } from "@foxitsoftware/web-collab-server";
const messageHandler: MessageHandler = (msg: Message) => {
  console.log("received msg:", msg)
}

const server = new WebCollabServer({
  messageHandler
  // other options
})

Clustering

A cluster mode is provided by Web Collaboration Server. This mode supports horizontal scaling, so that it can support large-scale users.

In cluster mode, multiple Collaboration Servers can be started to form a cluster to handle users requests together.

Users can provide the core services required for the collaborative cluster mode by implementing the interfaces defined by collaboration server.

To support cluster, some additional configurations are required when creating collaboration server. For example:

const messageQueue = new CustomMessageQueue()
const memberStateService = new CustomMemberStateService()

const server = new WebCollabServer({
  // other options
  cluster: {
    serverId: '1',
    messageQueue, // only required if you want to use your customized MessageQueue
    memberStateService // only required if you want to use your customized MemberStateService
  }
});

Further descriptions of cluster parameters are as follows:

serverId

A serverId is required for each collaboration server instance. It can be any string but please make sure that it is unique in the same cluster.

MessageQueue

A message queue is used to exchange Message among different servers and components.

Message queue is a key component for the clustering of collaboration servers. All collaboration servers in the cluster communicate by exchanging messages via message queue.

A message queue can be implemented on top of RabbitMQ, Kafka, Redis, etc.

This config is optional. A default MessageQueue based on Redis is provided, and will be used if messageQueue is not provided in the cluster option. The Redis URL should be provided as an environment variable when starting the collaboration server, like REDIS_URL="redis://127.0.0.1:6379" .

MemberStateService

MemberStateService is used to store and retrieve member states. The currently supported member states are online/offline. For more information, please refer to the API Reference of Foxit Web Collaboration Add-on.

This config is optional. A default MemberStateService is provided and will be used if memberStateService is not provided in the cluster option.

Load Balancer

In the cluster mode, a Load Balancer is needed to distribute the requests to server instances in the cluster.

Typically, Load Balancer has different load balancing strategies, and the collaboration server has no restrictions on the strategies.

We recommend to use consistent hashing based on collaborationId, which can reduce the synchronization overhead of multiple Server instances.

Logging

Collab server uses pino and pino-http for logging. You can pass in logger options when creating the server to customize the logging behavior.

const server = new WebCollabServer({
  logger: {
    level: 'info',
    autoLogging: false,
  },
  // ... other options omitted for brevity
});

You can pass pino-http options to the logger option, and it will be passed to the underlying pino-http module. Please refer to API Reference for more information.

Web Collaboration Client

Getting Started

Installation

npm install @foxitsoftware/web-collab-client

Integration

This section will walk you through getting Web Collaboration Client module integrated into a web application based on Foxit PDF SDK for Web.

1)Import the collaboration client module and Foxit PDF SDK for Web.

import PDFViewer from ' @foxitsoftware/PDFViewerCtrl' 
import { WebCollabClient } from ' @foxitsoftware/web-collab-client'

2)Initialize PDFViewer. For more information, please refer to the Developer Guide of Foxit PDF SDK for Web.

var PDFViewer = PDFViewCtrl.PDFViewer;
var pdfViewer = new PDFViewer({
      libPath: './lib', // the library path of Web SDK.
      jr: {
            licenseSN: licenseSN,
          licenseKey: licenseKey,
      }
});
pdfViewer.init('#pdf-viewer'); // the div (id="pdf-viewer")

3)Create a new instance of the collaboration client:

import { WebCollabClient } from ' @foxitsoftware/web-collab-client'
const webCollabClient = new WebCollabClient({
  pdfViewer: pdfViewer,
  baseURL:`http://localhost:8080`,
  userProvider: () => {
    return {
      id: 'userId',
      username: 'userName',
      token: 'usertoken'
    }
  }
});
  • options.pdfViewer: The Web SDK basic webViewer instance
  • options.baseURL: The base URL of the collaboration server component
  • options.userProvider: The user service

For a full list of constructor options, please see the Web Collaboration Client API reference.

Now, you have finished the integration of collaboration client. Next, you can create and begin the collaboration.

Create Collaboration

Collaboration is created with the webCollabClient.createCollaboration API.

const collaboration = await webCollabClient.createCollaboration({
  fileUrl: 'https://foxit.com/downloads/pl/demo.pdf',
  isDocPublic: true,
  docName: 'demo.pdf'
})
  • options.fileUrl: The URL of PDF document.
  • options.docName: The name of the document.
  • options.isDocPublic?: Sets whether or not the document can be allowed to open by everyone. True means allowed; false means not allowed.

Creating collaboration will not automatically open the collaborative document, you need to call collaboration.begin() API to open it.

Begin Collaboration

Once you have an instance of the collaboration object, you can call collaboration.begin to open it in the viewer.

Calling the method below will begin your collaboration:

await collaboration.begin(fileOptions?:{password:string, [key: string]: any})
  • An optional fileOptions parameter can be passed in to specify options when opening a PDF file.
  • For example, in order to open an encrypted PDF file, fileOptions.password is needed.
await collaboration.begin().catch(e => {
  if(e.error === 3){
      const passwordForPDF = await promptForPassword()  
      await collaboration.begin({
        password: passwordForThePDF
      })
    }
})

Get Collaboration List

The getCollaborationList API will return a list of collaborations.

Example

import { WebCollabClient } from ' @foxitsoftware/web-collab-client'
const webCollabClient = new WebCollabClient(CollabOptions);
const collaborations = await webCollabClient.getCollaborationList();

Get Collaboration

The getCollaboration API gets a specific collaboration via the collaboration id collaborationId (string).

Example

import { WebCollabClient } from ' @foxitsoftware/web-collab-client'

const webCollabClient = new WebCollabClient(CollabOptions);

const collaboration = await webCollabClient.getCollaboration('collaborationId');

End Collaboration

You can stop collaboration with the collaboration.end API.

This action can only be executed by the creator of the collaboration, and others members do not have permissions.

Example

collaboration.end(): Promise<boolean>

Quit Collaboration

You can quit collaboration with the collaboration.quit API.

This action can only be executed by the collaborator. After quitting successfully, you can still re-enter the collaboration and start a new round of collaboration.

Example

collaboration.quit(): Promise<boolean>

Collaboration Events

On Collaboration Event

You can use on function to listen the related collaboration events.

Example

collaboration.on(event: 'onlineStatusChanged', listener: (actionData: Record<string, any>, action: 'online' | 'offline' | 'delete-share' | 'edit-members'|'screen-sync-created'|'screen-sync-stopped'|'screen-sync-member-joined'|'screen-sync-member-leave') => void)

Off Collaboration Event

You can use off function to unlisten the related collaboration events.

Example

collaboration.off(): Promise<boolean> 

Collaboration Members

Get current Member

You can get the current member with the collaboration.getCurrentUser API.

Example

collaboration.getCurrentUser(): Promise<Member> 

This function resolves to member of Member.

Get Online Members

You can get collaboration online members with the collaboration.getOnlineMembers API. This function can get all the online members information under the current collaboration.

Example

collaboration.getOnlineMembers(): Promise<Member[]> 

This function resolves to an array of Member.

Get Members

You can get collaboration members with the collaboration.getMembers API. This function can get all the collaboration members information under the current collaboration.

Example

collaboration.getMembers(): Promise<Member[]> 

This function resolves to an array of Member.

Add Members

You can invite members to a collaboration with the collaboration.addMembers API.

If the collaboration session is shared by others and is not public, you will not have the permission to invite members.

Example

  collaboration.addMembers(members): Promise<boolean>;
  • members is an array of emails or user IDs to invite.

Remove Members

You can remove collaboration members with the collaboration.removeMembers API. This function can remove specific members from the current collaboration.

Example

collaboration.removeMembers(members: Array<{ id: 'MemberId' }>): Promise<boolean>

This action can only be executed by the creator of the collaboration, and other members do not have permissions.

Collaboration Permission

Get Permission

You can get the collaboration permission with the collaboration.getPermission() API.

Example

await collaboration.getPermission(): Promise<Permission>

This function returns an instance of Permission.

Update Permission

You can update Collaboration permission with the collaboration.updatePermission() API.

collaboration.updatePermission(permissionOption:{ isDocPublic?: boolean,isAllowComment?:boolean }): Promise<boolean>

  • isDocPublic (boolean): Sets whether or not the document can be allowed to open by everyone. True means allowed; false means not allowed.

  • isAllowComment (boolean): Sets whether or not the document can be allowed to add comments. True means allowed; false means not allowed.

Modify the permissions for the current collaboration:

await collaboration.updatePermission({ isDocPublic?: boolean,isAllowComment?:boolean })

1:This action can only be executed by the creator of the collaboration, and other members do not have permissions.

2:This action only takes effect for the joined collaboration members after the permission changed.

3:If you want to set different permissions for different participants, you can also set them through the updateMemberPermission method.

Update Member Permission

You can update collaboration member permission with the collaboration.updateMemberPermission API.

Modify the isAllowComment permission of a collaboration member through the member id:

collaboration.updateMemberPermission(members): Promise<boolean>

1:This action can only be executed by the creator of the collaboration, and other members do not have permissions.

2:When permissions updated, collaborators will receive an update notification to get the latest permissions.

3:The isAllowComment permission of updateMemberPermission will override the isAllowComment permission of updatePermission.

Collaboration ScreenSync

The screenSync session can be created on top of the collaboration session and has one “leader” and multiple “followers”

Followers will follow leader’s screen scrolling,PDFPage zooming,and PDFPage view mode.

A collaboration can have multiple active screenSync sessions at once, however a user can only be leading one session at a time, and a user can only be connected to one session at a time.

Create screenSync

First, you need to start a collaboration. During the collaboration, you can create a screenSync session through the collaboration.createScreenSync API.

import { WebCollabClient } from '@foxitsoftware/web-collab-client';
 
const webCollabClient = new WebCollabClient(CollabOptions);
const collaboration = await webCollabClient.createCollaboration({
  fileUrl: 'https://foxit.com/downloads/pl/demo.pdf',
  isDocPublic: true,
  docName: 'demo.pdf'
})
 
await collaboration.begin()

const screenSync = await collaboration.createScreenSync(memberIds)
  • memberIds?: The list of member ids of the collaboration which will be invited to be followers of the screenSync session. By default, all members of the current collaboration will be invited to be followers of the screenSync session.

After the screenSync session is successfully created, wait for other members to join. When a member joins, you will become the leader of the screenSync session, and other members will follow you.

Get a screenSync session

When the screenSync session is successfully created, the ‘screen-sync-created’ event is fired for specified member or all members of the collaboration. You can get a screenSync session with the collaboration.getScreenSync API.

The getScreenSync API gets a specific screenSync via the screenSync id screenSyncId (string).

Example

const screenSync = await collaboration.getScreenSync('screenSyncId');

Get screenSync List

You can get the screenSync list with the collaboration.getScreenSyncList API.

Example

const screenSync = await collaboration.getScreenSyncList();

Join a screenSync session

A screenSync session can be joined by calling the screenSync.join API.

Once you have a screenSync session, join it by calling join().

const screenSync = await collaboration.getScreenSync('screenSyncId');
await screenSync.join()

When you join a screenSync session, you will be a follower of the screenSync. The session leader now controls the screen scrolling, zooming, and PDF layout mode.

Leave a screenSync session

You can leave a screenSync session at any time by calling the screenSync.leave API.

When you leave the current screenSync session, your view will no longer follow the leader’s view. If the leaving user is the leader of screenSync, the current screenSync session will be stopped.

const screenSync = await collaboration.getScreenSync('screenSyncId');
await screenSync.leave()

Get screenSync members

You can get screenSync members by the screenSync role with the screenSync.getMembers API. This function can get all the members information under the current screenSync session.

Example

const screenSync = await collaboration.getScreenSync('screenSyncId');
let leader=await screenSync.getMembers('leader')
let followers=await screenSync.getMembers('follower')
let screenSyncMembers=await screenSync.getMembers()

Collaboration Offline Support

Starting from version 1.1.0, Foxit Web Collaboration Add-on provides a new feature “Offline Support” which is enabled by default under the hood without any configuration. In a collaboration session, if some members go offline or have bad internet connection, they can still add/delete/update annotations to the PDF file. When they go back online, the editing operations made in offline state can be synchronized to the server and merged with the operations of other users. Conflicting edits from multiple members during the merging process can be automatically resolved with eventual consistency.

Integration

This section will introduce how to integrate the Foxit Web Collaboration Add-on into an existing web application which is built based on Foxit PDF SDK for Web 9.0.0.

In this guide, we will take the complete_webViewer demo(FoxitPDFSDKforWeb/examples/UIExtension/complete_webViewer) of Foxit PDF SDK for Web as an example to show you the critical steps of the integration.

Assumed that you already have a simple collaboration server. If you need to integrate the collaboration server with your own infrastructure, please refer to Web Collaboration Server Guide.

Install Dependencies

Navigate into the root directory of complete_webViewer demo by running

npm install @foxitsoftware/web-collab-client

Initialize a Web Collaboration Client

import { WebCollabClient } from ' @foxitsoftware/web-collab-client'

async function initWebCollabClient(){
  
  // Get pdfViewer from the existing web app.
  let pdfViewer = await pdfui.getPDFViewer();
  
  // Login with your own User Authentication service.   
  let userInfo = await login();
  
  const webCollabClient = new WebCollabClient({
    pdfViewer: pdfViewer,
    baseURL:`http://localhost:8080`, // This should be changed to the collaboration server base url.
    userProvider: () => {
      return {
        id: userInfo.id,
        username: userInfo.name,
        token: userInfo.token 
      }
    }
  });
  
  return webCollabClient
}

Initiator: Initiate a Collaboration and Begin the Collaboration session

async function initiateCollaboration(){
  const colloaboration = await webCollabClient.createCollaboration({
    // The URL of file to share.
    fileUrl: '/assets/FoxitPDFSDKforWeb.pdf', 
    isDocPublic: true,
    docName: "FoxitPDFSDKforWeb" 
  })
 
  // Begin the collaboration session. 
  await collaboration.begin()
 
  // Listen to online member state change event and refresh the online members list.
  collaboration.on("onlineStatusChanged",async function (){
     const onlineMembers = await colloaboration.getOnlineMembers()
    
     // You can show online members on the UI. For abbreviation, we just log to console here. 
     console.log(onlineMembers)
  })
 
  // Create a invitation which will expire in 2 hours (7200 * 1000 milliseconds)  
  const invitation = await webCollabClient.createInvitation(colloaboration.id, 7200 * 1000)
 
  // Then, you can send invitation to others who will join the collaboration by the invitation id. 
  sendInvitationByEmail(invitation)
  
}

Participant: Join a Collaboration


// The participant gets the invitation id by email or a shared link. 
const invitationId = getInvitationFromSomewhere()

async function joinCollaboration(){
  
   // Get the collaboration by initation id.  
  const collaboration =  await webCollabClient.joinCollaborationWithInvitation(invitationId) 
 
  // Start to collaborate with others.
  await collaboration.begin()
  
}

This guide is intended to show how to integrate the Foxit Web Collaboration Add-on into an existing web application. The code is not production grade.