Skip to main content
Ask your AI

Web Core Utilities

Web Source code Package

Web core utilities are browser-specific functions designed for client-side walkerOS implementations. These utilities handle DOM interactions, browser information, storage, and web-based communication.

Installation​

Import web utilities from the @walkeros/web-core package:

import { getAttribute, isVisible, sendWeb } from '@walkeros/web-core';

DOM utilities​

getAttribute​

getAttribute(element: Element, name: string): string returns an attribute's trimmed value, or an empty string when the element does not have it.

const element = document.querySelector('[data-elb="product"]');
const entityType = getAttribute(element, 'data-elb'); // Returns 'product'

Attribute Parsing​

splitAttribute​

splitAttribute(str: string, separator?: string): string[] splits attribute strings by a separator (default ;).

splitAttribute('id:123,name:shirt', ','); // Returns ['id:123', 'name:shirt']

splitKeyVal​

splitKeyVal(str: string): [string, string] splits key-value pairs from attribute strings.

splitKeyVal('id:123'); // Returns ['id', '123']

parseInlineConfig​

parseInlineConfig(str: string): Record<string, unknown> parses inline configuration strings from HTML attributes.

parseInlineConfig('tracking:true;debug:false;port:3000');
// Returns { tracking: true, debug: false, port: 3000 }

Browser information​

getLanguage​

getLanguage(navigatorRef: Navigator): string | undefined extracts the user's preferred language.

getLanguage(navigator); // Returns 'en-US' or user's language

getTimezone​

getTimezone(): string | undefined gets the user's timezone from the Intl API.

getTimezone(); // Returns 'America/New_York' or user's timezone

getScreenSize​

getScreenSize(windowRef: Window): string returns the window's screen dimensions.

getScreenSize(window); // Returns '1920x1080' or current screen size

Element visibility​

isVisible​

isVisible(element: HTMLElement, win: Window, doc: Document): boolean checks whether an element is rendered and not painted over. It does not measure how much of the element is inside the viewport; that is the job of the visible and impression triggers.

const promoElement = document.getElementById('promotion');
if (isVisible(promoElement, window, document)) {
  // Element is rendered and nothing else is painted over it
}

This function considers:

  • Computed display, visibility, and opacity, including transparent ancestors
  • Clipping against the viewport itself, not against ancestor overflow boxes; a parent with overflow: hidden is instead caught incidentally by the occlusion hit test below
  • Occlusion, via a hit test at the centre of the element's visible area, so something else painted on top of it counts as not visible

Storage management​

Storage Operations​

storageRead​

storageRead(key: string, storage?: StorageType, env?: StorageEnv): WalkerOS.PropertyType reads data from browser storage with automatic type conversion. A missing or expired value reads as an empty string.

// Default uses sessionStorage
const sessionData = storageRead('session_data');

// Use localStorage
const userId = storageRead('walker_user_id', 'local');

storageWrite​

storageWrite(key: string, value: WalkerOS.PropertyType, maxAgeInMinutes?: number, storage?: StorageType, domain?: string, env?: StorageEnv): WalkerOS.PropertyType writes data to storage with expiration and domain options. maxAgeInMinutes defaults to 30 and storage to 'session'. It returns the value read back, or an empty string when the write failed. Local and session storage keep String(value), so pass an object as a JSON string; a cookie JSON-encodes an object itself.

// Store with 30-minute expiration
storageWrite('user_preference', 'dark-mode', 30);

// Store in localStorage with the default expiration
storageWrite('temp_data', JSON.stringify({ id: 123 }), undefined, 'local');

// Store with custom domain for cookies
storageWrite('tracking_id', 'abc123', 1440, 'cookie', '.example.com');

storageDelete​

storageDelete(key: string, storage?: StorageType, domain?: string, env?: StorageEnv) removes data from storage.

storageDelete('expired_data');
storageDelete('session_temp', 'session');

// Delete a cookie that was written with a domain attribute
storageDelete('tracking_id', 'cookie', 'example.com');

Web communication​

sendWeb​

sendWeb<T>(url: string, data?: SendDataValue, options?: SendWebOptionsDynamic<T>): SendWebReturn<T> sends data using various web transport methods. It resolves (fetch) or returns (beacon, xhr) { data } when the request was sent, and throws a StepError otherwise: code: 'transport' with status and body for a non-2xx answer or a network error, 'timeout' for a fetch past its timeout, and 'beacon-rejected' when the browser refuses a beacon. The beacon transport ignores headers and method.

