Smart Code Runtime
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
| Word | Everyday meaning | Meaning in CROForge |
|---|---|---|
| Smart Code | The small script pasted on a website. | Workspace init.js. Targeting, assignment, CSS/JS apply, event capture, integrations. Sample: static/init.js. |
| Snippet | A copy-paste install tag. | The HTML/JS that loads Smart Code on the customer site. |
| IIFE | Immediately 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 mode | The real show for real visitors. | execLiveMode + bindGenericEventHandler: URL/segment targeting, sticky assignment, inject CSS/JS, send impressions, fire triggers. |
| Preview mode | A dress rehearsal: you force a look without full live traffic rules. | loadPreviewMode. Storage: _croforge_view_mode / preview token. |
| Editor mode | The workshop inside CROForge where you edit a variation on the page. | execEditorMode when editorContext is set (must exist). |
| Sticky assignment | Remembering 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 allowlist | A guest list of allowed websites. | CODE.domains vs location.hostname. If the host is not listed, Smart Code does not run. |
| Attribute helper | A 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. |
| Integration | A 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. |
| gtag | Google’s function for sending analytics events. | Sample runtime may call gtag("event", "croforge_" + name, payload). |
| dataLayer | Google 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. |
| sendBeacon | A 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. |
| Cookie | A small note the browser stores and often sends with later requests. | Used for sticky visitor/assignment when useLocalStorage is false. |
| localStorage | A 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). |
| sessionStorage | A notepad that is thrown away when the tab closes. | _croforge_session_uuid lives here. |
| Visitor UUID | A unique nametag for “this browser” across visits. | Storage key _croforge_visitor_uuid. |
| Session UUID | A unique nametag for “this visit until the tab ends.” | Storage key _croforge_session_uuid (sessionStorage). |
| Impression | Proof that someone was shown something. | Event fired after a variation is assigned and CSS/JS applied in live mode. |
| Beacon | A 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.
- Ensure
dataLayer/gtagstub exists. - Define
CODEpayload (domains, experiments, attributes, metrics, segments, triggers, events, integrations). - Define attribute helpers +
CROFORGEAPI. - Validate
location.hostnameagainstCODE.domains. window._CROFORGE = window._CROFORGE || CROFORGEtheninit().
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.
| Condition | Path |
|---|---|
| Already started/finished | no-op |
editorContext set | execEditorMode (must exist) |
| Preview mode | loadPreviewMode |
| Else | execLiveMode + bindGenericEventHandler |
Live mode
Live mode is what real visitors hit. Experiments in CODE.experiments are processed one by one.
- Fire page_view-style events for matching triggers.
- For each experiment in
CODE.experiments:getVariation(experiment), then inject CSS, run JS, send impression. - 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.
- URL targeting via
getUrlTargetingMatch→isUrlMatchCondition. - Segment via
getSegmentMatch. - Read sticky variation id (
_croforge_exp_{id}). - If missing/invalid, sample using
startTrafficPercent/endTrafficPercent. - Persist assignment; expose summary on
window._CROFORGE.experiments.
Implementation note: storage keys for assignment must stay consistent between
getLiveVariationIdByExperimentId/setLiveVariationIdByExperimentIdand any write sites ingetVariation.
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 pattern | Purpose |
|---|---|
_croforge_visitor_uuid | Sticky visitor |
_croforge_session_uuid | Session (sessionStorage) |
_croforge_exp_{id} | Sticky variation |
_croforge_view_mode / preview token | Preview |
Integrations
Default push targets (in addition to CROForge’s own ingest):
- CROForge beacon URL (
/e) viasendBeaconor Image pixel - GA4
gtag("event", "croforge_" + name, payload) - 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
sendDebugLogson failure.