The chat responses are generated using Generative AI technology for intuitive search and may not be entirely accurate. They are not intended as professional advice. For full details, including our use rights, privacy practices and potential export control restrictions, please refer to our Generative AI Service Privacy Information. As this is a test version, please let us know if something irritating comes up. Like you get recommended a chocolate fudge ice cream instead of an energy managing application. If that occurs, please use the feedback button in our contact form!
Skip to content

Read the context

2612

fetchContext() is the first call every view makes. This guide shows the patterns that work well and the mistakes that are easy to make.

Plain JavaScript

import { fetchContext, destroy } from 'polarion-app-sdk';

async function start() {
  try {
    const context = await fetchContext();
    render(context);
  } catch (error) {
    showError('This page must be opened inside Polarion.', error);
  }
}

window.addEventListener('beforeunload', () => destroy());
start();

React

Fetch once on mount, keep the result in state, and release the bridge on unmount:

import { useEffect, useState } from 'react';
import { destroy, fetchContext, type PolarionContext } from 'polarion-app-sdk';

export function usePolarionContext() {
  const [context, setContext] = useState<PolarionContext | null>(null);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    let cancelled = false;
    fetchContext()
      .then((ctx) => {
        if (!cancelled) setContext(ctx);
      })
      .catch((e: unknown) => {
        if (!cancelled) setError(e instanceof Error ? e : new Error(String(e)));
      });
    return () => {
      // Ignore pending results before destroy() cancels requests, including during Strict Mode cleanup.
      cancelled = true;
      destroy();
    };
  }, []);

  return { context, error };
}
export default function App() {
  const { context, error } = usePolarionContext();
  if (error) return <p>Cannot reach Polarion: {error.message}</p>;
  if (!context) return <p>Loading…</p>;
  return <p>Work item {context.workItemId} in {context.projectId}</p>;
}

In React 18/19 development mode with StrictMode, effects run twice: the first run's fetchContext() is canceled by the cleanup's destroy() and rejects, then the second run creates a fresh instance and succeeds. The cancelled flag set in the cleanup makes the hook ignore everything the first run returns, the rejection included, without depending on the wording of the error. Production builds do not double-invoke effects.

Handling the failure case

fetchContext() rejects after five seconds when no host answers. That happens when:

  • the page is opened directly by its URL, outside Polarion;
  • the page runs on the Vite dev server;
  • the Polarion host page failed to initialize the bridge (rare; reload the Polarion page).

Show a clear message rather than a spinner. Users and administrators who open the view URL to check a deployment should see "this view only works inside Polarion", not a hang.

Deriving identifiers

const { projectId, workItemId, spaceId, documentId } = context;

// REST URL for the open work item
const workItemUrl = `${context.restBaseUrl}/projects/${projectId}/workitems/${workItemId}`;

// Combined id used by server scripts in this guide and as JSON:API resource id
const fullId = `${projectId}/${workItemId}`;

// REST URL for the open document (sidebar in a Document)
const documentUrl = `${context.restBaseUrl}/projects/${projectId}/spaces/${spaceId}/documents/${documentId}`;

// Polarion UI link to a work item, for <a target="_top">
const uiLink = `${window.location.origin}/polarion/#/project/${projectId}/workitem?id=${workItemId}`;

All of these are optional in the type. Guard them according to the view type:

if (!context.workItemId) {
  throw new Error('This view must be placed on a work item form.');
}

Refreshing

The context is a snapshot and does not change while the view is open. Call fetchContext() again when you need a fresh token (after a 401). Reading it again does not give a sidebar the current selection: selectedWorkItemIds stays empty there, and the selection arrives only through selection-changed events. Each call is a round trip to the host page and resolves in a few milliseconds.

Logging

During development it helps to print the context once:

console.log('[myapp] context', context);

Remove or guard such logs before release; the context contains the REST token.

Next