Skip to main content

Scoped scripts

There are two places your SDK code can live. The Quickstart covers the first: one module script on the experience, which imports the SDK, calls connect(), and looks components up by locator. This page covers the second: a scoped script, written on a single element and running with that element already handed to you.

Use a scoped script when the behaviour belongs to one thing — a card that counts its own clicks, a button that toggles its own state. Use an experience-level script when the logic spans components, or has to coordinate them.

Rolling out

The SDK Script section is being released gradually. If you don't see it in the inspector, ask your Ceros contact.

Writing one

Select an element in Flex and open SDK Script in the inspector. Press +, type your code, and use the expand control for a full-size editor.

let clicks = Number(this.getData('clicks') ?? 0)

this.on('component.click', () => {
this.setData('clicks', String(++clicks))
this.setAttribute('opacity', clicks % 2 ? '50' : '100')
})

There is no import and no connect(). this is the Component for the element the script is written on — everything on that page applies, including this.experience for the experience-wide handle, this.on(...) for events, and the capabilities for its type. Locators (findByLocator, findByTag) search the element's own subtree, so on an element with no children they find nothing; reach for this.experience when you need to look further.

await works at the top level of your script.

What to expect at runtime

  • One script per element, running once, as soon as the experience is ready — the same moment connect() would resolve. On a page navigation, elements mounted fresh run their scripts; elements that survived the navigation don't run again.
  • Published experiences and the preview only. Nothing runs while you're editing on the canvas, so a script can't disturb your design work. Use Preview to try it before publishing.
  • A failure stays on its element. If a script throws, that element's script stops, everything else on the page carries on, and the browser console gets one message naming the element. Your viewers see nothing.

Limits

Your code is compiled as a module, which sets three rules:

  1. No import declarations. Write const x = await import('https://…') instead — a top-of-file import … from … is a syntax error.
  2. Imports must be absolute URLs. A relative path (./helper.js) has nothing to resolve against. You rarely need an import at all: this is already the SDK.
  3. On your own site, your CSP must allow blob: in script-src. Without it the browser blocks every scoped script on the page. Ceros-hosted pages are fine as they are.

One more, if you embed with Flex SSR: the embed must carry the data-flex-manifest-url attribute, or your scripts have no way to reach the page. The WordPress plugin and AEM connector already emit it; a hand-rolled integration should follow the SSR recipe.