// Default fetch transport
await sendWeb('https://api.example.com/events', eventData);

// Use specific transport
await sendWeb(url, data, { transport: 'beacon' });
await sendWeb(url, data, { transport: 'xhr' });

// With custom headers (fetch and xhr)
await sendWeb(url, data, {
  headers: { 'X-Site': 'shop' },
  method: 'PUT',
});

Headers set in browser code reach every visitor: never put a secret in them.

Transport-Specific Functions​

sendWebAsFetch​

sendWebAsFetch(url: string, data?: SendDataValue, options?: SendWebOptionsFetch): Promise<SendResponse> uses the Fetch API. Requests use keepalive while the keepalive bodies in flight on the page stay within 64 KiB, so they can outlive the page; past that a request goes out without it. With noCors: true the response is opaque: any answer counts as sent and data is empty.

await sendWebAsFetch(url, data, {
  credentials: 'include',
  timeout: 5000,
});

// Opaque request: the status is not readable
await sendWebAsFetch(url, data, { noCors: true });

sendWebAsBeacon​

sendWebAsBeacon(url: string, data?: SendDataValue): SendResponse uses the Beacon API for reliable data transmission, especially during page unload. It throws a StepError with code: 'beacon-rejected' when the browser refuses the beacon.

// Reliable sending during page unload
window.addEventListener('beforeunload', () => {
  sendWebAsBeacon('/analytics/pageview', { duration: Date.now() - startTime });
});

sendWebAsXhr​

sendWebAsXhr(url: string, data?: SendDataValue, options?: SendWebOptions): SendResponse uses XMLHttpRequest for synchronous communication.

// Synchronous request (blocks execution)
const response = sendWebAsXhr(url, data, { method: 'POST' });

Tag Mode loader​

moin​

moin() lets the walkerOS app open Tag Mode on your page, in the one browser tab the app opened for it. There is nothing to configure. walker.js and the web bundles the CLI builds call it first in their entry, so call it yourself only when you start a flow from your own browser code:

import { moin } from '@walkeros/web-core';

moin(); // once, early, before startFlow

It does nothing unless the page, or an earlier page in the same tab, was opened with elbMoin in its address, and it runs only in the top frame. On such a page it waits for the walkerOS app tab to answer and only then loads the Tag Mode script from https://cdn.walkeros.io; without that answer nothing loads. Without https://cdn.walkeros.io in your Content Security Policy's script-src, nothing loads either, unless the policy uses 'strict-dynamic', which trusts scripts added by a script that carries your nonce.

moin(target?: MoinTarget) takes no argument in normal use: the default, MOIN_PRODUCTION, trusts the walkerOS app at https://app.walkeros.io. MOIN_PARAM is the address parameter, 'elbMoin'. Both constants are exported by @walkeros/core.

Web hashing​

getHashWeb​

getHashWeb(str: string, length?: number): Promise<string> generates SHA-256 hex hashes using the Web Crypto API. Without Web Crypto, for example on a page served over plain http, it resolves to an empty string.

await getHashWeb('user123@example.com');
// Returns the full 64-character hash

await getHashWeb('user123@example.com', 16);
// Returns '865c4dd20427a134'

Configuration types​

SendWebOptions​

interface SendWebOptions {
  headers?: Record<string, string>;
  method?: string; // Default: 'POST'
  transport?: 'fetch' | 'beacon' | 'xhr'; // Default: 'fetch'
}

interface SendWebOptionsFetch extends SendWebOptions {
  credentials?: 'omit' | 'same-origin' | 'include';
  noCors?: boolean;
  timeout?: number; // Abort the request after this many ms (default 10000)
}

StorageEnv​

interface StorageEnv {
  window?: Window & typeof globalThis;
  document?: Document;
}

The optional env parameter on storage functions allows injecting window and document for testing and simulation. When omitted, the global window and document are used.

StorageType​

type StorageType = 'local' | 'session' | 'cookie';

Usage notes​

  • Browser information functions may require user consent, depending on privacy regulations.
  • Storage functions do not throw when storage is unavailable: a read returns an empty string, and so does a failed write.
  • Choose the transport by use case:
    • fetch - Supports responses
    • beacon - Reliable during page unload, small payloads, no custom headers
    • xhr - Synchronous when needed, broader browser support

For platform-agnostic utilities, see Core Utilities. Sessions are detected by the session source.

💡 Need implementation support?
elbwalker offers hands-on support: setup review, measurement planning, destination mapping, and live troubleshooting. Book a 2-hour session (€399)