Skip to main content

Macro example: Add labels

This macro keeps a set of labels on a page. Each time someone opens the page, it adds the labels from its macro body that the page lacks. If someone removes one by mistake, it comes back.

Applies to: Script Master for Confluence Β· Cloud. It's based on the editor's Add labels template, and only reports labels that Confluence really added.

How it works​

  • You list the labels in the Macro Body, separated by commas, for example policy, reviewed.
  • The macro sets its own height to 0px, so it takes no room on the page.
  • The macro adds labels as the person viewing the page. If that person can't add labels, nothing happens. The label comes back the next time someone who can opens the page.
  • When it adds labels, the viewer sees a flag that lists them.

Set it up​

  1. Create a macro and paste the code below into HTML Content.
  2. Turn on Enable and select Save.
  3. On a page, add the macro and type the labels in Macro Body.

Result: When someone opens the page, the macro adds any missing label from your list.

The live preview never passes a macro body. There, the macro adds nothing and logs "No labels in the Macro Body: nothing to add." Test it on a page you can change.

The code​

<script type="module">
setHeight('0px'); // Take no room on the page

// The labels to keep on the page, from the Macro Body. A macro with no body yet
// (and the live preview, which has none) has nothing to add.
const context = await view.getContext();
const requiredLabels = (context.extension.config?.macroBody ?? '')
.split(',').map(labelName => labelName.trim()).filter(Boolean);
if (!requiredLabels.length) {
console.log('No labels in the Macro Body: nothing to add.');
}

// Get the page's current labels
const response = await requestConfluence(`/wiki/api/v2/pages/${context.extension.content.id}/labels?limit=250`, {
headers: { 'Accept': 'application/json' }
});
const labelsData = await response.json();

// Find the labels that are missing
const labelsToBeAdded = requiredLabels.filter(requiredLabel =>
!labelsData.results.some(pageLabel => pageLabel.name === requiredLabel));

// Add them
const labelsAddedSuccessfully = [];
for (const labelToAdd of labelsToBeAdded) {
// A viewer who can't add labels gets an error status: skip the label quietly
const addResponse = await requestConfluence(`/wiki/rest/api/content/${context.extension.content.id}/label`, {
method: 'POST',
headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
body: JSON.stringify([{ prefix: 'global', name: labelToAdd }]),
});
if (addResponse.ok) labelsAddedSuccessfully.push(labelToAdd);
else console.warn(`Couldn't add "${labelToAdd}": ${addResponse.status}`);
}

// Show a flag when labels were added
if (labelsAddedSuccessfully.length) showFlag({
id: 'success-flag',
title: 'These labels were added to the page: ' + labelsAddedSuccessfully.join(', '),
type: 'success',
isAutoDismiss: true,
});
</script>