# @alessiofrittoli/web-utils 中文文档

规范地址：https://npmcn.com/package/%40alessiofrittoli/web-utils/

版本：3\.0\.0
npm 元数据更新时间：2026-10-25T22:51:16.099Z
中文译文更新时间：2026-11-06T12:04:14.807Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40alessiofrittoli/web-utils
原文对照：https://npmcn.com/package/%40alessiofrittoli/web-utils/?lang=original
项目主页：https://github.com/alessiofrittoli/web-utils#readme
源码仓库：https://github.com/alessiofrittoli/web-utils

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：256 kB，49 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=24\.15\.0
- 运行依赖：0 个
- peer 依赖：@alessiofrittoli/fetcher ^2\.1\.0，@alessiofrittoli/exception ^4\.2\.0，@alessiofrittoli/typed-map ^1\.1\.0，@alessiofrittoli/url-utils ^4\.2\.0，@alessiofrittoli/date-utils ^4\.3\.0，@alessiofrittoli/math-utils ^2\.2\.0
- 首次发布：2025-01-06T20:44:07.422Z
- 最新版本发布：2026-10-25T22:51:15.895Z
- 近 30 天下载量：3295（2026-10-06 至 2026-11-04，npm 官方下载统计）
- 已发布版本数：52（近 12 个月 19 个）

## 中文简介

常见类型Script网络工具

## 安装

```sh
npm install @alessiofrittoli/web-utils
```

也可以使用：`pnpm add @alessiofrittoli/web-utils`、`yarn add @alessiofrittoli/web-utils`、`bun add @alessiofrittoli/web-utils`

## README

# 网络用户 QQ

