
Product
Introducing Data Exports
Export Socket alert data to your own cloud storage in JSON, CSV, or Parquet, with flexible snapshot or incremental delivery.
@alessiofrittoli/web-utils
Advanced tools
Common TypeScript web utilities
Run the following command to start using web-utils in your projects:
npm i @alessiofrittoli/web-utils
or using pnpm
pnpm i @alessiofrittoli/web-utils
normalizeIndex utility function. See API Reference for more info.getPreviousIndex utility function. See API Reference for more info.getNextIndex utility function. See API Reference for more info.insertAfter utility function. See API Reference for more info.Old updates:
deferTask. See API Reference for more info.deferCallback. See API Reference for more info.parameterized function. See API Reference for more info.arrayUniqueRemoves duplicate values from an array.
| Parameter | Type | Description |
|---|---|---|
array | T[] | The input array. |
Type: T[]
The filtered array.
import { arrayUnique } from "@alessiofrittoli/web-utils";
const pointer = {};
console.log(arrayUnique([pointer, "b", pointer, "c", "b"]));
// Outputs: [ {}, 'b', 'c' ]
arrayObjectUniqueRemoves duplicate entries from an array referencing an object key.
| Parameter | Type | Description |
|---|---|---|
array | T[] | An array of objects. |
property | keyof T | The Object property to refer to. |
Type: T[]
The filtered array.
import { arrayObjectUnique } from "@alessiofrittoli/web-utils";
const arr = [
{ id: 1, name: "a" },
{ id: 2, name: "b" },
{ id: 1, name: "c" }, // duplicate `id`
{ id: 3, name: "d" },
{ id: 4, name: "a" }, // duplicate `name`
];
console.log(arrayObjectUnique(arr, "id"));
// Outputs: [
// { id: 1, name: 'a' },
// { id: 2, name: 'b' },
// { id: 3, name: 'd' },
// { id: 4, name: 'a' },
// ]
console.log(arrayObjectUnique(arr, "name"));
// Outputs: [
// { id: 1, name: 'a' },
// { id: 2, name: 'b' },
// { id: 1, name: 'c' },
// { id: 3, name: 'd' },
// ]
listToArrayConvert a stringified Array to Array object.
| Parameter | Type | Description |
|---|---|---|
string | string | An array of objects. |
Type: string[]
The converted stringified Array to Array object.
import { listToArray } from "@alessiofrittoli/web-utils";
console.log(listToArray("1,2, 3, 4").map(Number));
// Outputs: [ 1, 2, 3, 4 ]
chunkIntoSplit Array into chunks.
| Parameter | Default | Description |
|---|---|---|
T | unknown[] | The input array type. |
| Parameter | Type | Description |
|---|---|---|
array | T[] | The original Array. |
options | ChunkIntoOptions | An object defining split criteria. |
options.size | number | Will split the given Array in a way to ensure each chunk length is, whenever possible, equal to the given value. |
options.count | number | Will split the given Array in a way to ensure n chunks as the given value. |
Type: T[]
An Array of chunks.
import { chunkInto } from "@alessiofrittoli/web-utils";
console.log(chunkInto([1, 2, 3, 4, 5], { count: 2 }));
// Output: [ [ 1, 2, 3 ], [ 4, 5 ] ]
console.log(chunkInto([1, 2, 3, 4, 5], { size: 2 }));
// Output: [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]
shuffleShuffle the elements of an array in place using the Fisher-Yates algorithm.
Please note that this function modify the original given array.
| Parameter | Description |
|---|---|
T | The automatically inferred type of elements in the array. |
| Parameter | Type | Description |
|---|---|---|
array | Array<T> | The array to shuffle. |
Type: Array<T>
The modified shuffled array.
import { shuffle } from "@alessiofrittoli/web-utils";
console.log(shuffle([1, 2, 3, 4, 5]));
shuffleCopyCopy and shuffle the elements of an array in place using the Fisher-Yates algorithm.
Same API of shuffle is applied, but this function does not modify the original given array.
normalizeIndexNormalize negative indexes to a positive value.
| Parameter | Type | Description |
|---|---|---|
index | number | The index. |
length | number | The array length. |
Type: number
The normalized index.
import { normalizeIndex } from "@alessiofrittoli/web-utils";
const array = [0, 1, 2, 3];
console.log(normalizeIndex(2, array.length)); // Outputs: 2
console.log(normalizeIndex(-1, array.length)); // Outputs: 3
console.log(normalizeIndex(-3, array.length)); // Outputs: 1
getPreviousIndexGet the previous index.
| Parameter | Type | Default | Description |
|---|---|---|---|
length | number | - | The array length. |
index | number | 0 | The index. |
Type: number
The previous index.
import { getPreviousIndex } from "@alessiofrittoli/web-utils";
const array = [0, 1, 2, 3];
console.log(getPreviousIndex(array.length, 2)); // Outputs: 1
console.log(getPreviousIndex(array.length, -1)); // Outputs: 2
console.log(getPreviousIndex(array.length, -3)); // Outputs: 0
getNextIndexGet the next index.
| Parameter | Type | Default | Description |
|---|---|---|---|
length | number | - | The array length. |
index | number | 0 | The index. |
Type: number
The next index.
import { getNextIndex } from "@alessiofrittoli/web-utils";
const array = [0, 1, 2, 3];
console.log(getNextIndex(array.length, 2)); // Outputs: 3
console.log(getNextIndex(array.length, -1)); // Outputs: 0
console.log(getNextIndex(array.length, -3)); // Outputs: 2
insertAfterInserts one or more items into an array at the specified index position.
T The type of elements in the array.| Parameter | Type | Default | Description |
|---|---|---|---|
array | T[] | - | The original array to insert items into. |
item | T|T[] | 0 | A single item or an array of items to insert. |
index | number | -1 | The index after which to insert the item(s). |
Type: T[]
A new array with the item(s) inserted at the specified position.
import { insertAfter } from "@alessiofrittoli/web-utils";
console.log(insertAfter([1, 2, 3, 4], 5)); // Outputs: [ 1, 2, 3, 4, 5 ]
console.log(insertAfter(["a", "c"], "b", 0)); // Outputs: [ 'a', 'b', 'c' ]
console.log(insertAfter(["a", "b", "c", "e"], "d", -2)); // Outputs: [ 'a', 'b', 'c', 'd', 'e' ]
findIndexByFinds the index of the first object whose selected field strictly equals the provided value.
T The object type stored in the array.U The key of T used for the comparison.| Parameter | Type | Description |
|---|---|---|
options | FindInxeByOptions<T, U> | The search options. |
options.items | T[] | The collection to search. |
options.field | U | The object field to compare against value. |
options.value | T[U] | The value that must match the selected field. |
Type: number
The index of the matching item, or -1 when no match is found.
import { findIndexBy } from "@alessiofrittoli/web-utils";
const users = [
{ id: 1, name: "Ada" },
{ id: 2, name: "Grace" },
{ id: 3, name: "Linus" },
];
console.log(findIndexBy({ items: users, field: "id", value: 2 })); // Outputs: 1
console.log(findIndexBy({ items: users, field: "name", value: "Linus" })); // Outputs: 2
console.log(findIndexBy({ items: users, field: "id", value: 9 })); // Outputs: -1
downloadBlobCreate and download a blob object.
| Parameter | Type | Description |
|---|---|---|
filename | string | The download file name. |
data | BodyInit | The download file data. |
init | ResponseInit | (Optional) The ResponseInit object. |
import { downloadBlob } from '@alessiofrittoli/web-utils'
fetch( ... )
.then( response => response.formData() )
.then( async data => {
await Promise.all(
Array.from( data.entries() )
.map( async ( [, file ] ) => {
if ( ! ( file instanceof File ) ) return
await downloadBlob( file.name, file )
} )
)
} )
.catch( error => {
console.error( error )
} )
blockScrollPrevent Element Overflow.
It calculates the scrollbar width and the resulting value is applied to the target element right padding-right to prevent width grows.
It also applies the --scrollbar-size CSS variable that can be used to apply a padding-right to the position fixed elements inside the target.
| Parameter | Type | Default | Description |
|---|---|---|---|
target | HTMLElement | Document.documentElement | (Optional) The target Element. |
import { blockScroll } from "@alessiofrittoli/web-utils";
const openPopUpHandler = () => {
blockScroll();
// ... handle popup
};
.modal-wrapper {
position: fixed;
inset: 0;
padding-right: var(--scrollbar-size, 0);
}
import { blockScroll } from "@alessiofrittoli/web-utils";
const element = document.querySelector(".css-selector");
if (element) {
blockScroll(element);
}
restoreScrollRestore Element Overflow.
| Parameter | Type | Default | Description |
|---|---|---|---|
target | HTMLElement | Document.documentElement | (Optional) The target Element. |
import { restoreScroll } from "@alessiofrittoli/web-utils";
const closePopUpHandler = () => {
// ... handle close
restoreScroll();
};
import { restoreScroll } from "@alessiofrittoli/web-utils";
const element = document.querySelector(".css-selector");
if (element) {
restoreScroll(element);
}
Represents a URL stylesheet as a simple URL input, URL object or as an object with URL and fetch configuration options.
type UrlStylesheet =
| UrlInput
| {
/**
* The URL string or a URL object of the stylesheet to load.
*
*/
url: UrlInput;
/**
* Indicates whether to fetch the given URL.
*
* @default false
*/
fetch?: boolean;
};
Represents a style input.
type Style = UrlStylesheet | HTMLStyleElement | CSSStyleSheet | StyleSheetList;
Represents a single style object or an array of style objects.
type Styles = Style | Style[];
cloneStyleSheetListClones a StyleSheetList or array of CSSStyleSheets into an array of HTMLStyleElement objects.
This function extracts CSS rules from each stylesheet and creates corresponding <style>
elements containing the serialized CSS text. If an error occurs while processing a stylesheet,
the error is logged and that stylesheet is skipped.
| Parameter | Type | Description |
|---|---|---|
styles | StyleSheetList|CSSStyleSheet[] | The source StyleSheetList or array of CSSStyleSheet objects to clone. |
Type: HTMLStyleElement[]
HTMLStyleElement objects, each containing the CSS rules from the source stylesheets.import { cloneStyleSheetList } from "@alessiofrittoli/web-utils";
const styles = cloneStyleSheetList(document.styleSheets);
// do something with cloned stylesheets
// styles.forEach( style => shadowRoot.appendChild( style ) )
cloneStyleSheetsClones style sheets from various sources into new HTMLStyleElement nodes.
fetch: true, the stylesheet content is fetched and embedded as inline CSS.fetch: false (default), a link element is created instead.Url utility with support for both string and UrlInput object formats.| Parameter | Type | Description |
|---|---|---|
styles | Styles | A style source or array of style sources. |
- See Styles type for a list of possible values. |
Type: Promise<CloneStyleSheetsReturn>
HTMLStyleElement and HTMLLinkElement nodes.HTMLStyleElement nodes.HTMLLinkElement nodes (or HTMLStyleElement if fetch is true).StyleSheetListimport { cloneStyleSheets } from "@alessiofrittoli/web-utils";
const styles = await cloneStyleSheets(document.styleSheets);
// do something with cloned dcoument stylesheets
// styles.forEach( style => shadowRoot.appendChild( style ) )
import { cloneStyleSheets } from "@alessiofrittoli/web-utils";
const styles = await cloneStyleSheets("/path-to-stylesheet-file.css");
const styles = await cloneStyleSheets({
url: "/path-to-stylesheet-file-2.css",
fetch: true,
});
const styles = await cloneStyleSheets([
"/path-to-stylesheet-file-3.css",
{ url: "/path-to-stylesheet-file-4.css", fetch: true },
]);
isGeneratorFunctionCheck if a function is a GeneratorFunction or AsyncGeneratorFunction.
| Parameter | Type | Description |
|---|---|---|
reference | unknown | The function to check. |
Type: reference is GeneratorFunction | AsyncGeneratorFunction
true if the given reference is a GeneratorFunction or AsyncGeneratorFunction.false otherwise.isDefaultGeneratorFunctionCheck if a function is a GeneratorFunction.
| Parameter | Type | Description |
|---|---|---|
reference | unknown | The function to check. |
Type: reference is GeneratorFunction
true if the given reference is a GeneratorFunction.false otherwise.isAsyncGeneratorFunctionCheck if a function is an AsyncGeneratorFunction.
| Parameter | Type | Description |
|---|---|---|
reference | unknown | The function to check. |
Type: reference is AsyncGeneratorFunction
true if the given reference is an AsyncGeneratorFunction.false otherwise.isGeneratorObject<T>Check if reference is a Generator or AsyncGenerator.
| Parameter | Type | Description |
|---|---|---|
reference | unknown | The reference to check. |
Type: reference is Generator<T> | AsyncGenerator<T>
true if the given reference is a Generator or AsyncGenerator.false otherwise.isDefaultGeneratorObject<T>Check if reference is a Generator.
| Parameter | Type | Description |
|---|---|---|
reference | unknown | The reference to check. |
Type: reference is Generator<T>
true if the given reference is a Generator.false otherwise.isAsyncGeneratorObject<T>Check if reference is an AsyncGenerator.
| Parameter | Type | Description |
|---|---|---|
reference | unknown | The reference to check. |
Type: reference is AsyncGenerator<T>
true if the given reference is an AsyncGenerator.false otherwise.TypedMap<T, P, K>A type-safe extension of the Map class that enforces key-value relationships based on a provided type.
| Parameter | Type | Default | Description |
|---|---|---|---|
T | Record<string, unknown> | unknown | The object type defining the key-value relationships. |
P | boolean | true | Defines whether the Map.get() method should return a possibily undefined value. |
K | keyof T | keyof T | Internal - The subset of keys in T that are allowed in the Map. |
getTypedMap<T, P, K>Creates a new instance of a type-safe Map with the given type.
| Parameter | Type | Description |
|---|---|---|
iterable | Iterable<readonly [ K, T[ K ] ]> | null | Initial Map constructor iterable object. |
Type: TypedMap<T, P, K>
A new instance of a type-safe Map.
import { getTypedMap } from "@alessiofrittoli/web-utils";
interface User {
name: string;
age: number;
isActive: boolean;
}
const user = getTypedMap<User>([
["name", "Foo"],
["age", 27],
["isActive", true],
]);
console.log(user.get("name")); // type: `string | undefined`
console.log(user.get("age")); // type: `number | undefined`
console.log(user.get("isActive")); // type: `boolean | undefined`
import { getTypedMap } from "@alessiofrittoli/web-utils";
interface User {
name: string;
age: number;
isActive: boolean;
banned?: boolean;
}
const user = getTypedMap<User, false>([
["name", "Foo"],
["age", 27],
["isActive", true],
]);
console.log(user.get("name")); // type: `string`
console.log(user.get("age")); // type: `number`
console.log(user.get("isActive")); // type: `boolean`
console.log(user.get("banned")); // type: `boolean | undefined`
sleepAwait a void Promise that resolves after the given time.
| Parameter | Type | Description |
|---|---|---|
time | number | The sleep time in milliseconds after the Promise get resolved. |
Type: Promise<void>
A new Promise which get resolved after the specified time.
import { sleep } from "@alessiofrittoli/web-utils";
const fn = async () => {
// ...
await sleep(2000);
// ...
};
deferTaskDefer task so main-thread is not blocked in order to quickly paint and respond to user interaction.
| Parameter | Description |
|---|---|
T | The task function definition. unknown types will be inherited by your function type definition. |
U | The task function arguments. unknown types will be inherited by your function type. |
| Parameter | Type | Description |
|---|---|---|
task | T | The task callable function. |
...args | U | Arguments required by the given task function. |
Type: Promise<Awaited<ReturnType<T>>>
A new Promise which returns the task result once fulfilled.
import { deferTask } from '@alessiofrittoli/web-utils'
const myLongTask = () => {
...
}
button.addEventListener( 'click', () => {
deferTask( myLongTask )
} )
import { deferTask } from '@alessiofrittoli/web-utils'
const myLongTask = ( target: HTMLButtonElement ) => {
...
}
button.addEventListener( 'click', event => {
const target = event.target as HTMLButtonElement
deferTask( myLongTask, target )
} )
deferCallbackDefer task handler so main-thread is not blocked in order to quickly paint and respond to user interaction.
| Parameter | Description |
|---|---|
T | The task function definition. unknown types will be inherited by your function type definition. |
U | The task function arguments. unknown types will be inherited by your function type. |
| Parameter | Type | Description |
|---|---|---|
task | T | The task callable function. |
Type: ( ...args: U ) => Promise<Awaited<ReturnType<T>>>
A new handler which returns a new Promise that returns the task result once fulfilled.
import { deferCallback } from '@alessiofrittoli/web-utils'
const myLongTask = ( event: Event ) => {
...
}
button.addEventListener( 'click', deferCallback( myLongTask ) )
ucFirstMake first letter uppercase.
| Parameter | Type | Description |
|---|---|---|
input | string | The input string to convert. |
Type: string
The processed string.
import { ucFirst } from "@alessiofrittoli/web-utils";
console.log(ucFirst("String value")); // Outputs: 'String value'
console.log(ucFirst("string value")); // Outputs: 'String value'
lcFirstMake first letter lowercase.
| Parameter | Type | Description |
|---|---|---|
input | string | The input string to convert. |
Type: string
The processed string.
import { lcFirst } from "@alessiofrittoli/web-utils";
console.log(lcFirst("String value")); // Outputs: 'string value'
console.log(lcFirst("string value")); // Outputs: 'string value'
toCamelCaseConvert string to camelCase.
| Parameter | Type | Description |
|---|---|---|
input | string | The input string to convert. |
Type: string
The converted string to camelCase.
import { toCamelCase } from "@alessiofrittoli/web-utils";
console.log(toCamelCase("font-family")); // Outputs: 'fontFamily'
console.log(toCamelCase("background-color")); // Outputs: 'backgroundColor'
console.log(toCamelCase("-webkit-align-content")); // Outputs: 'WebkitAlignContent'
console.log(toCamelCase("some value")); // Outputs: 'someValue'
console.log(toCamelCase("some_value")); // Outputs: 'someValue'
console.log(toCamelCase("some value_with mixed_Cases")); // Outputs: 'someValueWithMixedCases'
console.log(toCamelCase("-string@with#special$characters")); // Outputs: 'StringWithSpecialCharacters'
toKebabCaseConvert string to kebab-case string.
| Parameter | Type | Description |
|---|---|---|
input | string | The input string to convert. |
Type: string
The converted string to kebab-case.
import { toKebabCase } from "@alessiofrittoli/web-utils";
console.log(toKebabCase("fontFamily")); // Outputs: 'font-family'
console.log(toKebabCase("backgroundColor")); // Outputs: 'background-color'
console.log(toKebabCase("string with spaces")); // Outputs: 'string-with-spaces'
console.log(toKebabCase("string_with_underscores")); // Outputs: 'string-with-underscores'
console.log(toKebabCase("WebkitAlignContent")); // Outputs: '-webkit-align-content'
console.log(toKebabCase("some value_with mixed_Cases")); // Outputs: 'some-value-with-mixed-cases'
console.log(toKebabCase("-string@with#special$characters")); // Outputs: '-string-with-special-characters
stringifyValueStringify value.
| Parameter | Type | Description |
|---|---|---|
input | any | The value to stringify. |
Type: string
The stringified input.
import { stringifyValue } from "@alessiofrittoli/web-utils";
console.log(stringifyValue(new Date("Sat, 20 Apr 2025 16:20:00 GMT")));
// Outputs: '2025-04-20T16:20:00.000Z'
console.log(stringifyValue(null));
// Outputs: 'null'
console.log(stringifyValue({ prop: "value", prop2: true }));
// Outputs: '{"prop":"value","prop2":true}'
console.log(stringifyValue([1, 2, true, null, () => {}]));
// Outputs: '[1,2,true,null,null]'
console.log(
stringifyValue(
new Map([
["key", "value"],
["key2", "value"],
]),
),
);
// Outputs: '[["key","value"],["key2","value"]]'
console.log(
stringifyValue(
new Headers({
key: "value",
key2: "value",
}),
),
);
// Outputs: '[["key","value"],["key2","value"]]'
console.log(stringifyValue(true)); // Outputs: 'true'
console.log(stringifyValue(false)); // Outputs: 'false'
console.log(stringifyValue(0)); // Outputs: '0'
console.log(stringifyValue(420)); // Outputs: '420'
console.log(stringifyValue(undefined)); // Outputs: ''
console.log(stringifyValue(() => {})); // Outputs: ''
console.log(stringifyValue(new Promise<void>((resolve) => resolve()))); // Outputs: ''
parseValueParse stringified value.
| Parameter | Description |
|---|---|
T | The expected returned value type. |
| Parameter | Type | Description |
|---|---|---|
input | string | The value to parse. |
Type: T | undefined
input.undefined if no input or empty string is given.import { parseValue } from "@alessiofrittoli/web-utils";
console.log(parseValue<Date>(stringifyValue(new Date())));
// Outputs: current Date object.
console.log(parseValue<number>("12345")); // Outputs: 12345
console.log(parseValue()); // Outputs: undefined
console.log(parseValue(" ")); // Outputs: undefined
console.log(parseValue<true>(stringifyValue(true)));
// Outputs: true
console.log(parseValue(stringifyValue({ key: "value" })));
// Outputs: { key: 'value' }
console.log(parseValue(stringifyValue([1, 2, 3, 4, 5])));
// Outputs: [ 1, 2, 3, 4, 5 ]
console.log(parseValue("String value")); // Outputs: 'String value'
parameterizedCreates a parameterized string with placeholder values.
ParameterizedValueRepresents a value that can be used as a parameter in string operations.
type ParameterizedValue = string | boolean | number | bigint;
ParameterizedRepresents a parameterized string with its corresponding values.
type Parameterized = [string, ParameterizedValue[]];
import { parameterized } from "@alessiofrittoli/web-utils";
const data = {
value: "parameterized",
};
console.log(parameterized`My string with ${data.value} values.`); // [ 'My string with ? values.', [ 'parameterized' ] ]
⚠️ Docs coming soon
⚠️ Docs coming soon
⚠️ Docs coming soon
getMediaMatchesSafely executes window.matchMedia() in server and browser environments.
| Parameter | Type | Description |
|---|---|---|
query | string | The Media Query string to check. |
Type: boolean
false if window is not defined or if the document currently doesn't matches the given query.true otherwise.import { getMediaMatches } from "@alessiofrittoli/web-utils";
console.log(!getMediaMatches("(orientation:portrait)"));
openBrowserPopUpOpens a webpage in a browser PopUp.
The openBrowserPopUp uses Window.open() under the hood, but provides default options to make your work easier.
| Parameter | Type | Default | Description |
|---|---|---|---|
options | OpenBrowserPopUpOptions | - | An object defining custom PopUp options. |
options.url | UrlInput | - | The URL or path of the resource to be loaded. See UrlInput for more info about accepted formats. |
options.width | number | 600 | The PopUp width. |
options.height | number | 800 | The PopUp height. |
options.context | string | - | A string, without whitespace, specifying the name of the browsing context the resource is being loaded into. |
options.features | OptionsFeatures | - | Additional custom PopUp features. |
Type: WindowProxy | null
WindowProxy object is returned if the browser successfully opens the new browsing context.null is returned if the browser fails to open the new browsing context, for example because it was blocked by a browser popup blocker.import { openBrowserPopUp } from "@alessiofrittoli/web-utils";
let windowProxy: WindowProxy | null = null;
const clickHandler = () => {
if (windowProxy && !windowProxy.closed) {
return windowProxy.focus();
}
windowProxy = openBrowserPopUp({
url: {
pathname: "/",
query: { key: "value" },
},
});
};
import { openBrowserPopUp } from "@alessiofrittoli/web-utils";
const clickHandler = () => {
openBrowserPopUp({
context: "some-context-name",
url: {
pathname: "/",
query: { key: "value" },
},
});
};
const clickHandler2 = () => {
openBrowserPopUp({
context: "some-context-name",
url: "/other-path",
});
};
OpenDocumentPictureInPictureOptionsDefines configuration options for opening a Document Picture-in-Picture window.
| Property | Type | Default | Description |
|---|---|---|---|
sizes | InputDimensions | [ 250, 250 ] | A tuple defining non-negative numbers representing the width and the height to set |
| for the Picture-in-Picture window's viewport, in pixels. | |||
- See InputDimensions type for a list of possible values. | |||
disallowReturnToOpener | boolean | false | Hints to the browser that it should not display a UI control that enables the |
| user to return to the originating tab and close the Picture-in-Picture window. | |||
preferInitialWindowPlacement | boolean | false | Defines whether the Picture-in-Picture window will always appear back at the |
| position and size it initially opened at, when it is closed and then reopened. | |||
By contrast, if preferInitialWindowPlacement is false the | |||
| Picture-in-Picture window's size and position will be remembered when closed | |||
| and reopened — it will reopen at its previous position and size, | |||
| for example as set by the user. | |||
styles | Styles | - | Custom styles to load inside the Picture-in-Picture window. |
- See Styles type for a list of possible values. | |||
| ⚠️ To keep consistent styling with your web-app, document styles are automatically cloned. | |||
onQuit | () => void | - | A callback to execute when Picture-in-Picture window is closed. |
OpenDocumentPictureInPictureDefines the returned result of opening a Document Picture-in-Picture window.
| Property | Type | Description |
|---|---|---|
window | Window | The browsing context inside the Document Picture-in-Picture window. |
isDocumentPictureInPictureSupportedChecks if the Document Picture-in-Picture API is supported by the current browser.
Type: boolean
true if Document Picture-in-Picture is supported.false otherwise.import { isDocumentPictureInPictureSupported } from "@alessiofrittoli/web-utils";
if ( isDocumentPictureInPictureSupported() ) {
...
}
requiresDocumentPictureInPictureAPIValidates that the Document Picture-in-Picture API is supported by the current browser.
Exception with code ErrorCode.DOCUMENT_PIP_NOT_SUPPORTED if the Document Picture-in-Picture API is not supported.import { Exception } from "@alessiofrittoli/exception";
import { requiresDocumentPictureInPictureAPI, ErrorCode } from "@alessiofrittoli/web-utils";
const myFunction = () => {
requiresDocumentPictureInPictureAPI()
...
}
try {
myFunction()
} catch ( _err ) {
const err = _err as Error
const error = (
Exception.isException<string, ErrorCode>(err)
? err
: (
new Exception(
err.message,
{
code : ErrorCode.UNKNOWN,
name : err.name,
cause : err,
}
)
)
)
switch ( error.code ) {
case ErrorCode.DOCUMENT_PIP_NOT_SUPPORTED:
console.warn( 'Document Picture-in-Picture is not supported.' )
break
default:
console.error( 'Unknown error', error )
}
}
openDocumentPictureInPictureOpens a Document Picture-in-Picture window.
Exception with code ErrorCode.DOCUMENT_PIP_NOT_SUPPORTED if the Document Picture-in-Picture API is not supported.| Parameter | Type | Description |
|---|---|---|
options | OpenDocumentPictureInPictureOptions | Configuration options for opening a new Document Picture-in-Picture window. |
Type: Promise<OpenDocumentPictureInPicture>
window of the new browsing context.import { Exception } from "@alessiofrittoli/exception";
import {
openDocumentPictureInPicture,
ErrorCode,
} from "@alessiofrittoli/web-utils";
const openPictureInPicture = async () => {
try {
const content = document.createElement("div");
const { window } = await openDocumentPictureInPicture();
window.document.body.appendChild(content);
} catch (_err) {
const err = _err as Error;
const error = Exception.isException<string, ErrorCode>(err)
? err
: new Exception(err.message, {
code: ErrorCode.UNKNOWN,
name: err.name,
cause: err,
});
switch (error.code) {
case ErrorCode.DOCUMENT_PIP_NOT_SUPPORTED:
console.warn("Document Picture-in-Picture is not supported.");
break;
default:
console.error("Unknown error", error);
}
}
};
import { Exception } from "@alessiofrittoli/exception";
import {
openDocumentPictureInPicture,
ErrorCode,
} from "@alessiofrittoli/web-utils";
const openPictureInPicture = async () => {
try {
const content = document.createElement("div");
const { window } = await openDocumentPictureInPicture({
styles: {
url: "/important-stylesheet-fetched-before-opening.css",
fetch: true,
},
});
window.document.body.appendChild(content);
} catch (error) {
// ...
}
};
isPortraitCheck if device is in portrait orientation.
Type: boolean
true if the device is in portrait orientation when this function is executed.false otherwise.import { isPortrait } from "@alessiofrittoli/web-utils";
console.log(!isPortrait());
Connection interfaceDefiens network status and NetworkInformation.
| Property | Type | Description |
|---|---|---|
network | NetworkInformation | The NetworkInformation interface of the Network Information API |
| provides information about the connection a device is using to communicate | ||
| with the network and provides a means for scripts to be notified if the connection type changes. | ||
| ⚠️ Limited availability - See full compatibility | ||
onLine | boolean | Indicates whether the device is connected to the network. |
| - See Listening for changes in network status. |
getConnectionGet current Network status and information.
Type: Connection
An object defining network status and NetworkInformation. See Connection interface for more info.
import { getConnection } from "@alessiofrittoli/web-utils";
const { network } = getConnection();
console.log(network?.effectiveType);
Cookie Classimport { Priority, SameSite } from "@alessiofrittoli/web-utils";
import type {
RawCookie,
ParsedCookie,
ParsedCookieMap,
} from "@alessiofrittoli/web-utils";
Priority EnumThe Cookie Priority.
| Constant | Value | Description |
|---|---|---|
Low | Low | Low priority. |
Medium | Medium | Medium priority (default). |
High | High | High priority. |
SameSite EnumControls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks (CSRF).
| Constant | Value | Description |
|---|---|---|
Strict | Strict | The browser sends the cookie only for same-site requests. |
Lax | Lax | The cookie is not sent on cross-site requests, such as on requests to load images or frames, but is sent when a user is navigating to the origin site from an external site. |
None | None | The browser sends the cookie with both cross-site and same-site requests. |
RawCookie<K, V>Interface representing Cookie properties before it get parsed.
| Property | Type | Description |
|---|---|---|
name | K | The Cookie name. |
value | V | The Cookie value. |
domain | string | Defines the host to which the cookie will be sent. |
expires | string | number | Date | Indicates the maximum lifetime of the cookie. |
httpOnly | boolean | Forbids JavaScript from accessing the cookie, for example, through the Document.cookie property. |
maxAge | number | Indicates the number of seconds until the cookie expires. If set, expires is ignored. |
partitioned | boolean | Indicates that the cookie should be stored using partitioned storage. |
path | string | Indicates the path that must exist in the requested URL for the browser to send the Cookie header. |
sameSite | SameSite | Controls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks (CSRF). |
secure | boolean | Indicates that the cookie is sent to the server only when a request is made with the https: scheme. |
priority | Priority | Defines the Cookie priority. |
ParsedCookie<K, V>Interface representing Cookie properties after it get parsed.
RawCookie<K, V>| Property | Type | Description |
|---|---|---|
expires | Date | Indicates the maximum lifetime of the cookie. |
ParsedCookieMap<K, V>Map representation of a parsed Cookie.
Cookie.parse<K, V>()Parse the given cookie parameters to a Cookie Map.
| Parameter | Description |
|---|---|
K | The typed cookie name. |
V | The type of the cookie value. |
| Parameter | Type | Description |
|---|---|---|
options | RawCookie<K, V> | ParsedCookieMap<K, V> | The cookie options or a parsed Cookie Map. |
Type: ParsedCookieMap<K, V>
The parsed Cookie Map.
import { Cookie } from "@alessiofrittoli/web-utils";
const cookie = Cookie.parse({
name: "cookiename",
value: { test: "value" },
path: "/specific-path",
priority: Priority.High,
expires: Date.now() + 20 * 60 * 1000,
domain: "example.com",
secure: true,
httpOnly: true,
sameSite: SameSite.Lax,
maxAge: Date.now() + 30 * 60 * 1000,
partitioned: true,
});
Cookie.toString<K, V>()Stringify a Cookie ready to be stored.
| Parameter | Description |
|---|---|
K | The typed cookie name. |
V | The type of the cookie value. |
| Parameter | Type | Description |
|---|---|---|
options | RawCookie<K, V> | ParsedCookieMap<K, V> | The cookie options or a parsed Cookie Map. |
Type: string
The stringified Cookie ready to be stored.
import { Cookie } from "@alessiofrittoli/web-utils";
document.cookie = Cookie.toString({
name: "cookiename",
value: { test: "value" },
path: "/specific-path",
priority: Priority.High,
expires: Date.now() + 20 * 60 * 1000,
domain: "example.com",
secure: true,
httpOnly: false,
sameSite: SameSite.Lax,
maxAge: Date.now() + 30 * 60 * 1000,
partitioned: true,
});
Cookie.fromString<K, V>()Parse a cookie string to a Cookie Map.
| Parameter | Description |
|---|---|
K | The typed cookie name. |
V | The expected cookie value type. |
| Parameter | Type | Description |
|---|---|---|
cookie | string | The cookie string. |
Type: ParsedCookieMap<K, V> | null
The parsed Cookie Map or null if parsing fails.
import { Cookie } from "@alessiofrittoli/web-utils";
const cookies = document.cookie
.split("; ")
.map(Cookie.fromString)
.filter(Boolean);
Cookie.fromListString<T, K>()Parse a cookie list string to a Map of cookies.
| Parameter | Description |
|---|---|
T | A Record o key-value pairs (key: cookie name, value: expected cookie value type). |
K | Internal. |
| Parameter | Type | Description |
|---|---|---|
list | string | The cookie list string. |
Type: TypedMap<{ [P in K]: ParsedCookieMap<P, T[P]>; }>
The Map of parsed cookies indexed by the Cookie name.
import { Cookie } from "@alessiofrittoli/web-utils";
/** On-site stubbed cookie names. */
enum CookieName {
COOKIE_1 = "cookie-1",
COOKIE_2 = "cookie-2",
}
interface Cookie1 {
test: "value";
}
interface Cookie2 {
test: boolean;
}
type CookiesMap = {
[CookieName.COOKIE_1]: Cookie1;
[CookieName.COOKIE_2]: Cookie2;
};
Document.cookieimport { Cookie } from "@alessiofrittoli/web-utils";
const cookies = Cookie.fromListString<CookiesMap>(document.cookie);
const cookie = cookies.get(CookieName.COOKIE_1); // `ParsedCookieMap<CookieName.COOKIE_1, Cookie1> | undefined`
const cookieValue = cookie?.get("value"); // `Cookie1 | undefined`
Cookie headerimport { Cookie } from "@alessiofrittoli/web-utils";
const { headers } = request;
const cookielist = headers.get("Cookie");
if (cookielist) {
const cookies = Cookie.fromListString<CookiesMap>(cookielist);
const cookie = cookies.get(CookieName.COOKIE_2); // `ParsedCookieMap<CookieName.COOKIE_2, Cookie2> | undefined`
const cookieValue = cookie?.get("value"); // `Cookie2 | undefined`
}
Cookie.get<T>()Get a cookie by cookie name from Document.cookie.
| Parameter | Description |
|---|---|
T | The expected type for the Cookie value. |
| Parameter | Type | Description |
|---|---|---|
name | string | The name of the cookie. |
Type: ParsedCookieMap<typeof name, T> | undefined
undefined if no cookie has been found in Document.cookie.import { Cookie } from "@alessiofrittoli/web-utils";
const cookie = Cookie.get<string>("access_token");
const value = cookie?.get("value"); // `string | undefined`
Cookie.getAll<T>()Get a Map of all cookies found in Document.cookie.
| Parameter | Description |
|---|---|
T | A Record o key-value pairs (key: cookie name, value: expected cookie value type). |
Type: TypedMap<{ [P in K]: ParsedCookieMap<P, T[P]>; }>
The Map of parsed cookies indexed by the Cookie name.
import { Cookie } from "@alessiofrittoli/web-utils";
const cookies = Cookie.getAll();
const cookie = cookies.get("somecookie");
Cookie.set<K, V>()Set a cookie to Document.cookie.
| Parameter | Description |
|---|---|
K | The typed cookie name. |
V | The cookie value type. |
| Parameter | Type | Description |
|---|---|---|
options | RawCookie<K, V> | ParsedCookieMap<K, V> | The cookie options or a parsed Cookie Map. |
Type: ParsedCookieMap<K, V> | false
Map if successful.false on failure.import { Cookie, type RawCookie } from "@alessiofrittoli/web-utils";
const cookieOptions: RawCookie = {
name: "cookiename",
value: { test: "value" },
path: "/specific-path",
priority: Priority.High,
expires: Date.now() + 20 * 60 * 1000,
domain: "example.com",
secure: true,
httpOnly: false,
sameSite: SameSite.Lax,
maxAge: Date.now() + 30 * 60 * 1000,
partitioned: true,
};
Cookie.set(cookieOptions);
// or
Cookie.set(Coookie.parse(cookieOptions));
Cookie.delete()Delete a cookie by cookie name from Document.cookie.
| Parameter | Type | Description |
|---|---|---|
name | string | The cookie name to delete. |
Type: boolean
true on successfull.false on failure.import { Cookie } from "@alessiofrittoli/web-utils";
Cookie.delete("some_cookie");
LocalStorage ClassA browser-compatible implementation of localStorage.
LocalStorage.key()Get storage item name by item numeric index.
| Parameter | Type | Description |
|---|---|---|
index | number | The item index in the storage. |
Type: string | null
null if n is greater than or equal to the number of key/value pairs.import { LocalStorage } from "@alessiofrittoli/web-utils";
console.log(LocalStorage.key(0)); // Outputs: first item name if any.
LocalStorage.getLength()Get the number of key/value pairs.
Type: number
The number of key/value pairs.
import { LocalStorage } from "@alessiofrittoli/web-utils";
console.log(LocalStorage.getLength());
LocalStorage.get<T>()Get the current value associated with the given key, or undefined if the given key does not exist.
| Parameter | Description |
|---|---|
T | The expected item value type. |
| Parameter | Type | Description |
|---|---|---|
key | string | The item name. |
Type: T | undefined
key.undefined if the given key does not exist.import { LocalStorage } from "@alessiofrittoli/web-utils";
LocalStorage.get<Date>("expiration");
LocalStorage.set<T>()Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.
Dispatches a storage event on Window objects holding an equivalent Storage object.
If a nullish or empty string value is provided, the LocalStorage.delete() method is invoked.
| Parameter | Description |
|---|---|
T | The item value type. |
| Parameter | Type | Description |
|---|---|---|
key | string | The item name. |
value | T | The item value. |
Type: DOMException
A "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.)
import { LocalStorage } from "@alessiofrittoli/web-utils";
LocalStorage.set<Date>("expiration", new Date());
LocalStorage.delete()Removes the key/value pair with the given key, if a key/value pair with the given key exists.
Dispatches a storage event on Window objects holding an equivalent Storage object.
| Parameter | Type | Description |
|---|---|---|
key | string | The item name. |
import { LocalStorage } from "@alessiofrittoli/web-utils";
LocalStorage.delete("expiration");
LocalStorage.clear()Removes all key/value pairs, if there are any.
Dispatches a storage event on Window objects holding an equivalent Storage object.
import { LocalStorage } from "@alessiofrittoli/web-utils";
LocalStorage.clear();
SessionStorage ClassA browser-compatible implementation of sessionStorage.
Same API References of LocalStorage Class is applied to the SessionStorage Class.
Please, refer to LocalStorage Class static methods API Reference for more informations.
getDimensionsExtracts and normalizes dimensions from various input formats.
InputDimensionsRepresents valid input types for specifying dimensions.
type InputDimensions = string | number | [xy: Dimensions[number]] | Dimensions;
DimensionsRepresents a tuple of two optional numeric values.
type Dimensions = [x: number | undefined, y: number | undefined];
| Parameter | Type | Description |
|---|---|---|
dimensions | InputDimensions | The input dimensions. |
Type: Dimensions
A tuple containing [ number, number ] where either value can be undefined.
import { getDimensions } from "@alessiofrittoli/web-utils";
const [width, height] = getDimensions(); // [ undefined, undefined ]
const [width, height] = getDimensions(100); // [ 100, 100 ]
const [width, height] = getDimensions([200, 300]); // [ 200, 300 ]
const [width, height] = getDimensions([200]); // [ 200, 200 ]
const [width, height] = getDimensions("200x300"); // [ 200, 300 ]
npm install
or using pnpm
pnpm i
Run the following command to test and build code for distribution.
pnpm build
warnings / errors check.
pnpm lint
Run all the defined test suites by running the following:
# Run tests and watch file changes.
pnpm test:watch
# Run tests in a CI environment.
pnpm test:ci
package.json file scripts for more info.Run tests with coverage.
An HTTP server is then started to serve coverage files from ./coverage folder.
⚠️ You may see a blank page the first time you run this command. Simply refresh the browser to see the updates.
test:coverage:serve
Contributions are truly welcome!
Please refer to the Contributing Doc for more information on how to start contributing to this project.
Help keep this project up to date with GitHub Sponsor.
If you believe you have found a security vulnerability, we encourage you to responsibly disclose this and NOT open a public issue. We will investigate all legitimate reports. Email security@alessiofrittoli.it to disclose any security vulnerabilities.
|
|
|
FAQs
Common TypeScript web utilities
The npm package @alessiofrittoli/web-utils receives a total of 21 weekly downloads. As such, @alessiofrittoli/web-utils popularity was classified as not popular.
We found that @alessiofrittoli/web-utils demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Product
Export Socket alert data to your own cloud storage in JSON, CSV, or Parquet, with flexible snapshot or incremental delivery.

Research
/Security News
Bitwarden CLI 2026.4.0 was compromised in the Checkmarx supply chain campaign after attackers abused a GitHub Action in Bitwarden’s CI/CD pipeline.

Research
/Security News
Docker and Socket have uncovered malicious Checkmarx KICS images and suspicious code extension releases in a broader supply chain compromise.