Run the following command to start using web-utils in your projects:
npm i @alessiofrittoli/web-utilsor using pnpm
pnpm i @alessiofrittoli/web-utils- Add
deferTask. See API Reference for more info. - Add
deferCallback. See API Reference for more info.
import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/arrays'Removes duplicate values from an array.
Parameters
| Parameter | Type | Description |
|---|---|---|
array |
T[] |
The input array. |
Returns
Type: T[]
The filtered array.
Usage
const pointer = {}
console.log( arrayUnique( [ pointer, 'b', pointer, 'c', 'b' ] ) )
// Outputs: [ {}, 'b', 'c' ]Removes duplicate entries from an array referencing an object key.
Parameters
| Parameter | Type | Description |
|---|---|---|
array |
T[] |
An array of objects. |
property |
keyof T |
The Object property to refer to. |
Returns
Type: T[]
The filtered array.
Usage
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' },
// ]Convert a stringified Array to Array object.
Parameters
| Parameter | Type | Description |
|---|---|---|
string |
string |
An array of objects. |
Returns
Type: string[]
The converted stringified Array to Array object.
Usage
console.log( listToArray( '1,2, 3, 4' ).map( Number ) )
// Outputs: [ 1, 2, 3, 4 ]Split Array into chunks.
Type Parameters
| Parameter | Default | Description |
|---|---|---|
T |
unknown[] |
The input array type. |
Parameters
| 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. |
Returns
Type: T[]
An Array of chunks.
Usage
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 ] ]import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/blob'Create and download a blob object.
Parameters
| Parameter | Type | Description |
|---|---|---|
filename |
string |
The download file name. |
data |
BodyInit |
The download file data. |
init |
ResponseInit |
(Optional) The ResponseInit object. |
Usage
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 )
} )import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/dom'Prevent 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.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
target |
HTMLElement |
Document.documentElement |
(Optional) The target Element. |
Usage
const openPopUpHandler = () => {
blockScroll()
// ... handle popup
}.modal-wrapper {
position : fixed;
inset : 0;
padding-right : var( --scrollbar-size, 0 );
}const element = document.querySelector( '.css-selector' )
if ( element ) {
blockScroll( element )
}Restore Element Overflow.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
target |
HTMLElement |
Document.documentElement |
(Optional) The target Element. |
Usage
const closePopUpHandler = () => {
// ... handle close
restoreScroll()
}const element = document.querySelector( '.css-selector' )
if ( element ) {
restoreScroll( element )
}import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/generators'Check if a function is a GeneratorFunction or AsyncGeneratorFunction.
Parameters
| Parameter | Type | Description |
|---|---|---|
reference |
unknown |
The function to check. |
Returns
Type: reference is GeneratorFunction | AsyncGeneratorFunction
trueif the givenreferenceis aGeneratorFunctionorAsyncGeneratorFunction.falseotherwise.
Check if a function is a GeneratorFunction.
Parameters
| Parameter | Type | Description |
|---|---|---|
reference |
unknown |
The function to check. |
Returns
Type: reference is GeneratorFunction
trueif the givenreferenceis aGeneratorFunction.falseotherwise.
Check if a function is an AsyncGeneratorFunction.
Parameters
| Parameter | Type | Description |
|---|---|---|
reference |
unknown |
The function to check. |
Returns
Type: reference is AsyncGeneratorFunction
trueif the givenreferenceis anAsyncGeneratorFunction.falseotherwise.
Check if reference is a Generator or AsyncGenerator.
Parameters
| Parameter | Type | Description |
|---|---|---|
reference |
unknown |
The reference to check. |
Returns
Type: reference is Generator<T> | AsyncGenerator<T>
trueif the givenreferenceis aGeneratororAsyncGenerator.falseotherwise.
Check if reference is a Generator.
Parameters
| Parameter | Type | Description |
|---|---|---|
reference |
unknown |
The reference to check. |
Returns
Type: reference is Generator<T>
trueif the givenreferenceis aGenerator.falseotherwise.
Check if reference is an AsyncGenerator.
Parameters
| Parameter | Type | Description |
|---|---|---|
reference |
unknown |
The reference to check. |
Returns
Type: reference is AsyncGenerator<T>
trueif the givenreferenceis anAsyncGenerator.falseotherwise.
import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/map'A type-safe extension of the Map class that enforces key-value relationships based on a provided type.
Type parameters
| 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. |
Creates a new instance of a type-safe Map with the given type.
Type parameters
Parameters
| Parameter | Type | Description |
|---|---|---|
iterable |
Iterable<readonly [ K, T[ K ] ]> | null |
Initial Map constructor iterable object. |
Returns
Type: TypedMap<T, P, K>
A new instance of a type-safe Map.
Usage
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`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`import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/promises'Await a void Promise that resolves after the given time.
Parameters
| Parameter | Type | Description |
|---|---|---|
time |
number |
The sleep time in milliseconds after the Promise get resolved. |
Returns
Type: Promise<void>
A new Promise which get resolved after the specified time.
Usage
const fn = async () => {
// ...
await sleep( 2000 )
// ...
}Defer task so main-thread is not blocked in order to quickly paint and respond to user interaction.
Type Parameters
| 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. |
Parameters
| Parameter | Type | Description |
|---|---|---|
task |
T |
The task callable function. |
...args |
U |
Arguments required by the given task function. |
Returns
Type: Promise<Awaited<ReturnType<T>>>
A new Promise which returns the task result once fulfilled.
Usage
const myLongTask = () => {
...
}
button.addEventListener( 'click', () => {
deferTask( myLongTask )
} )const myLongTask = ( target: HTMLButtonElement ) => {
...
}
button.addEventListener( 'click', event => {
const target = event.target as HTMLButtonElement
deferTask( myLongTask, target )
} )Defer task handler so main-thread is not blocked in order to quickly paint and respond to user interaction.
Type Parameters
| 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. |
Parameters
| Parameter | Type | Description |
|---|---|---|
task |
T |
The task callable function. |
Returns
Type: ( ...args: U ) => Promise<Awaited<ReturnType<T>>>
A new handler which returns a new Promise that returns the task result once fulfilled.
Usage
const myLongTask = ( event: Event ) => {
...
}
button.addEventListener( 'click', deferCallback( myLongTask ) )import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/strings'Make first letter uppercase.
Parameters
| Parameter | Type | Description |
|---|---|---|
input |
string |
The input string to convert. |
Returns
Type: string
The processed string.
Usage
console.log( ucFirst( 'String value' ) ) // Outputs: 'String value'
console.log( ucFirst( 'string value' ) ) // Outputs: 'String value'Make first letter lowercase.
Parameters
| Parameter | Type | Description |
|---|---|---|
input |
string |
The input string to convert. |
Returns
Type: string
The processed string.
Usage
console.log( lcFirst( 'String value' ) ) // Outputs: 'string value'
console.log( lcFirst( 'string value' ) ) // Outputs: 'string value'Convert string to camelCase.
Parameters
| Parameter | Type | Description |
|---|---|---|
input |
string |
The input string to convert. |
Returns
Type: string
The converted string to camelCase.
Usage
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'Convert string to kebab-case string.
Parameters
| Parameter | Type | Description |
|---|---|---|
input |
string |
The input string to convert. |
Returns
Type: string
The converted string to kebab-case.
Usage
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-charactersStringify value.
Parameters
| Parameter | Type | Description |
|---|---|---|
input |
any |
The value to stringify. |
Returns
Type: string
The stringified input.
Usage
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: ''Parse stringified value.
Type parameters
| Parameter | Description |
|---|---|
T |
The expected returned value type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
input |
string |
The value to parse. |
Returns
Type: T | undefined
- The parsed
input. undefinedif noinputor emptystringis given.
Usage
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'import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/browser-api'Safely executes window.matchMedia() in server and browser environments.
Parameters
| Parameter | Type | Description |
|---|---|---|
query |
string |
The Media Query string to check. |
Returns
Type: boolean
falseifwindowis not defined or if thedocumentcurrently doesn't matches the givenquery.trueotherwise.
Usage
console.log( ! getMediaMatches( '(orientation:portrait)' ) )Opens a webpage in a browser PopUp.
The openBrowserPopUp uses Window.open() under the hood, but provides default options to make your work easier.
Parameters
| 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. |
Returns
Type: WindowProxy | null
- a
WindowProxyobject is returned if the browser successfully opens the new browsing context. nullis returned if the browser fails to open the new browsing context, for example because it was blocked by a browser popup blocker.
Usage
let windowProxy: WindowProxy | null = null
const clickHandler = () => {
if ( windowProxy && ! windowProxy.closed ) {
return windowProxy.focus()
}
windowProxy = openBrowserPopUp( {
url : {
pathname : '/',
query : { key: 'value' }
},
} )
}const clickHandler = () => {
openBrowserPopUp( {
context : 'some-context-name',
url : {
pathname : '/',
query : { key: 'value' }
},
} )
}
const clickHandler2 = () => {
openBrowserPopUp( {
context : 'some-context-name',
url : '/other-path',
} )
}import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/device'Check if device is in portrait orientation.
Returns
Type: boolean
trueif the device is in portrait orientation when this function is executed.falseotherwise.
Importing the class
import { Cookie } from '@alessiofrittoli/web-utils'
// or
import { Cookie } from '@alessiofrittoli/web-utils/storage/Cookie'Importing enum and types
import { Priority, SameSite } from '@alessiofrittoli/web-utils'
// or
import { Priority, SameSite } from '@alessiofrittoli/web-utils/storage/Cookie'
import type { RawCookie, ParsedCookie, ParsedCookieMap } from '@alessiofrittoli/web-utils'
// or
import type { RawCookie, ParsedCookie, ParsedCookieMap } from '@alessiofrittoli/web-utils/storage/Cookie'Enumerators
The Cookie Priority.
| Constant | Value | Description |
|---|---|---|
Low |
Low | Low priority. |
Medium |
Medium | Medium priority (default). |
High |
High | High priority. |
Controls 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. |
Types
Interface representing Cookie properties before it get parsed.
Properties
| 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. |
Interface representing Cookie properties after it get parsed.
Properties
- Extends and overrides -
RawCookie<K, V>
| Property | Type | Description |
|---|---|---|
expires |
Date |
Indicates the maximum lifetime of the cookie. |
Map representation of a parsed Cookie.
Static methods
Parse the given cookie parameters to a Cookie Map.
Type parameters
| Parameter | Description |
|---|---|
K |
The typed cookie name. |
V |
The type of the cookie value. |
Parameters
| Parameter | Type | Description |
|---|---|---|
options |
RawCookie<K, V> | ParsedCookieMap<K, V> |
The cookie options or a parsed Cookie Map. |
Returns
Type: ParsedCookieMap<K, V>
The parsed Cookie Map.
Usage
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,
} )Stringify a Cookie ready to be stored.
Type parameters
| Parameter | Description |
|---|---|
K |
The typed cookie name. |
V |
The type of the cookie value. |
Parameters
| Parameter | Type | Description |
|---|---|---|
options |
RawCookie<K, V> | ParsedCookieMap<K, V> |
The cookie options or a parsed Cookie Map. |
Returns
Type: string
The stringified Cookie ready to be stored.
Usage
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,
} )
)Parse a cookie string to a Cookie Map.
Type parameters
| Parameter | Description |
|---|---|
K |
The typed cookie name. |
V |
The expected cookie value type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
cookie |
string |
The cookie string. |
Returns
Type: ParsedCookieMap<K, V> | null
The parsed Cookie Map or null if parsing fails.
Usage
const cookies = (
document.cookie.split( '; ' )
.map( Cookie.fromString )
.filter( Boolean )
)Parse a cookie list string to a Map of cookies.
Type parameters
| Parameter | Description |
|---|---|
T |
A Record o key-value pairs (key: cookie name, value: expected cookie value type). |
K |
Internal. |
Parameters
| Parameter | Type | Description |
|---|---|---|
list |
string |
The cookie list string. |
Returns
Type: TypedMap<{ [P in K]: ParsedCookieMap<P, T[P]>; }>
The Map of parsed cookies indexed by the Cookie name.
Usage
/** 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
}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`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`
}Get a cookie by cookie name from Document.cookie.
Type parameters
| Parameter | Description |
|---|---|
T |
The expected type for the Cookie value. |
Parameters
| Parameter | Type | Description |
|---|---|---|
name |
string |
The name of the cookie. |
Returns
Type: ParsedCookieMap<typeof name, T> | undefined
- The found parsed cookie.
undefinedif no cookie has been found inDocument.cookie.
Usage
const cookie = Cookie.get<string>( 'access_token' )
const value = cookie?.get( 'value' ) // `string | undefined`Get a Map of all cookies found in Document.cookie.
Type parameters
| Parameter | Description |
|---|---|
T |
A Record o key-value pairs (key: cookie name, value: expected cookie value type). |
Returns
Type: TypedMap<{ [P in K]: ParsedCookieMap<P, T[P]>; }>
The Map of parsed cookies indexed by the Cookie name.
Usage
const cookies = Cookie.getAll()
const cookie = cookies.get( 'somecookie' )Set a cookie to Document.cookie.
Type parameters
| Parameter | Description |
|---|---|
K |
The typed cookie name. |
V |
The cookie value type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
options |
RawCookie<K, V> | ParsedCookieMap<K, V> |
The cookie options or a parsed Cookie Map. |
Returns
Type: ParsedCookieMap<K, V> | false
- The set Cookie
Mapif successful. falseon failure.
Usage
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 ) )Delete a cookie by cookie name from Document.cookie.
Parameters
| Parameter | Type | Description |
|---|---|---|
name |
string |
The cookie name to delete. |
Returns
Type: boolean
trueon successfull.falseon failure.
Usage
Cookie.delete( 'some_cookie' )A browser-compatible implementation of localStorage.
Importing the class
import { LocalStorage } from '@alessiofrittoli/web-utils'
// or
import { LocalStorage } from '@alessiofrittoli/web-utils/storage/LocalStorage'Static methods
Get storage item name by item numeric index.
Parameters
| Parameter | Type | Description |
|---|---|---|
index |
number |
The item index in the storage. |
Returns
Type: string | null
- The name of the nth key.
nullif n is greater than or equal to the number of key/value pairs.
Usage
console.log( LocalStorage.key( 0 ) ) // Outputs: first item name if any.Get the number of key/value pairs.
Returns
Type: number
The number of key/value pairs.
Usage
console.log( LocalStorage.getLength() )Get the current value associated with the given key, or undefined if the given key does not exist.
Type parameters
| Parameter | Description |
|---|---|
T |
The expected item value type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
key |
string |
The item name. |
Returns
Type: T | undefined
- The current value associated with the given
key. undefinedif the givenkeydoes not exist.
Usage
LocalStorage.get<Date>( 'expiration' )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.
Type parameters
| Parameter | Description |
|---|---|
T |
The item value type. |
Parameters
| Parameter | Type | Description |
|---|---|---|
key |
string |
The item name. |
value |
T |
The item value. |
Throws
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.)
Usage
LocalStorage.set<Date>( 'expiration', new Date() )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.
Parameters
| Parameter | Type | Description |
|---|---|---|
key |
string |
The item name. |
Usage
LocalStorage.delete( 'expiration' )Removes all key/value pairs, if there are any.
Dispatches a storage event on Window objects holding an equivalent Storage object.
Usage
LocalStorage.clear()A 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.
Importing the class
import { SessionStorage } from '@alessiofrittoli/web-utils'
// or
import { SessionStorage } from '@alessiofrittoli/web-utils/storage/SessionStorage'npm installor using pnpm
pnpm iRun the following command to test and build code for distribution.
pnpm buildwarnings / errors check.
pnpm lintRun 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- See
package.jsonfile scripts for more info.
Run tests with coverage.
An HTTP server is then started to serve coverage files from ./coverage folder.
test:coverage:serveContributions 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 [email protected] to disclose any security vulnerabilities.
|
|
|