常见类型Script网络工具

 [![Latest version](https://img.shields.io/npm/v/@alessiofrittoli/web-utils)](https://npmjs.org/package/@alessiofrittoli/web-utils)[![Test coverage](https://coveralls.io/repos/github/alessiofrittoli/web-utils/badge.svg) ](https://coveralls.io/github/alessiofrittoli/web-utils)[![Socket Security score](https://socket.dev/api/badge/npm/package/@alessiofrittoli/web-utils) ](https://socket.dev/npm/package/@alessiofrittoli/web-utils/overview)[![npm downloads](https://img.shields.io/npm/dm/@alessiofrittoli/web-utils.svg) ](https://npmjs.org/package/@alessiofrittoli/web-utils)[![Dependencies](https://badgen.net/bundlephobia/dependency-count/@alessiofrittoli/web-utils) ](https://bundlephobia.com/package/@alessiofrittoli/web-utils)[![Dependencies status](https://img.shields.io/librariesio/release/npm/@alessiofrittoli/web-utils)](https://libraries.io/npm/%40alessiofrittoli%2Fweb-utils)

 [![minified](https://badgen.net/bundlephobia/min/@alessiofrittoli/web-utils)](https://bundlephobia.com/package/@alessiofrittoli/web-utils)[![minizipped](https://badgen.net/bundlephobia/minzip/@alessiofrittoli/web-utils) ](https://bundlephobia.com/package/@alessiofrittoli/web-utils)[![Tree shakable](https://badgen.net/bundlephobia/tree-shaking/@alessiofrittoli/web-utils)](https://bundlephobia.com/package/@alessiofrittoli/web-utils)

[![Fund this package](https://img.shields.io/static/v1?label=Fund%20this%20package&message=%E2%9D%A4&logo=GitHub&color=%23DB61A2)](https://github.com/sponsors/alessiofrittoli)

### 目录

-   [开始](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-getting-started)
-   [变了什么](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-whats-changed)
-   [发展](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-development)
    -   [地方发展](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-local-development)
    -   [生产建设](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-production-build)
    -   [单位测试](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-unit-tests)
        -   [进行覆盖测试](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-run-tests-with-coverage)
    -   [捐款](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-contributing)
    -   [警卫](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-security)
-   [API 参考](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-api-reference)
    -   [公用事业](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-blob-utilities)
    -   [阵列公用事业](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-array-utilities)
    -   [多姆公用事业](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-dom-utilities)
        -   [滚动公用事业](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-scroll-utilities)
        -   [样式表工具](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-stylesheet-utilities)
    -   [发电机水电费](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-generators-utilities)
    -   [承诺公用事业](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-promises-utilities)
    -   [字符串公用事业](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-strings-utilities)
    -   [公用事业类型](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-types-utilities)
    -   [核证公用事业](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-validation-utilities)
    -   [公用事业](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-objects-utilities)
    -   [浏览器 API 工具](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-browser-api-utilities)
        -   [文档图片](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-document-picture-in-picture)
        -   [网络信息](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-network-information)
    -   [设备公用事业](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-device-utilities)
    -   [储存公用事业](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-storage-utilities)
        -   [`Cookie` 类](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-cookie-class)
        -   [`LocalStorage` 类](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-localstorage-class)
        -   [`SessionStorage` 类](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-sessionstorage-class)
    -   [用户](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-utils)
-   [贷项](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-made-with-)

* * *

### 开始

运行以下命令开始使用 `web-utils` 在您的项目中:

```bash
npm i @alessiofrittoli/web-utils
```

或使用 `pnpm`

```bash
pnpm i @alessiofrittoli/web-utils
```

* * *

### 变了什么

#### 最新版本的更新 QQ

-   删除已贬值 `getTypedMap` 现在属于 [`@alessiofrittoli/typed-map`](https://www.npmjs.com/package/@alessiofrittoli/typed-map)。 。 。 .
-   移动 [`openBrowserPopUp`](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-openbrowserpopup) 改为 `/browser-popup` 子路径导出 .
-   移动 [`Document Picture-in-Picture`](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-document-picture-in-picture) 改为 `/picture-in-picture` 子路径导出 .
-   移动 [`Cookie` 类](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-cookie-class) 改为 `/cookie` 子路径导出 .
-   移动 [`LocalStorage` 类](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-localstorage-class) 改为 `/storage` 子路径导出 .
-   移动 [`SessionStorage` 类](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-sessionstorage-class) 改为 `/storage` 子路径导出 .
-   移动 [`getDimensions`](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-getdimensions) 改为 `/sizes` 子路径导出 .

旧更新 :

-   添加 `normalizeIndex` 函数。 见 [API 参考](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-normalizeindex) 需要更多信息.
-   添加 `getPreviousIndex` 函数。 见 [API 参考](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-getpreviousindex) 需要更多信息.
-   添加 `getNextIndex` 函数。 见 [API 参考](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-getnextindex) 需要更多信息.
-   添加 `insertAfter` 函数。 见 [API 参考](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-insertafter) 需要更多信息.
-   添加 `deferTask`。见 [API 参考](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-defertask) 需要更多信息.
-   添加 `deferCallback`。见 [API 参考](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-defercallback) 需要更多信息.
-   添加 `parameterized` 函数。 见 [API 参考](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-parameterized) 需要更多信息.
-   添加文档 Picture 工具 。 见 [文档图片](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-document-picture-in-picture) 需要更多信息.

* * *

### 发展

运行以下开始开发

```shell
nvm use

pnpm i
```

#### 地方发展

运行以下

```shell
pnpm dev
```

这将生成未忽略的输出代码, 源图并启用源文件监视器 .

* * *

#### 生产建设

运行以下来创建本地生产建筑

```shell
pnpm build
```

这将生成没有源代码的已修改输出代码 .

* * *

#### 单位测试

通过运行下列程序运行所有定义的测试套件 :

```shell
# Run tests and watch file changes.
pnpm test:watch

# Run tests in a CI environment.
pnpm test:ci
```

* * *

##### 进行覆盖测试

然后开始使用 HTTP 服务器服务覆盖文件 `./coverage` 文件夹.

您可以在您第一次运行此命令时看到空白页 。 只需刷新浏览器即可看到更新 .

```shell
pnpm test:coverage:serve
```

* * *

#### 捐款

献礼真受欢迎!

请参看 [贡献文件](https://npmcn.com/package/%40alessiofrittoli/web-utils/CONTRIBUTING.md) 了解如何开始为该项目作出贡献的更多信息.

帮助更新此项目 [GitHub 赞助商](https://github.com/sponsors/alessiofrittoli)。 。 。 .

[![GitHub Sponsor](https://img.shields.io/static/v1?label=Fund%20this%20package&message=%E2%9D%A4&logo=GitHub&color=%23DB61A2)](https://github.com/sponsors/alessiofrittoli)

* * *

#### 警卫

如果你认为你发现了安全漏洞 我们鼓励你 **_负责地披露此事,不公开问题_**我们将调查所有合法的报告。 电子邮件 `security@alessiofrittoli.it` 披露任何安全弱点.

* * *

### API 参考

#### 阵列公用事业

##### `arrayUnique`

从数组中删除重复值.

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `array` | `T[]` | 输入阵列 . |

* * *

回返

类型 : `T[]`

被过滤的阵列 .

* * *

使用量

###### 从数组中删除重复

```ts
import { arrayUnique } from '@alessiofrittoli/web-utils'

const pointer = {}
console.log(arrayUnique([pointer, 'b', pointer, 'c', 'b']))
// Outputs: [ {}, 'b', 'c' ]
```

* * *

##### `arrayObjectUnique`

从引用对象密钥的数组中删除重复条目.

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `array` | `T[]` | 一系列对象. |
| `property` | `keyof T` | 要提到的对象属性 . |

* * *

回返

类型 : `T[]`

被过滤的阵列 .

* * *

使用量

###### 删除相同正则值的数组重复

```ts
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' },
// ]
```

* * *

##### `listToArray`

将字符串化的矩阵转换为矩阵对象 .

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `string` | `string` | 一系列对象. |

* * *

回返

类型 : `string[]`

转换为串行对象的矩阵 .

* * *

使用量

###### 基本用途

```ts
import { listToArray } from '@alessiofrittoli/web-utils'

console.log(listToArray('1,2, 3, 4').map(Number))
// Outputs: [ 1, 2, 3, 4 ]
```

* * *

##### `chunkInto`

将阵列分割成块 .

类型参数

| 参数 | 默认 | 说明 |
| --- | --- | --- |
| `T` | `unknown[]` | 投入 `array` 类型. |

* * *

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `array` | `T[]` | 原始阵. |
| `options` | `ChunkIntoOptions` | 定义分割标准的对象. |
| `options.size` | `number` | 将分割给定的阵列,以确保每个块长度尽可能与给定的值相等. |
| `options.count` | `number` | 将分割给定的矩阵, 以确保 n 块作为给定值 . |

* * *

回返

类型 : `T[]`

一大堆块.

* * *

使用量

###### 基本用途

```ts
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 ] ]
```

* * *

##### `shuffle`

使用 [Fisher- Yates 算法](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)。 。 。 .

请注意,此函数修改了原给定的 `array`。 。 。 .

类型参数

| 参数 | 说明 |
| --- | --- |
| `T` | 数组中自动推断的元素类型. |

* * *

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `array` | `Array<T>` | 要洗牌的阵列 . |

* * *

回返

类型 : `Array<T>`

已修改的洗牌阵列 .

* * *

示例

```ts
import { shuffle } from '@alessiofrittoli/web-utils'

console.log(shuffle([1, 2, 3, 4, 5]))
```

* * *

##### `shuffleCopy`

使用 [Fisher- Yates 算法](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)。 。 。 .

同样的 API [`shuffle`](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-shuffle) ,但此函数 **不修改** 给定的原件 `array`。 。 。 .

* * *

##### `normalizeIndex`

将负指数规范为正值.

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `index` | `number` | 索引. |
| `length` | `number` | 阵列长度 . |

* * *

回返

类型 : `number`

正常指数.

* * *

实例

```ts
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
```

* * *

##### `getPreviousIndex`

获得上个索引.

参数

| 参数 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `length` | `number` | \- 说吧 | 阵列长度 . |
| `index` | `number` | `0` | 索引. |

* * *

回返

类型 : `number`

上个索引.

* * *

实例

```ts
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
```

* * *

##### `getNextIndex`

获得下个索引.

参数

| 参数 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `length` | `number` | \- 说吧 | 阵列长度 . |
| `index` | `number` | `0` | 索引. |

* * *

回返

类型 : `number`

下个索引.

* * *

实例

```ts
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
```

* * *

##### `insertAfter`

在指定的索引位置将一个或多个项目插入数组.

类型参数

-   `T` 数组中的元素类型.

* * *

参数

| 参数 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `array` | `T[]` | \- 说吧 | 插入项的原始数组 . |
| `item` | `T|T[]` | 0 个 | 要插入的单个项目或一系列项目. |
| `index` | `number` | `-1` | 插入项目后的索引. |

* * *

回返

类型 : `T[]`

在指定位置插入项的新阵列 .

* * *

实例

```ts
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' ]
```

* * *

##### `findIndexBy`

查找首个对象的索引,该对象的选定字段严格等于所提供的值.

类型参数

-   `T` 存储在阵列中的对象类型 .
-   `U` 关键 `T` 用于比较.

* * *

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `options` | `FindInxeByOptions<T, U>` | 搜索选项 . |
| `options.items` | `T[]` | 取所取所取来取取取. |
| `options.field` | `U` | 要比较的对象字段 `value`。 。 。 . |
| `options.value` | `T[U]` | 必须匹配选定字段的值 . |

* * *

回返

类型 : `number`

匹配项的索引,或 `-1` 当找不到匹配时.

* * *

实例

```ts
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
```

* * *

#### 公用事业

##### `downloadBlob`

创建并下载 blob 对象 .

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `filename` | `string` | 下载文件名. |
| `data` | `BodyInit` | 下载文件数据 . |
| `init` | `ResponseInit` | (可选)应答Init对象. |

* * *

使用量

###### 从 HTTP 响应下载文件

```ts
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 )
  } )
```

* * *

#### 多姆公用事业

##### 滚动公用事业

###### `blockScroll`

防止元素流出.

它计算出滚动条宽度,由此产生的值被应用到目标元素右上贴-右上来防止宽度增大.

它还适用 `--scrollbar-size` CSS变量,可用于对目标内的位置固定元素应用贴补右.

参数

| 参数 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `target` | `HTMLElement` | `Document.documentElement` | (可选)目标元素. |

* * *

使用量

###### 弹出时屏蔽文档 HTML 滚动

```ts
import { blockScroll } from '@alessiofrittoli/web-utils/dom'

const openPopUpHandler = () => {
  blockScroll()
  // ... handle popup
}
```

```css
.modal-wrapper {
  position: fixed;
  inset: 0;
  padding-right: var(--scrollbar-size, 0);
}
```

* * *

###### 特定 HTML 元素的块滚动

```ts
import { blockScroll } from '@alessiofrittoli/web-utils/dom'

const element = document.querySelector('.css-selector')

if (element) {
  blockScroll(element)
}
```

* * *

###### `restoreScroll`

还原元素多流.

参数

| 参数 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `target` | `HTMLElement` | `Document.documentElement` | (可选)目标元素. |

* * *

使用量

###### 弹出关闭时恢复文档 HTML 滚动

```ts
import { restoreScroll } from '@alessiofrittoli/web-utils/dom'

const closePopUpHandler = () => {
  // ... handle close
  restoreScroll()
}
```

* * *

###### 恢复特定 HTML 元素的滚动

```ts
import { restoreScroll } from '@alessiofrittoli/web-utils/dom'

const element = document.querySelector('.css-selector')

if (element) {
  restoreScroll(element)
}
```

* * *

##### 样式表工具

###### 类型

###### 乌尔斯图表

代表一个 URL 样式表作为简单的 URL 输入, URL 对象或带有 URL 和获取配置选项的对象.

```ts
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
    }
```

* * *

###### 样式

代表样式输入 .

```ts
type Style = UrlStylesheet | HTMLStyleElement | CSSStyleSheet | StyleSheetList
```

* * *

###### 样式

代表单一样式对象或样式对象的数组.

```ts
type Styles = Style | Style[]
```

* * *

###### `cloneStyleSheetList`

CLones a StyleSheetList 或 CSSStyleSheets 的数组为一组 `HTMLStyleElement` 对象.

此函数从每个样式表提取 CSS 规则并创建相应的 `<style>` 包含序列化 CSS 文本的元素。 如果处理样式表时发生错误, 错误被记录,样式表被跳过.

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `styles` | `StyleSheetList|CSSStyleSheet[]` | 来源 `StyleSheetList` 或数组 `CSSStyleSheet` 要复制的对象. |

* * *

回返

类型 : `HTMLStyleElement[]`

-   数组 `HTMLStyleElement` 对象,每个对象包含来自源样式表的 CSS 规则.
-   失败的样式表被过滤出而不包含在结果中 .

* * *

实例

```ts
import { cloneStyleSheetList } from '@alessiofrittoli/web-utils/stylesheet'

const styles = cloneStyleSheetList(document.styleSheets)
// do something with cloned stylesheets
// styles.forEach( style => shadowRoot.appendChild( style ) )
```

* * *

###### `cloneStyleSheets`

各种来源的克伦斯样式表变成新 `HTMLStyleElement` 节点.

-   当 URL 样式表有 `fetch: true`,样式表内容被取出并嵌入为内置 CSS.
-   何时 `fetch: false` (默认),将生成链接元素.
-   URL 解析是通过 `Url` 用于支持字符串和 `UrlInput` 对象格式.

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `styles` | `Styles` | 样式源或样式源的数组. |
|  |  | \- 看到没 [`Styles`](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-styles) 类型,用于列出可能的值. |

* * *

回返

类型 : `Promise<CloneStyleSheetsReturn>`

-   一个承诺,解决 一系列克隆 `HTMLStyleElement` 财务报告和审定财务报表 `HTMLLinkElement` 节点.
-   对于内行样式和样式SheetLists,返回 `HTMLStyleElement` 节点.
-   对于基于 URL 的样式表,返回 `HTMLLinkElement` 节点(或 `HTMLStyleElement` 如果获取是 `true`) (中文(简体) ).
-   失败的操作被默默地忽略.

* * *

实例

###### 克隆 `StyleSheetList`

```ts
import { cloneStyleSheets } from '@alessiofrittoli/web-utils/stylesheet'

const styles = await cloneStyleSheets(document.styleSheets)
// do something with cloned dcoument stylesheets
// styles.forEach( style => shadowRoot.appendChild( style ) )
```

* * *

###### 从 URL 复制样式表

```ts
import { cloneStyleSheets } from '@alessiofrittoli/web-utils/stylesheet'

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 },
])
```

* * *

#### 发电机水电费

##### `isGeneratorFunction`

检查一个函数是否是一个 `GeneratorFunction` 或者说 `AsyncGeneratorFunction`。 。 。 .

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `reference` | `unknown` | 要检查的功能 . |

* * *

回返

类型 : `reference` 实值 `GeneratorFunction | AsyncGeneratorFunction`

-   `true` 如果给定 `reference` 是一个 `GeneratorFunction` 或者说 `AsyncGeneratorFunction`。 。 。 .
-   `false` 否则.

* * *

##### `isDefaultGeneratorFunction`

检查一个函数是否是一个 `GeneratorFunction`。 。 。 .

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `reference` | `unknown` | 要检查的功能 . |

* * *

回返

类型 : `reference` 实值 `GeneratorFunction`

-   `true` 如果给定 `reference` 是一个 `GeneratorFunction`。 。 。 .
-   `false` 否则.

* * *

##### `isAsyncGeneratorFunction`

检查一个函数是否是 `AsyncGeneratorFunction`。 。 。 .

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `reference` | `unknown` | 要检查的功能 . |

* * *

回返

类型 : `reference` 实值 `AsyncGeneratorFunction`

-   `true` 如果给定 `reference` 是一个 `AsyncGeneratorFunction`。 。 。 .
-   `false` 否则.

* * *

##### `isGeneratorObject<T>`

检查引用是否为 a `Generator` 或者说 `AsyncGenerator`。 。 。 .

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `reference` | `unknown` | 查询的参考文献. |

* * *

回返

类型 : `reference` 实值 `Generator<T> | AsyncGenerator<T>`

-   `true` 如果给定 `reference` 是一个 `Generator` 或者说 `AsyncGenerator`。 。 。 .
-   `false` 否则.

* * *

##### `isDefaultGeneratorObject<T>`

检查引用是否为 a `Generator`。 。 。 .

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `reference` | `unknown` | 查询的参考文献. |

* * *

回返

类型 : `reference` 实值 `Generator<T>`

-   `true` 如果给定 `reference` 是一个 `Generator`。 。 。 .
-   `false` 否则.

* * *

##### `isAsyncGeneratorObject<T>`

检查引用是否为 `AsyncGenerator`。 。 。 .

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `reference` | `unknown` | 查询的参考文献. |

* * *

回返

类型 : `reference` 实值 `AsyncGenerator<T>`

-   `true` 如果给定 `reference` 是一个 `AsyncGenerator`。 。 。 .
-   `false` 否则.

* * *

#### 承诺公用事业

##### `sleep`

等待一个空洞的保证,在给定的时间之后解决.

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `time` | `number` | 承诺完成后 以毫秒计的入睡时间. |

* * *

回返

类型 : `Promise<void>`

新的承诺,在指定时间之后得到解决.

* * *

使用量

```ts
import { sleep } from '@alessiofrittoli/web-utils'

const fn = async () => {
  // ...
  await sleep(2000)
  // ...
}
```

* * *

##### `deferTask`

Defer任务所以主行脚不被屏蔽,以便快速地涂装并响应用户交互.

类型参数

| 参数 | 说明 |
| --- | --- |
| `T` | 任务函数定义 . `unknown` 类型将由函数类型定义继承. |
| `U` | 任务函数参数 . `unknown` 类型将由函数类型继承. |

* * *

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `task` | `T` | 可调用的任务函数 . |
| `...args` | `U` | 给定的参数 `task` 函数. |

* * *

回返

类型 : `Promise<Awaited<ReturnType<T>>>`

返回新承诺 `task` 结果一旦实现.

* * *

使用量

###### 基本用途

```ts
import { deferTask } from '@alessiofrittoli/web-utils'

const myLongTask = () => {
  ...
}

button.addEventListener( 'click', () => {
  deferTask( myLongTask )
} )
```

* * *

###### 带有自定义参数

```ts
import { deferTask } from '@alessiofrittoli/web-utils'

const myLongTask = ( target: HTMLButtonElement ) => {
  ...
}

button.addEventListener( 'click', event => {
  const target = event.target as HTMLButtonElement
  deferTask( myLongTask, target )
} )
```

* * *

##### `deferCallback`

延后任务处理器如此主行不被屏蔽,以便能快速地作画并响应用户交互.

类型参数

| 参数 | 说明 |
| --- | --- |
| `T` | 任务函数定义 . `unknown` 类型将由函数类型定义继承. |
| `U` | 任务函数参数 . `unknown` 类型将由函数类型继承. |

* * *

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `task` | `T` | 可调用的任务函数 . |

* * *

回返

类型 : `( ...args: U ) => Promise<Awaited<ReturnType<T>>>`

一个新的处理器,它返回一个新的承诺,返回 `task` 结果一旦实现.

* * *

使用量

```ts
import { deferCallback } from '@alessiofrittoli/web-utils'

const myLongTask = ( event: Event ) => {
  ...
}

button.addEventListener( 'click', deferCallback( myLongTask ) )
```

* * *

#### 字符串公用事业

##### `ucFirst`

写出第一个字母大写 .

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `input` | `string` | 要转换的输入字符串 . |

* * *

回返

类型 : `string`

处理过的字符串 .

* * *

使用量

```ts
import { ucFirst } from '@alessiofrittoli/web-utils'

console.log(ucFirst('String value')) // Outputs: 'String value'
console.log(ucFirst('string value')) // Outputs: 'String value'
```

* * *

##### `lcFirst`

使第一个字母小写.

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `input` | `string` | 要转换的输入字符串 . |

* * *

回返

类型 : `string`

处理过的字符串 .

* * *

使用量

```ts
import { lcFirst } from '@alessiofrittoli/web-utils'

console.log(lcFirst('String value')) // Outputs: 'string value'
console.log(lcFirst('string value')) // Outputs: 'string value'
```

* * *

##### `toCamelCase`

将字符串转换为骆驼Case .

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `input` | `string` | 要转换的输入字符串 . |

* * *

回返

类型 : `string`

转换为骆驼Case的字符串 .

* * *

使用量

```ts
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'
```

* * *

##### `toKebabCase`

将字符串转换为 kebab- case 字符串 .

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `input` | `string` | 要转换的输入字符串 . |

* * *

回返

类型 : `string`

转换为 kebab 的字符串 .

* * *

使用量

```ts
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
```

* * *

##### `stringifyValue`

字符串值 .

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `input` | `any` | 字符串的值 . |

* * *

回返

类型 : `string`

字符串 `input`。 。 。 .

* * *

使用量

```ts
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: ''
```

* * *

##### `parseValue`

解析字符串值 .

类型参数

| 参数 | 说明 |
| --- | --- |
| `T` | 预期返回的值类型 . |

* * *

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `input` | `string` | 分析的价值. |

* * *

回返

类型 : `T | undefined`

-   解析 `input`。 。 。 .
-   `undefined` 若无 `input` 或为空 `string` 给出.

* * *

使用量

```ts
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'
```

* * *

##### `parameterized`

创建一个带有占位符值的参数化字符串.

###### 类型

###### `ParameterizedValue`

表示字符串操作中可以用作参数的值.

```ts
type ParameterizedValue = string | boolean | number | bigint
```

###### `Parameterized`

以相应的数值表示参数化字符串.

```ts
type Parameterized = [string, ParameterizedValue[]]
```

实例

```ts
import { parameterized } from '@alessiofrittoli/web-utils'

const data = {
  value: 'parameterized',
}

console.log(parameterized`My string with ${data.value} values.`) // [ 'My string with ? values.', [ 'parameterized' ] ]
```

* * *

#### 公用事业类型

医生马上就来了

* * *

#### 核证公用事业

医生马上就来了

#### 公用事业

医生马上就来了

* * *

#### 浏览器 API 工具

##### `getMediaMatches`

安全执行 `window.matchMedia()` 在服务器和浏览器环境中.

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `query` | `string` | 媒体查询字符串要检查 . |

* * *

回返

类型 : `boolean`

-   `false` 若为 `window` 未定义或如果 `document` 目前不匹配给定的 `query`。 。 。 .
-   `true` 否则.

* * *

使用量

###### 检查当前设备是否面向地貌

```ts
import { getMediaMatches } from '@alessiofrittoli/web-utils'

console.log(!getMediaMatches('(orientation:portrait)'))
```

* * *

##### `openBrowserPopUp`

在浏览器 PopUp 中打开网页.

这个 `openBrowserPopUp` 用途 [`Window.open()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/open) 但提供默认选项 让你的工作更容易.

> \[尖叫声\]
> 
> 需要安装以下软件包:
> 
> -   [`@alessiofrittoli/typed-map`](https://npmjs.com/package/@alessiofrittoli/typed-map)
> -   [`@alessiofrittoli/url-utils`](https://npmjs.com/package/@alessiofrittoli/url-utils)

参数

| 参数 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `options` | `OpenBrowserPopUpOptions` | \- 说吧 | 定义自定义弹出选项的对象 . |
| `options.url` | `UrlInput` | \- 说吧 | 要加载的资源的 URL 或路径 。 见 [用户输入](https://github.com/alessiofrittoli/url-utils?tab=readme-ov-file#urlinput) 需要更多关于公认格式的信息. |
| `options.width` | `number` | `600` | 弹出宽度. |
| `options.height` | `number` | `800` | 弹出地高. |
| `options.context` | `string` | \- 说吧 | 一个字符串,没有空白,指定正在装入资源的浏览上下文的名称. |
| `options.features` | `OptionsFeatures` | \- 说吧 | 额外的自定义 PopUp 特性 . |

* * *

回返

类型 : `WindowProxy | null`

-   (单位:千美元) `WindowProxy` 如果浏览器成功打开了新的浏览上下文,则返回对象.
-   `null` 如果浏览器无法打开新的浏览上下文, 则返回, 例如因为它被浏览器弹出屏蔽.

* * *

使用量

###### 重聚焦先前打开的弹出

```ts
import { openBrowserPopUp } from '@alessiofrittoli/web-utils/browser-popup'

let windowProxy: WindowProxy | null = null

const clickHandler = () => {
  if (windowProxy && !windowProxy.closed) {
    return windowProxy.focus()
  }

  windowProxy = openBrowserPopUp({
    url: {
      pathname: '/',
      query: { key: 'value' },
    },
  })
}
```

* * *

###### 重新使用弹出

```ts
import { openBrowserPopUp } from '@alessiofrittoli/web-utils/browser-popup'

const clickHandler = () => {
  openBrowserPopUp({
    context: 'some-context-name',
    url: {
      pathname: '/',
      query: { key: 'value' },
    },
  })
}

const clickHandler2 = () => {
  openBrowserPopUp({
    context: 'some-context-name',
    url: '/other-path',
  })
}
```

* * *

##### 文档图片

> \[尖叫声\]
> 
> 需要安装以下软件包:
> 
> -   [`@alessiofrittoli/exception`](https://npmjs.com/package/@alessiofrittoli/exception)
> -   [`@alessiofrittoli/fetcher`](https://npmjs.com/package/@alessiofrittoli/fetcher)
> -   [`@alessiofrittoli/url-utils`](https://npmjs.com/package/@alessiofrittoli/url-utils)
> -   [`@alessiofrittoli/math-utils`](https://npmjs.com/package/@alessiofrittoli/math-utils)

###### 类型

###### `OpenDocumentPictureInPictureOptions`

定义打开文档相册窗口的配置选项.

属性

| 财产 | 类型 | 默认 | 说明 |
| --- | --- | --- | --- |
| `sizes` | `InputDimensions` | `[ 250, 250 ]` | 表示要设置的宽度和高度的非负数的倒数 |
|  |  |  | 为 Picture 窗口的取景口,以像素为单位. |
|  |  |  | \- 看到没 [`InputDimensions`](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-inputdimensions) 类型,用于列出可能的值. |
| `disallowReturnToOpener` | `boolean` | `false` | 提示浏览器它不应显示允许 |
|  |  |  | 用户返回原标签并关闭 Picture 窗口. |
| `preferInitialWindowPlacement` | `boolean` | `false` | 定义 Picture 窗口是否总是出现在 |
|  |  |  | 它最初开放的位置和大小,在关闭后重新开放. |
|  |  |  | 相反,如果 `preferInitialWindowPlacement` 实值 `false` 页:1 |
|  |  |  | 关闭时会记住图片内窗口的大小和位置 |
|  |  |  | 并重新开放——它将按以前的立场和规模重新开放, |
|  |  |  | 例如用户设置的. |
| `styles` | `Styles` | \- 说吧 | 自定义在 Picture 窗口内加载的样式 . |
|  |  |  | \- 看到没 [`Styles`](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-styles) 类型,用于列出可能的值. |
|  |  |  | QQ 为了与您的网页应用程序保持一致的样式,文档样式会自动被克隆. |
| `onQuit` | `() => void` | \- 说吧 | 当 Picture- in- Picture 窗口关闭时, 要执行的回调 . |

* * *

###### `OpenDocumentPictureInPicture`

定义打开文档相册窗口的返回结果.

属性

| 财产 | 类型 | 说明 |
| --- | --- | --- |
| `window` | `Window` | 文档 Picture 窗口内的浏览上下文 . |

* * *

###### `isDocumentPictureInPictureSupported`

检查文档 Picture API 是否得到当前浏览器的支持 .

回返

类型 : `boolean`

-   `true` 如果支持文档中的图片.
-   `false` 否则.

* * *

实例

```ts
import { isDocumentPictureInPictureSupported } from "@alessiofrittoli/web-utils/picture-in-picture";

if ( isDocumentPictureInPictureSupported() ) {
  ...
}
```

* * *

###### `requiresDocumentPictureInPictureAPI`

验证文档 Picture API 由当前浏览器支持 .

-   扔出一个新的 `Exception` 有代码 `ErrorCode.DOCUMENT_PIP_NOT_SUPPORTED` 如果文档中的图片不支持 API.

实例

```ts
import { Exception } from "@alessiofrittoli/exception";
import { requiresDocumentPictureInPictureAPI, ErrorCode } from "@alessiofrittoli/web-utils/picture-in-picture";

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 )
  }
}

```

###### `openDocumentPictureInPicture`

打开文档中图片窗口.

-   扔出一个新的 `Exception` 有代码 `ErrorCode.DOCUMENT_PIP_NOT_SUPPORTED` 如果文档中的图片不支持 API.

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `options` | `OpenDocumentPictureInPictureOptions` | 打开新文档相册窗口的配置选项 . |

* * *

回返

类型 : `Promise<OpenDocumentPictureInPicture>`

-   一个新的承诺,解决文件图片和图片结果 `window` 的上下文.

* * *

实例

###### 简单使用

```ts
import { openDocumentPictureInPicture, ErrorCode } from '@alessiofrittoli/web-utils/picture-in-picture'
import { Exception } from '@alessiofrittoli/exception'

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)
    }
  }
}
```

* * *

###### 装入渲染屏蔽样式

```ts
import { openDocumentPictureInPicture, ErrorCode } from '@alessiofrittoli/web-utils/picture-in-picture'
import { Exception } from '@alessiofrittoli/exception'

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) {
    // ...
  }
}
```

* * *

#### 设备公用事业

##### `isPortrait`

检查设备是否在肖像取向中 .

回返

类型 : `boolean`

-   `true` 如果设备在执行此函数时处于肖像取向.
-   `false` 否则.

* * *

使用量

###### 检查当前设备是否面向地貌

```ts
import { isPortrait } from '@alessiofrittoli/web-utils'

console.log(!isPortrait())
```

* * *

##### 网络信息

###### 类型

###### `Connection` 接口

缺陷网络状态和 `NetworkInformation`。 。 。 .

属性

| 财产 | 类型 | 说明 |
| --- | --- | --- |
| `network` | `NetworkInformation` | 这个 `NetworkInformation` 接口 [网络信息 API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API) |
|  |  | 提供设备用于通信的连接信息 |
|  |  | 与网络连接,并提供一个在连接类型发生变化时通知脚本的手段. |
|  |  | \* 可用性有限 [见完全兼容](https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation#browser_compatibility) |
| `onLine` | `boolean` | 显示设备是否连接到网络. |
|  |  | \- 看到没 [正在监听网络状态的变化](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine#listening_for_changes_in_network_status)。 。 。 . |

* * *

###### `getConnection`

获取当前网络状态和信息 .

回返

类型 : `Connection`

定义网络状态的对象和 `NetworkInformation`。见 [`Connection`](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-connection-interface) 用于更多信息的接口.

* * *

实例

```ts
import { getConnection } from '@alessiofrittoli/web-utils'

const { network } = getConnection()

console.log(network?.effectiveType)
```

* * *

#### 储存公用事业

##### `Cookie` 类

> \[尖叫声\]
> 
> 需要安装以下软件包:
> 
> -   [`@alessiofrittoli/typed-map`](https://npmjs.com/package/@alessiofrittoli/typed-map)
> -   [`@alessiofrittoli/date-utils`](https://npmjs.com/package/@alessiofrittoli/date-utils)
> -   [`@alessiofrittoli/math-utils`](https://npmjs.com/package/@alessiofrittoli/math-utils)

导入enum和类型

```ts
import type { RawCookie, ParsedCookie, ParsedCookieMap } from '@alessiofrittoli/web-utils/cookie'
import { Priority, SameSite } from '@alessiofrittoli/web-utils/cookie'
```

* * *

数字

###### `Priority` 数字

Cookie优先级.

| 常数 | 数值 | 说明 |
| --- | --- | --- |
| `Low` | 低级 | 低优先级. |
| `Medium` | 中型 | 中等优先权(默认). |
| `High` | 高级 | 高优先级. |

* * *

###### `SameSite` 数字

控制是否发送有跨地点请求的饼干,为防范跨地点请求的伪造袭击提供某种保护([中国证监会](https://developer.mozilla.org/en-US/docs/Glossary/CSRF)) (中文(简体) ).

| 常数 | 数值 | 说明 |
| --- | --- | --- |
| `Strict` | 严格 | 浏览器只为同一站点请求发送饼干. |
| `Lax` | 蜡 | 饼干不是根据跨站点请求发送的,比如关于加载图像或帧的请求,而是在用户从外部站点导航到发源地时发送. |
| `None` | 无 | 浏览器发送的饼干同时带有跨站点和同站点请求. |

* * *

类型

###### `RawCookie<K, V>`

在解析前代表 Cookie 属性的接口 .

属性

| 财产 | 类型 | 说明 |
| --- | --- | --- |
| `name` | `K` | 饼干的名字. |
| `value` | `V` | Cookie的价值. |
| `domain` | `string` | 定义寄出饼干的主机. |
| `expires` | `string | number | Date` | 表示饼干的最大寿命. |
| `httpOnly` | `boolean` | 禁止 JavaScript 访问 cookie, 例如通过 [`Document.cookie`](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) 属性. |
| `maxAge` | `number` | 表示到饼干到期为止的秒数。 如果设定, `expires` 被忽略. |
| `partitioned` | `boolean` | 表示饼干应该使用分块存储来存储. |
| `path` | `string` | 指定浏览器发送时必须在请求的 URL 中存在的路径 `Cookie` 头曰. |
| `sameSite` | `SameSite` | 控制是否发送有跨地点请求的饼干,为防范跨地点请求的伪造袭击提供某种保护([中国证监会](https://developer.mozilla.org/en-US/docs/Glossary/CSRF)) (中文(简体) ). |
| `secure` | `boolean` | 指出饼干只有在与 https: scheme 请求时才会发送到服务器. |
| `priority` | `Priority` | 定义 Cookie 优先级 . |

* * *

###### `ParsedCookie<K, V>`

解析后代表 Cookie 属性的界面 .

属性

-   扩展并覆盖 - [`RawCookie<K, V>`](https://npmcn.com/package/%40alessiofrittoli/web-utils/#readme-rawcookiek-v)

| 财产 | 类型 | 说明 |
| --- | --- | --- |
| `expires` | `Date` | 表示饼干的最大寿命. |

* * *

###### `ParsedCookieMap<K, V>`

地图上的Cookie.

* * *

静态方法

###### `Cookie.parse<K, V>()`

将给定的饼干参数分析为 Cookie 地图 .

类型参数

| 参数 | 说明 |
| --- | --- |
| `K` | 被打的饼干名称. |
| `V` | 饼干值的类型 . |

* * *

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `options` | `RawCookie<K, V> | ParsedCookieMap<K, V>` | 饼干选项或解析的Cookie地图. |

* * *

回返

类型 : `ParsedCookieMap<K, V>`

解析的Cookie地图.

* * *

使用量

```ts
import { Cookie } from '@alessiofrittoli/web-utils/cookie'

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>()`

将准备保存的 Cookie 绑定.

类型参数

| 参数 | 说明 |
| --- | --- |
| `K` | 被打的饼干名称. |
| `V` | 饼干值的类型 . |

* * *

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `options` | `RawCookie<K, V> | ParsedCookieMap<K, V>` | 饼干选项或解析的Cookie地图. |

* * *

回返

类型 : `string`

已串起的 Cookie 准备储存 .

* * *

使用量

```ts
import { Cookie } from '@alessiofrittoli/web-utils/cookie'

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>()`

把饼干串分析成饼干地图.

类型参数

| 参数 | 说明 |
| --- | --- |
| `K` | 被打的饼干名称. |
| `V` | 预期的饼干价值类型 . |

* * *

参数

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `cookie` | `string` | 饼干串. |

* * *

调试

## 常见问题

### @alessiofrittoli/web-utils 是什么？

常见类型Script网络工具

### 如何安装 @alessiofrittoli/web-utils？

在项目目录运行 npm install @alessiofrittoli/web-utils，或使用 pnpm add / yarn add / bun add。

### @alessiofrittoli/web-utils 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @alessiofrittoli/web-utils 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @alessiofrittoli/web-utils 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=24\.15\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @alessiofrittoli/web-utils 可以商用吗？

@alessiofrittoli/web-utils 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @alessiofrittoli/web-utils 的下载量有多少？

根据 npm 官方下载统计，@alessiofrittoli/web-utils 在 2026/10/06 – 2026/11/04 这 30 天内被下载 3,295 次，日均约 110 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @alessiofrittoli/web-utils 还在维护吗？

最新版本 3\.0\.0 发布于 2026/10/26（12 天前）；至今共发布 52 个版本，其中过去 12 个月发布了 19 个；首次发布于 2025/01/07。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

