@alessiofrittoli/web-utils

中文文档
3.0.0发布于 2026/10/26MITTypeScriptESM + CJS零依赖近 30 天下载 3295

常见类型Script网络工具

中文使用文档
文档目录5 节
  1. 目录
  2. 开始
  3. 变了什么
  4. 发展
  5. API 参考

网络用户 QQ

常见类型Script网络工具

Latest version Test coverage Socket Security score npm downloads Dependencies Dependencies status

minified minizipped Tree shakable

Fund this package

目录


开始

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

npm i @alessiofrittoli/web-utils

或使用 pnpm

pnpm i @alessiofrittoli/web-utils

变了什么

最新版本的更新 QQ

旧更新 :

  • 添加 normalizeIndex 函数。 见 API 参考 需要更多信息.
  • 添加 getPreviousIndex 函数。 见 API 参考 需要更多信息.
  • 添加 getNextIndex 函数。 见 API 参考 需要更多信息.
  • 添加 insertAfter 函数。 见 API 参考 需要更多信息.
  • 添加 deferTask。见 API 参考 需要更多信息.
  • 添加 deferCallback。见 API 参考 需要更多信息.
  • 添加 parameterized 函数。 见 API 参考 需要更多信息.
  • 添加文档 Picture 工具 。 见 文档图片 需要更多信息.

发展

运行以下开始开发

nvm use

pnpm i

地方发展

运行以下

pnpm dev

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


生产建设

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

pnpm build

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


单位测试

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

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

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

进行覆盖测试

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

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

pnpm test:coverage:serve

捐款

献礼真受欢迎!

请参看 贡献文件 了解如何开始为该项目作出贡献的更多信息.

帮助更新此项目 GitHub 赞助商。 。 。 .

GitHub Sponsor


警卫

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


API 参考

阵列公用事业

arrayUnique

从数组中删除重复值.

参数
参数类型说明
arrayT[]输入阵列 .

回返

类型 : T[]

被过滤的阵列 .


使用量
从数组中删除重复
import { arrayUnique } from '@alessiofrittoli/web-utils'

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

arrayObjectUnique

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

参数
参数类型说明
arrayT[]一系列对象.
propertykeyof T要提到的对象属性 .

回返

类型 : T[]

被过滤的阵列 .


使用量
删除相同正则值的数组重复
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

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

参数
参数类型说明
stringstring一系列对象.

回返

类型 : string[]

转换为串行对象的矩阵 .


使用量
基本用途
import { listToArray } from '@alessiofrittoli/web-utils'

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

chunkInto

将阵列分割成块 .

类型参数
参数默认说明
Tunknown[]投入 array 类型.

参数
参数类型说明
arrayT[]原始阵.
optionsChunkIntoOptions定义分割标准的对象.
options.sizenumber将分割给定的阵列,以确保每个块长度尽可能与给定的值相等.
options.countnumber将分割给定的矩阵, 以确保 n 块作为给定值 .

回返

类型 : T[]

一大堆块.


使用量
基本用途
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 算法。 。 。 .

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

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

参数
参数类型说明
arrayArray<T>要洗牌的阵列 .

回返

类型 : Array<T>

已修改的洗牌阵列 .


示例
import { shuffle } from '@alessiofrittoli/web-utils'

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

shuffleCopy

使用 Fisher- Yates 算法。 。 。 .

同样的 API shuffle ,但此函数 不修改 给定的原件 array。 。 。 .


normalizeIndex

将负指数规范为正值.

参数
参数类型说明
indexnumber索引.
lengthnumber阵列长度 .

回返

类型 : number

正常指数.


实例
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

获得上个索引.

参数
参数类型默认说明
lengthnumber- 说吧阵列长度 .
indexnumber0索引.

回返

类型 : number

上个索引.


实例
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

获得下个索引.

参数
参数类型默认说明
lengthnumber- 说吧阵列长度 .
indexnumber0索引.

回返

类型 : number

下个索引.


实例
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 数组中的元素类型.

参数
参数类型默认说明
arrayT[]- 说吧插入项的原始数组 .
itemT|T[]0 个要插入的单个项目或一系列项目.
indexnumber-1插入项目后的索引.

回返

类型 : T[]

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


实例
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 用于比较.

参数
参数类型说明
optionsFindInxeByOptions<T, U>搜索选项 .
options.itemsT[]取所取所取来取取取.
options.fieldU要比较的对象字段 value。 。 。 .
options.valueT[U]必须匹配选定字段的值 .

回返

类型 : number

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


实例
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 对象 .

参数
参数类型说明
filenamestring下载文件名.
dataBodyInit下载文件数据 .
initResponseInit(可选)应答Init对象.

使用量
从 HTTP 响应下载文件
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变量,可用于对目标内的位置固定元素应用贴补右.

参数
参数类型默认说明
targetHTMLElementDocument.documentElement(可选)目标元素.

使用量
弹出时屏蔽文档 HTML 滚动
import { blockScroll } from '@alessiofrittoli/web-utils/dom'

