Smart Code Runtime

Documents / Developer

This page explains what happens after a customer site loads CROForge’s script. Runtime means “while the page is actually running in the visitor’s browser”—not the screens in the CROForge app. Smart Code decides whether this page and this visitor qualify, which variation they see, applies CSS/JS, and sends events.

The reference implementation is static/init.js, an IIFE that assigns window._CROFORGE. Doc ID: dev.smartcode. Audience: developer.

Words used on this page

WordEveryday meaningMeaning in CROForge
Smart CodeThe small script pasted on a website.Workspace init.js. Targeting, assignment, CSS/JS apply, event capture, integrations. Sample: static/init.js.
SnippetA copy-paste install tag.The HTML/JS that loads Smart Code on the customer site.
IIFEImmediately Invoked Function Expression: a function that runs the moment it is defined, so its variables stay private.How init.js wraps itself, then assigns window._CROFORGE.
init“Start up.” The first function that turns the lights on.init() after domain check. Chooses Editor, Preview, or Live mode (or no-op if already started/finished).
Live modeThe real show for real visitors.execLiveMode + bindGenericEventHandler: URL/segment targeting, sticky assignment, inject CSS/JS, send impressions, fire triggers.
Preview modeA dress rehearsal: you force a look without full live traffic rules.loadPreviewMode. Storage: _croforge_view_mode / preview token.
Editor modeThe workshop inside CROForge where you edit a variation on the page.execEditorMode when editorContext is set (must exist).
Sticky assignmentRemembering which team jersey you got so you keep wearing the same one.Variation id stored as _croforge_exp_{id} so the visitor sees the same variant next time.
Domain allowlistA guest list of allowed websites.CODE.domains vs location.hostname. If the host is not listed, Smart Code does not run.
Attribute helperA small function that looks up a fact about the visitor (device, browser, …).CROFORGE_ATTRIBUTES: device, browser, OS, UTMs (persisted), referral, visitorType, etc. Used by segment evaluation.
IntegrationA pipe to another system so it hears about the same event.Default push targets: CROForge /e, GA4 gtag, GTM dataLayer. This frontend has no GA4/GTM settings UI.
gtagGoogle’s function for sending analytics events.Sample runtime may call gtag("event", "croforge_" + name, payload).
dataLayerGoogle Tag Manager’s inbox: an array you push objects into.Sample runtime may dataLayer.push({ event: "croforge_" + name, ... }). Boot also stubs dataLayer / gtag if missing.
sendBeaconA browser API that sends a tiny package even as the page is closing.Preferred way to POST to the CROForge beacon URL (/e); Image pixel is the fallback.
CookieA small note the browser stores and often sends with later requests.Used for sticky visitor/assignment when useLocalStorage is false.
localStorageA larger notebook in the browser that lasts until the user clears it; not sent on every request.Preferred when useLocalStorage is true (visitor UUID, experiment assignment).
sessionStorageA notepad that is thrown away when the tab closes._croforge_session_uuid lives here.
Visitor UUIDA unique nametag for “this browser” across visits.Storage key _croforge_visitor_uuid.
Session UUIDA unique nametag for “this visit until the tab ends.”Storage key _croforge_session_uuid (sessionStorage).
ImpressionProof that someone was shown something.Event fired after a variation is assigned and CSS/JS applied in live mode.
BeaconA signal sent home without waiting around.Event POST to /e; errors POST to /ee via _croforge_err.

Screenshot filename

Suggested screenshot filename: smartcode-flow.png. Capture a flow of boot → domain check → init() → Live / Preview / Editor. Insert the real image from the WordPress Media Library in place of this note.

Integrations note

This frontend does not provide a GA4/GTM settings UI. Sample Smart Code (static/init.js) may still push to gtag / dataLayer as runtime integrations—treat that as site-runtime behavior, not an app configuration screen.

Boot sequence

Boot means the ordered startup steps before experiments run. If a step fails (especially the domain allowlist), later steps do not apply variations.

  1. Ensure dataLayer / gtag stub exists.
  2. Define CODE payload (domains, experiments, attributes, metrics, segments, triggers, events, integrations).
  3. Define attribute helpers + CROFORGE API.
  4. Validate location.hostname against CODE.domains.
  5. window._CROFORGE = window._CROFORGE || CROFORGE then init().

init() modes

init() is a traffic cop: it picks one path and returns. “Already started/finished” means do nothing (no-op) so the script is safe if it runs twice.

ConditionPath
Already started/finishedno-op
editorContext setexecEditorMode (must exist)
Preview modeloadPreviewMode
ElseexecLiveMode + bindGenericEventHandler

Live mode

Live mode is what real visitors hit. Experiments in CODE.experiments are processed one by one.

  1. Fire page_view-style events for matching triggers.
  2. For each experiment in CODE.experiments: getVariation(experiment), then inject CSS, run JS, send impression.
  3. Mark finished = true.

getVariation(experiment)

getVariation answers “which experience does this visitor get, if any?” URL targeting and segment must pass before traffic sampling. Sticky storage wins over a new random roll.

  1. URL targeting via getUrlTargetingMatchisUrlMatchCondition.
  2. Segment via getSegmentMatch.
  3. Read sticky variation id (_croforge_exp_{id}).
  4. If missing/invalid, sample using startTrafficPercent / endTrafficPercent.
  5. Persist assignment; expose summary on window._CROFORGE.experiments.

Implementation note: storage keys for assignment must stay consistent between getLiveVariationIdByExperimentId / setLiveVariationIdByExperimentId and any write sites in getVariation.

URL rule format (compact)

Rules ship in a compact array so the compiled bundle stays small. Each row is [matchType, urlPattern, isExclude]. See URL rules in the conditions docs for match-type numbers.

// [matchType, urlPattern, isExclude]
[[0, "https://example.com", false], [0, "https://example.com/blog", true]]

Attributes

CROFORGE_ATTRIBUTES resolves device, browser, OS, UTMs (persisted), referral, visitorType, and similar facts. Segment evaluation uses these helpers rather than re-detecting the environment on every condition.

Storage

Keys must stay exactly as listed so assignment and identity survive reloads. The useLocalStorage flag prefers localStorage over cookies when true.

Key patternPurpose
_croforge_visitor_uuidSticky visitor
_croforge_session_uuidSession (sessionStorage)
_croforge_exp_{id}Sticky variation
_croforge_view_mode / preview tokenPreview

Integrations

Default push targets (in addition to CROForge’s own ingest):

  1. CROForge beacon URL (/e) via sendBeacon or Image pixel
  2. GA4 gtag("event", "croforge_" + name, payload)
  3. GTM dataLayer.push({ event: "croforge_" + name, ... })

Error reporting

_croforge_err posts to /ee with stack + environment metadata so maintainers can see runtime failures without relying on the host page’s console.

Performance notes for maintainers

  • Pre-index triggers/events by type/id instead of nested scans on every click.
  • Cache attribute values per page.
  • Prefer body beacons over huge query strings.
  • Avoid recursive sendDebugLogs on failure.

Related reading