Trimble Connect Workspace API
The Trimble Connect Workspace API facilitates interaction between client applications and the Trimble Connect Web application, including the 3D Viewer. It primarily uses `window.postMessage()` for secure communication, allowing for two main integration patterns: embedding Trimble Connect Web Modules or the 3D Viewer within an `iframe` in a client application, or embedding the client application itself as an extension within Trimble Connect Web or the 3D Viewer. This library, currently at version 0.3.34, is actively maintained, with release notes and updates frequently published by Trimble. Its key differentiator is providing a standardized, type-safe interface for programmatic control and data exchange within the Trimble Connect ecosystem, abstracting the complexities of cross-origin `postMessage` communication.
Common errors
-
TypeError: Cannot read properties of undefined (reading 'getProject')
cause The `WorkspaceAPI.connect` method likely failed to return a valid API instance, or the promise from `connect` was not awaited, resulting in `api` being undefined or null when attempting to access its properties (e.g., `api.project`). This can happen if the connection times out or fails to establish.fixEnsure `await WorkspaceAPI.connect(...)` is used within an `async` function. Check the console for connection errors or timeouts. Verify the target window (`window.parent` for extensions, `iframe.contentWindow` for embedded viewers) is accessible and ready, and that the Trimble Connect application is loaded and listening. Increase the timeout if necessary. -
Uncaught DOMException: Blocked a frame from accessing a cross-origin frame.
cause This browser security error occurs when JavaScript attempts to access properties of an `<iframe>`'s `contentWindow` or `contentDocument` that is hosted on a different origin, and the parent frame's origin is not permitted by the `iframe`'s `Access-Control-Allow-Origin` headers, or vice-versa. This specifically impacts direct DOM access, not necessarily `postMessage` itself if handled correctly.fixEnsure that the Trimble Connect Workspace API is initialized correctly via `WorkspaceAPI.connect()` with the appropriate target window, as it handles the cross-origin `postMessage` communication securely. Avoid direct JavaScript access to `iframe.contentWindow` properties (e.g., `iframe.contentWindow.document`) if the origins differ. Verify that if you are embedding a Trimble Connect component, the `iframe` itself is correctly configured and the host application is properly allowing cross-origin communication as per Trimble's guidelines. -
API Error: Manifest file URL is not CORS enabled.
cause When registering an extension in Trimble Connect, the platform attempts to fetch the extension's `manifest.json` file. If the server hosting this manifest does not include the necessary `Access-Control-Allow-Origin` HTTP headers, the browser will block the request, preventing the extension from being loaded.fixConfigure your web server to include `Access-Control-Allow-Origin` headers for your `manifest.json` file. For development, `Access-Control-Allow-Origin: *` can be used. For production, specify `web.connect.trimble.com` (and other relevant Trimble Connect domains) as the allowed origin.
Warnings
- breaking The `trimble-connect-project-workspace-api` package was deprecated. All integrations were required to migrate to `trimble-connect-workspace-api` by the end of Q1 2023. Older APIs ceased to function after this deadline.
- gotcha When developing Trimble Connect extensions or embedding components, the URL hosting the extension's manifest file (e.g., `manifest.json`) must be CORS-enabled to allow access from Trimble Connect for Browser. Failure to set proper CORS headers will prevent the extension from being created or loaded.
- gotcha The API relies on `window.postMessage()` for communication. While the library handles much of the complexity, developers must understand the security implications, especially related to `targetOrigin`. Though the library abstracts it, ensuring messages are only sent to and received from trusted origins is crucial for security. Improper configuration or direct `postMessage` usage can lead to cross-site scripting (XSS) or data leakage vulnerabilities.
- breaking The domain for the Trimble Connect Web 3D Viewer changed from `3d.connect.trimble.com` to `web.connect.trimble.com`. Bookmarked 3D Viewer URLs might require updating.
Install
-
npm install trimble-connect-workspace-api -
yarn add trimble-connect-workspace-api -
pnpm add trimble-connect-workspace-api
Imports
- connect
import { connect } from 'trimble-connect-workspace-api';import * as WorkspaceAPI from 'trimble-connect-workspace-api'; const api = await WorkspaceAPI.connect(window.parent);
- WorkspaceAPI
import { WorkspaceAPI } from 'trimble-connect-workspace-api'; - ExtensionAPI
import { ExtensionAPI } from 'trimble-connect-workspace-api';
Quickstart
import * as WorkspaceAPI from 'trimble-connect-workspace-api';
interface ProjectInfo {
projectId: string;
projectName: string;
}
// This example assumes the client application is embedded as an extension
// within the Trimble Connect environment, communicating with its parent window.
// If embedding the Trimble Connect Viewer/Modules, `window.parent` would be replaced
// with the `contentWindow` of the iframe.
async function initializeTrimbleConnectExtension() {
try {
console.log('Attempting to connect to Trimble Connect Workspace API...');
const api = await WorkspaceAPI.connect(
window.parent, // Target origin is handled internally; window.parent is typically used for extensions
(eventName: string, data: any) => {
console.log(`Received event: ${eventName}`, data);
// Handle various events from the Trimble Connect environment
if (eventName === 'extension.accessToken') {
console.log('Access token received:', data.data); // data.data contains the actual token
}
},
30000 // Connection timeout in milliseconds
);
console.log('Successfully connected to Workspace API.');
// Example: Get current project information
const project: ProjectInfo = await api.project.getProject();
console.log('Current project:', project.projectName, `(ID: ${project.projectId})`);
// Example: Set a status message in the Trimble Connect UI
api.extension.setStatusMessage(`Extension loaded for project: ${project.projectName}`);
// Example: Update the UI menu (assuming this is an extension)
api.ui.setMenu({
id: 'my-extension-menu',
title: 'My Custom Extension',
icon: 'https://example.com/menu-icon.png',
command: 'open-my-extension',
children: [
{ id: 'sub-menu-1', title: 'Action 1', command: 'action-1-clicked' },
{ id: 'sub-menu-2', title: 'Action 2', command: 'action-2-clicked' }
]
});
} catch (error) {
console.error('Failed to connect or use Workspace API:', error);
if (error instanceof Error && error.message.includes('timeout')) {
console.error('Connection timed out. Ensure the host application is ready and accessible.');
}
}
}
initializeTrimbleConnectExtension();