const openPopUpHandler = () => {
  blockScroll()
  // ... handle popup
}
.modal-wrapper {
  position: fixed;
  inset: 0;
  padding-right: var(--scrollbar-size, 0);
}

特定 HTML 元素的块滚动
import { blockScroll } from '@alessiofrittoli/web-utils/dom'

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

if (element) {
  blockScroll(element)
}

restoreScroll

还原元素多流.

参数
参数类型默认说明
targetHTMLElementDocument.documentElement(可选)目标元素.

使用量
弹出关闭时恢复文档 HTML 滚动
import { restoreScroll } from '@alessiofrittoli/web-utils/dom'

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

恢复特定 HTML 元素的滚动
import { restoreScroll } from '@alessiofrittoli/web-utils/dom'

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

if (element) {
  restoreScroll(element)
}

样式表工具
类型
乌尔斯图表

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

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
    }

样式

代表样式输入 .

type Style = UrlStylesheet | HTMLStyleElement | CSSStyleSheet | StyleSheetList

样式

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

type Styles = Style | Style[]

cloneStyleSheetList

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

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

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

回返

类型 : HTMLStyleElement[]

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

实例
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 对象格式.
参数
参数类型说明
stylesStyles样式源或样式源的数组.
- 看到没 Styles 类型,用于列出可能的值.

回返

类型 : Promise<CloneStyleSheetsReturn>

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

实例
克隆 StyleSheetList
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 复制样式表
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。 。 。 .

参数
参数类型说明
referenceunknown要检查的功能 .

回返

类型 : reference 实值 GeneratorFunction | AsyncGeneratorFunction

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

isDefaultGeneratorFunction

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

参数
参数类型说明
referenceunknown要检查的功能 .

回返

类型 : reference 实值 GeneratorFunction

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

isAsyncGeneratorFunction

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

参数
参数类型说明
referenceunknown要检查的功能 .

回返

类型 : reference 实值 AsyncGeneratorFunction

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

isGeneratorObject<T>

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

参数
参数类型说明
referenceunknown查询的参考文献.

回返

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

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

isDefaultGeneratorObject<T>

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

参数
参数类型说明
referenceunknown查询的参考文献.

回返

类型 : reference 实值 Generator<T>

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

isAsyncGeneratorObject<T>

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

参数
参数类型说明
referenceunknown查询的参考文献.

回返

类型 : reference 实值 AsyncGenerator<T>

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

承诺公用事业

sleep

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

参数
参数类型说明
timenumber承诺完成后 以毫秒计的入睡时间.

回返

类型 : Promise<void>

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


使用量
import { sleep } from '@alessiofrittoli/web-utils'

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

deferTask

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

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

参数
参数类型说明
taskT可调用的任务函数 .
...argsU给定的参数 task 函数.

回返

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

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


使用量
基本用途
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 )
} )

deferCallback

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

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

参数
参数类型说明
taskT可调用的任务函数 .

回返

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

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


使用量
import { deferCallback } from '@alessiofrittoli/web-utils'

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

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

字符串公用事业

ucFirst

写出第一个字母大写 .

参数
参数类型说明
inputstring要转换的输入字符串 .

回返

类型 : string

处理过的字符串 .


使用量
import { ucFirst } from '@alessiofrittoli/web-utils'

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

lcFirst

使第一个字母小写.

参数
参数类型说明
inputstring要转换的输入字符串 .

回返

类型 : string

处理过的字符串 .


使用量
import { lcFirst } from '@alessiofrittoli/web-utils'

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

toCamelCase

将字符串转换为骆驼Case .

参数
参数类型说明
inputstring要转换的输入字符串 .

回返

类型 : string

转换为骆驼Case的字符串 .


使用量
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 字符串 .

参数
参数类型说明
inputstring要转换的输入字符串 .

回返

类型 : string

转换为 kebab 的字符串 .


使用量
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

字符串值 .

参数
参数类型说明
inputany字符串的值 .

回返

类型 : string

字符串 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: ''

parseValue

解析字符串值 .

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

参数
参数类型说明
inputstring分析的价值.

回返

类型 : T | undefined

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

使用量
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

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

type ParameterizedValue = string | boolean | number | bigint
Parameterized

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

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

公用事业类型

医生马上就来了


核证公用事业

医生马上就来了

公用事业

医生马上就来了


浏览器 API 工具

getMediaMatches

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

参数
参数类型说明
querystring媒体查询字符串要检查 .

回返

类型 : boolean

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

使用量
检查当前设备是否面向地貌
import { getMediaMatches } from '@alessiofrittoli/web-utils'

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

openBrowserPopUp

在浏览器 PopUp 中打开网页.

这个 openBrowserPopUp 用途 Window.open() 但提供默认选项 让你的工作更容易.

[尖叫声]

需要安装以下软件包:

