> Part of the walkerOS documentation. Project overview and full index: <https://www.walkeros.io/llms.txt>

# Web Core Utilities

<!-- -->

[Web](#)[ ](https://github.com/elbwalker/walkerOS/tree/main/packages/web/core)

<!-- -->

[Source code](https://github.com/elbwalker/walkerOS/tree/main/packages/web/core)[ ](https://www.npmjs.com/package/@walkeros/web-core)

<!-- -->

[Package](https://www.npmjs.com/package/@walkeros/web-core)

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

## Installation[​](#installation "Direct link to Installation")

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

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

## DOM utilities[​](#dom-utilities "Direct link to DOM utilities")

### getAttribute[​](#getattribute "Direct link to getAttribute")

`getAttribute(element: Element, name: string): string` retrieves attribute values from DOM elements with enhanced handling.

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

### Attribute Parsing[​](#attribute-parsing "Direct link to Attribute Parsing")

#### splitAttribute[​](#splitattribute "Direct link to splitAttribute")

`splitAttribute(str: string, separator?: string): string[]` splits attribute strings using specified separators.

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

#### splitKeyVal[​](#splitkeyval "Direct link to splitKeyVal")

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

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

#### parseInlineConfig[​](#parseinlineconfig "Direct link to parseInlineConfig")

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

```
parseInlineConfig('{"tracking": true, "debug": false}');
// Returns { tracking: true, debug: false }
```

## Browser information[​](#browser-information "Direct link to Browser information")

### getLanguage[​](#getlanguage "Direct link to getLanguage")

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

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

### getTimezone[​](#gettimezone "Direct link to getTimezone")

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

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

### getScreenSize[​](#getscreensize "Direct link to getScreenSize")

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

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

## Element visibility[​](#element-visibility "Direct link to Element visibility")

### isVisible[​](#isvisible "Direct link to isVisible")

`isVisible(element: HTMLElement): 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)) {
// 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-management "Direct link to Storage management")

### Storage Operations[​](#storage-operations "Direct link to Storage Operations")

#### storageRead[​](#storageread "Direct link to storageRead")

`storageRead(key: string, storage?: StorageType, env?: StorageEnv): WalkerOS.PropertyType` reads data from browser storage with automatic type conversion.

```
// Default uses localStorage
const userId = storageRead('walker_user_id');

// Use sessionStorage
const sessionData = storageRead('session_data', 'session');
```

#### storageWrite[​](#storagewrite "Direct link to 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.

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

// Store in sessionStorage
storageWrite('temp_data', { id: 123 }, undefined, 'session');

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

#### storageDelete[​](#storagedelete "Direct link to 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');
```

## Session management[​](#session-management "Direct link to Session management")

### sessionStart[​](#sessionstart "Direct link to sessionStart")

`sessionStart(config?: SessionConfig): WalkerOS.SessionData | void` initializes and manages user sessions with automatic renewal and tracking.

```
// Start session with default config
const session = sessionStart();

// Custom session configuration
const session = sessionStart({
storage: true,
domain: '.example.com',
maxAge: 1440, // 24 hours
sampling: 1.0, // 100% sampling
});
```

Session data includes:

* `id` - Unique session identifier
* `start` - Session start timestamp
* `isNew` - Whether this is a new session
* `count` - Number of events in session
* `device` - Device identifier
* `storage` - Whether storage is available

### Advanced Session Functions[​](#advanced-session-functions "Direct link to Advanced Session Functions")

* `sessionStorage` - Session-specific storage operations
* `sessionWindow` - Window/tab session management

## Web communication[​](#web-communication "Direct link to Web communication")

### sendWeb[​](#sendweb "Direct link to sendWeb")

`sendWeb<T>(url: string, data?: SendDataValue, options?: SendWebOptionsDynamic<T>): SendWebReturn<T>` sends data using various web transport methods.

```
// 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
await sendWeb(url, data, {
headers: { Authorization: 'Bearer token' },
method: 'PUT',
});
```

### Transport-Specific Functions[​](#transport-specific-functions "Direct link to Transport-Specific Functions")

#### sendWebAsFetch[​](#sendwebasfetch "Direct link to sendWebAsFetch")

`sendWebAsFetch(url: string, data?: SendDataValue, options?: SendWebOptionsFetch): Promise<SendResponse>` uses the modern Fetch API with advanced options.

```
await sendWebAsFetch(url, data, {
credentials: 'include',
noCors: true,
headers: { 'Content-Type': 'application/json' },
});
```

#### sendWebAsBeacon[​](#sendwebasbeacon "Direct link to sendWebAsBeacon")

`sendWebAsBeacon(url: string, data?: SendDataValue): SendResponse` uses the Beacon API for reliable data transmission, especially during page unload.

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

#### sendWebAsXhr[​](#sendwebasxhr "Direct link to 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' });
```

## Web hashing[​](#web-hashing "Direct link to Web hashing")

### getHashWeb[​](#gethashweb "Direct link to getHashWeb")

`getHashWeb(str: string, length?: number): Promise<string>` generates SHA-256 hashes using the Web Crypto API.

```
// Generate hash for fingerprinting
const userFingerprint = await getHashWeb(
navigator.userAgent + navigator.language + screen.width,
16,
);
// Returns shortened hash like '47e0bdd10f04ef13'
```

## Configuration types[​](#configuration-types "Direct link to Configuration types")

### SendWebOptions[​](#sendweboptions "Direct link to 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)
}
```

### SessionConfig[​](#sessionconfig "Direct link to SessionConfig")

```
interface SessionConfig {
storage?: boolean; // Enable storage persistence
domain?: string; // Cookie domain
maxAge?: number; // Session duration in minutes
sampling?: number; // Sampling rate (0-1)
}
```

### StorageEnv[​](#storageenv "Direct link to 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[​](#storagetype "Direct link to StorageType")

```
type StorageType = 'localStorage' | 'sessionStorage' | 'cookie';
```

## Usage notes[​](#usage-notes "Direct link to Usage notes")

* **Consent Required**: Browser information functions may require user consent depending on privacy regulations

* **Storage Fallbacks**: Storage functions gracefully handle unavailable storage with fallbacks

* **Transport Selection**: Choose transport based on use case:

  <!-- -->

  * `fetch` - Modern, flexible, supports responses
  * `beacon` - Reliable during page unload, small payloads
  * `xhr` - Synchronous when needed, broader browser support

* **Performance**: Session and storage operations are optimized for minimal performance impact

For platform-agnostic utilities, see [Core Utilities](https://www.walkeros.io/docs/core.md).