参数
参数类型默认说明
optionsOpenBrowserPopUpOptions- 说吧定义自定义弹出选项的对象 .
options.urlUrlInput- 说吧要加载的资源的 URL 或路径 。 见 用户输入 需要更多关于公认格式的信息.
options.widthnumber600弹出宽度.
options.heightnumber800弹出地高.
options.contextstring- 说吧一个字符串,没有空白,指定正在装入资源的浏览上下文的名称.
options.featuresOptionsFeatures- 说吧额外的自定义 PopUp 特性 .

回返

类型 : WindowProxy | null

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

使用量
重聚焦先前打开的弹出
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' },
    },
  })
}

重新使用弹出
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',
  })
}

文档图片

[尖叫声]

需要安装以下软件包:

类型
OpenDocumentPictureInPictureOptions

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

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

OpenDocumentPictureInPicture

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

属性
财产类型说明
windowWindow文档 Picture 窗口内的浏览上下文 .

isDocumentPictureInPictureSupported

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

回返

类型 : boolean

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

实例
import { isDocumentPictureInPictureSupported } from "@alessiofrittoli/web-utils/picture-in-picture";

if ( isDocumentPictureInPictureSupported() ) {
  ...
}

requiresDocumentPictureInPictureAPI

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

  • 扔出一个新的 Exception 有代码 ErrorCode.DOCUMENT_PIP_NOT_SUPPORTED 如果文档中的图片不支持 API.
实例
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.
参数
参数类型说明
optionsOpenDocumentPictureInPictureOptions打开新文档相册窗口的配置选项 .

回返

类型 : Promise<OpenDocumentPictureInPicture>

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

实例
简单使用
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)
    }
  }
}

装入渲染屏蔽样式
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 否则.

使用量
检查当前设备是否面向地貌
import { isPortrait } from '@alessiofrittoli/web-utils'

console.log(!isPortrait())

网络信息
类型
Connection 接口

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

属性
财产类型说明
networkNetworkInformation这个 NetworkInformation 接口 网络信息 API
提供设备用于通信的连接信息
与网络连接,并提供一个在连接类型发生变化时通知脚本的手段.
* 可用性有限 见完全兼容
onLineboolean显示设备是否连接到网络.
- 看到没 正在监听网络状态的变化。 。 。 .

getConnection

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

回返

类型 : Connection

定义网络状态的对象和 NetworkInformation。见 Connection 用于更多信息的接口.


实例
import { getConnection } from '@alessiofrittoli/web-utils'

const { network } = getConnection()

console.log(network?.effectiveType)

储存公用事业

[尖叫声]

需要安装以下软件包:

导入enum和类型
import type { RawCookie, ParsedCookie, ParsedCookieMap } from '@alessiofrittoli/web-utils/cookie'
import { Priority, SameSite } from '@alessiofrittoli/web-utils/cookie'

数字
Priority 数字

Cookie优先级.

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

SameSite 数字

控制是否发送有跨地点请求的饼干,为防范跨地点请求的伪造袭击提供某种保护(中国证监会) (中文(简体) ).

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

类型
RawCookie<K, V>

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

属性
财产类型说明
nameK饼干的名字.
valueVCookie的价值.
domainstring定义寄出饼干的主机.
expiresstring | number | Date表示饼干的最大寿命.
httpOnlyboolean禁止 JavaScript 访问 cookie, 例如通过 Document.cookie 属性.
maxAgenumber表示到饼干到期为止的秒数。 如果设定, expires 被忽略.
partitionedboolean表示饼干应该使用分块存储来存储.
pathstring指定浏览器发送时必须在请求的 URL 中存在的路径 Cookie 头曰.
sameSiteSameSite控制是否发送有跨地点请求的饼干,为防范跨地点请求的伪造袭击提供某种保护(中国证监会) (中文(简体) ).
secureboolean指出饼干只有在与 https: scheme 请求时才会发送到服务器.
priorityPriority定义 Cookie 优先级 .

ParsedCookie<K, V>

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

属性
财产类型说明
expiresDate表示饼干的最大寿命.

ParsedCookieMap<K, V>

地图上的Cookie.


静态方法
Cookie.parse<K, V>()

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

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

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

回返

类型 : ParsedCookieMap<K, V>

解析的Cookie地图.


使用量
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饼干值的类型 .

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

回返

类型 : string

已串起的 Cookie 准备储存 .


使用量
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预期的饼干价值类型 .

参数
参数类型说明
cookiestring饼干串.

调试

版本与发布记录

@alessiofrittoli/web-utils 共发布 52 个版本,首次发布于 2025/01/07;过去 12 个月发布了 19 个版本。

版本发布日期距今
3.0.0latest2026/10/2612 天前
3.0.0-alpha.3alpha2026/10/2612 天前
3.0.0-alpha.22026/10/2612 天前
3.0.0-alpha.12026/10/2613 天前
2.5.02026/10/2613 天前
2.4.02026/10/1721 天前

关于 @alessiofrittoli/web-utils 的常见问题

@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 和提交记录判断。