Media Capture and Streams API

Media Capture and Streams API 用于处理视频音频流,以及枚举本地媒体设备,它与 WebRTC API 息息相关

枚举本地媒体设备

该部分 API 主要提供了枚举本地媒体设备的功能,包括媒体输入设备或媒体输出设备,通过 Navigator 接口的 mediaDevices 只读属性暴露的 MediaDevices 实例使用

通过调用 MediaDevices 接口的 enumerateDevices() 方法获取本地媒体设备列表

方法返回一个 Promise 的 MediaDeviceInfo 数组

调用该方法会受到 microphonecamera 权限策略的限制,并且要求文档处于完全活跃状态并且当前可见

默认调用该方法仅会返回系统默认媒体设备,返回具体设备受到 microphonecamera 权限 API 的限制

    监听本地媒体设备变化

    当本地媒体设备列表改变时(如新的媒体设备连接到系统,或已有媒体设备从系统中移除),MediaDevices 接口上的 devicechange 事件会被触发,方法返回一个 Event 事件

    此时可以再次调用 MediaDevices 接口的 enumerateDevices() 方法更新本地媒体设备列表

    本地媒体设备信息

    MediaDeviceInfo 接口表示一个本地媒体设备;特别的,InputDeviceInfo 接口表示一个本地媒体输入设备

    MediaDeviceInfo 接口的 deviceId 只读属性返回一个字符串,代表本地媒体设备的唯一标识

    MediaDeviceInfo 接口的 groupId 只读属性返回一个字符串,代表本地媒体设备的组标识,对于同一物理设备的不同媒体设备的该值相同

    MediaDeviceInfo 接口的 kind 只读属性返回一个字符串枚举,值为 videoinput audioinput audiooutput 之一,代表本地媒体设备的类型

    MediaDeviceInfo 接口的 label 只读属性返回一个字符串,代表本地媒体设备的描述,可用于向用户展示

    MediaDeviceInfo 接口的 toJSON() 方法是一个序列化方法,对该媒体设备信息序列化后返回一个普通对象

    InputDeviceInfo 接口的 getCapabilities() 方法描述原始音频或视频轨道的信息,返回一个 MediaTrackCapabilities 结构的对象;若未授予相应的权限,空对象将被返回

    MediaTrackCapabilities 结构参见如下媒体参数章节

    检测用户代理支持参数

    调用 MediaDevices 接口的 getSupportedConstraints() 方法获取用户代理支持识别的参数列表,返回一个 MediaTrackSupportedConstraints 结构的对象,对象的键名为所有受支持的参数列表,键值为 true

    MediaTrackSupportedConstraints 结构参见如下媒体参数章节

      获取本地媒体设备输入流

      调用 MediaDevices 接口的 getUserMedia() 方法从本地媒体设备获取输入流

      也可以使用该方法来请求本地媒体设备的权限,包括麦克风 microphone 权限与摄像头 camera 权限

      方法接收一个 MediaStreamConstraints 结构的对象

      方法返回一个兑现包含 MediaStream 实例的 Promise

      若未传入参数或传入对象参数包含任一 audio 参数或 video 参数,或传入对象参数包含不允许的参数,抛出 TypeError

      若文档未处于完全激活状态,抛出 InvalidStateError

      若请求媒体资源类型在当前浏览上下文中被阻止(如受权限策略限制),或被权限 API 拒绝,抛出 NotAllowedError

      若无法获取满足条件的媒体轨道,抛出 NotFoundError

      若不存在符合约束条件的候选设备,抛出 OverconstrainedError

      若因为操作系统/程序/网页锁定设备导致无法从设备读取流信息,抛出 NotReadableError

      若因为其他原因无法从设备读取流信息,抛出 AbortError

      MediaStreamConstraints 结构如下:

      audio 参数表示音频轨道相关信息,可以为一个布尔值(指定是否必须包含该轨道)或一个 MediaTrackConstraints 结构的对象

      video 参数表示视频轨道相关信息,可以为一个布尔值(指定是否必须包含该轨道)或一个 MediaTrackConstraints 结构的对象

      MediaTrackConstraints 结构继承自 MediaTrackConstraintSet 结构

      advanced 参数表示一个 MediaTrackConstraintSet 结构的对象的数组

      MediaTrackConstraintSet 结构参见如下媒体参数章节

      OverconstrainedError 异常继承自 DOMException,常用于表示所需的功能集无法满足当前 MediaStreamTrack

      constraint 只读属性返回一个字符串,表示未满足的约束

      媒体参数

      • width 参数表示视频轨道的宽度
      • height 参数表示视频轨道的高度
      • aspectRatio 参数表示视频轨道的宽高比
      • frameRate 参数表示视频轨道的帧速
      • facingMode 参数表示视频轨道的摄像头朝向参数
      • resizeMode 参数表示视频轨道的可裁剪模式
      • sampleRate 参数表示音频轨道的采样率
      • sampleSize 参数表示音频轨道的样本大小
      • echoCancellation 参数表示音频轨道的是否可进行回声消除
      • autoGainControl 参数表示音频轨道的是否可进行自动增益控制
      • noiseSuppression 参数表示音频轨道的是否可进行噪声抑制
      • latency 参数表示音频轨道的延迟时间
      • channelCount 参数表示音频轨道的通道数
      • deviceId 参数表示轨道相关的 deviceId 属性
      • groupId 参数表示轨道相关的 groupId 属性

      这些参数可被如下一些结构使用:

      • MediaTrackSupportedConstraints 结构,表示受到用户代理支持的约束参数
        • MediaDevices.getSupportedConstraints() 方法
      • MediaTrackConstraintSet 结构
      • MediaTrackConstraints 结构(继承 MediaTrackConstraintSet 结构),表示开发者配置的约束参数范围
        • MediaDevices.getDisplayMedia() 方法
        • MediaDevices.getUserMedia() 方法
        • MediaStreamTrack.getConstraints() 方法
        • MediaStreamTrack.applyConstraints() 方法
      • MediaTrackSettings 结构,表示用户代理实际使用的约束参数
        • MediaStreamTrack.getSettings() 方法
      • MediaTrackCapabilities 结构,表示用户代理支持的约束参数范围
        • MediaStreamTrack.getCapabilities() 方法
        • InputDeviceInfo.getCapabilities() 方法

      并且这些结构通过 Screen Capture API 和 MediaStream Image Capture API 被拓展

      媒体流

      MediaStream 接口表示一个媒体流,它可包含多个媒体轨道(音频轨道与视频轨道),它支持对其包含的媒体轨道的枚举、获取、增加及删除,以及对自身的创建和克隆等

      创建媒体流

      可以通过 MediaDevices.getUserMedia() MediaDevices.getDisplayMedia() HTMLCanvasElement.captureStream() HTMLMediaElement.captureStream() 等方法创建对应的媒体流

      亦可以调用 MediaStream() 构造方法创建新媒体流

      构造方法可以不传任何参数,创建一个空的媒体流

      构造方法可以传一个 MediaStream 实例参数,创建的媒体流会与传入参数的媒体流共享使用所有媒体轨道

      构造方法可以传一个 MediaStreamTrack 数组参数,创建的媒体流会使用所有传入的媒体轨道

      媒体流信息

      MediaStream 接口的 id 只读属性返回媒体流的一个唯一的 32 位标识符 UUID

      MediaStream 接口的 active 只读属性标识媒体流当前是否处于活跃状态

      媒体流是否处于活跃状态,取决于其包含的所有媒体轨道是否结束(readyState 属性是否被置为 ended

      克隆媒体流

      MediaStream 接口的 clone() 方法克隆当前媒体流,同时会克隆其包含的所有媒体轨道,返回的新媒体流具有与原媒体流不同的 ID

      增加媒体轨道

      MediaStream 接口的 addtrack() 方法向媒体流中增加给定媒体轨道,需要传入一个 MediaStreamTrack 实例参数;若给定媒体轨道已在媒体流中,调用该方法不会产生效果

      MediaStream 接口的 addtrack 事件在媒体流中增加媒体轨道时触发,返回一个 MediaStreamTrackEvent 事件

      移除媒体轨道

      MediaStream 接口的 removetrack() 方法向媒体流中移除给定媒体轨道,需要传入一个 MediaStreamTrack 实例参数;若给定媒体轨道未在媒体流中,调用该方法不会产生效果

      MediaStream 接口的 removetrack 事件在媒体流中移除媒体轨道时触发,返回一个 MediaStreamTrackEvent 事件

      媒体轨道改变事件

      MediaStreamTrackEvent 事件表示媒体流的改变

      track 只读属性表示产生该变化的媒体轨道,返回一个 MediaStreamTrack 实例

      获取媒体轨道

      MediaStream 接口的 getTrackById() 方法获取媒体流中给定 ID 的媒体轨道,若存在则返回一个 MediaStreamTrack 实例,反之 null 被返回

      MediaStream 接口的 getAudioTracks() 方法获取媒体流中所有音频轨道,返回一个 MediaStreamTrack 数组

      MediaStream 接口的 getVideoTracks() 方法获取媒体流中所有视频轨道,返回一个 MediaStreamTrack 数组

      MediaStream 接口的 getTracks() 方法获取媒体流中所有媒体轨道,返回一个 MediaStreamTrack 数组

      媒体轨道

      MediaStreamTrack 接口表示表示一个媒体轨道,它支持对自身的克隆和暂停及获取或设置自身的配置等

      媒体轨道信息

      MediaStreamTrack 接口的 id 只读属性返回媒体轨道的一个唯一的 32 位标识符 UUID

      MediaStreamTrack 接口的 kind 只读属性返回媒体轨道的类型,值为 audio 代表音频轨道,值为 video 代表视频轨道

      MediaStreamTrack 接口的 label 只读属性返回媒体轨道的标签,值由用户代理生成

      媒体轨道使用状态

      MediaStreamTrack 接口的 muted 只读属性指示媒体轨道当前是否支持提供媒体数据

      MediaStreamTrack 接口的 mute 事件在媒体轨道的源无法提供媒体数据时触发,返回一个 Event 事件

      MediaStreamTrack 接口的 unmute 事件在媒体轨道的源再次能够提供媒体数据时触发,返回一个 Event 事件

      MediaStreamTrack 接口的 enabled 属性读取或设置媒体轨道是否允许提供媒体数据;对音频轨道而言,样本值被置为 0;对视频轨道而言,像素值均为黑色

      媒体轨道运行状态

      MediaStreamTrack 接口的 readyState 只读属性返回当前媒体轨道的状态,值 live 指示媒体轨道正常运行,值 ended 指示媒体轨道已终止提供数据

      MediaStreamTrack 接口的 stop() 方法终止当前媒体轨道,并且 readyState 属性值会置为 ended,但 ended 事件不会被触发

      MediaStreamTrack 接口的 ended 事件在媒体轨道对应资源终止提供媒体数据时触发

      克隆媒体轨道

      MediaStreamTrack 接口的 clone() 方法克隆当前媒体轨道,返回的新媒体轨道具有与原媒体轨道不同的 ID

      媒体轨道参数

      MediaStreamTrack 接口的 getConstraints() 方法读取媒体轨道的约束属性,返回一个 MediaTrackConstraints 结构的对象

      MediaStreamTrack 接口的 applyConstraints() 方法向媒体轨道应用约束属性,需要传递一个 MediaTrackConstraints 结构的对象参数,返回一个 Promise

      MediaStreamTrack 接口的 getCapabilities() 方法读取媒体轨道的允许受约束属性值,返回一个 MediaTrackCapabilities 结构的对象

      MediaStreamTrack 接口的 getSettings() 方法读取媒体轨道的受约束属性(包含由操作系统指定的默认值),返回一个 MediaTrackSettings 结构的对象

      MediaTrackSettings 结构参见如上媒体参数章节

      权限策略

      该 API 调用受到 microphone 权限策略或 camera 权限策略的控制,可以通过 Permissions-Policy 响应头指定,或通过 <iframe> 标签的 allow 属性指定

      默认值均是 self,即允许在当前源的浏览上下文使用该 API

      权限 API

      该 API 调用需要用户授予 microphone 权限或 camera 权限,可以调用 Permission.query() 方法检查用户是否已授予了该权限

      camera 权限的描述符的额外参数 panTiltZoom,值 true 比值 false 具有更高的优先级

      类型

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      115
      116
      117
      118
      119
      120
      121
      122
      123
      124
      125
      126
      127
      128
      129
      130
      131
      132
      133
      134
      135
      136
      137
      138
      139
      140
      141
      142
      143
      144
      145
      146
      147
      148
      149
      150
      151
      152
      153
      154
      155
      156
      157
      158
      159
      160
      161
      162
      163
      164
      165
      166
      167
      168
      169
      170
      171
      172
      173
      174
      175
      176
      177
      178
      179
      interface MediaDevices extends EventTarget {
      enumerateDevices(): Promise<MediaDeviceInfo[]>
      getSupportedConstraints(): MediaTrackSupportedConstraints
      getUserMedia(constraints?: MediaStreamConstraints): Promise<MediaStream>
      ondevicechange: ((this: MediaDevices, ev: Event) => any) | null
      }

      declare var MediaDevices: {
      prototype: MediaDevices
      }

      interface MediaDeviceInfo {
      readonly deviceId: string
      readonly groupId: string
      readonly kind: MediaDeviceKind
      readonly label: string
      toJSON(): any
      }

      declare var MediaDeviceInfo: {
      prototype: MediaDeviceInfo
      new(): MediaDeviceInfo
      }

      interface InputDeviceInfo extends MediaDeviceInfo {
      getCapabilities(): MediaTrackCapabilities
      }

      declare var InputDeviceInfo: {
      prototype: InputDeviceInfo
      new(): InputDeviceInfo
      }

      interface OverconstrainedError extends DOMException {
      readonly constraint: string
      }

      declare var OverconstrainedError: {
      prototype: OverconstrainedError
      new(constraint: string, message?: string): OverconstrainedError
      }

      interface MediaStream extends EventTarget {
      readonly active: boolean
      readonly id: string
      addTrack(track: MediaStreamTrack): void
      clone(): MediaStream
      getAudioTracks(): MediaStreamTrack[]
      getTrackById(trackId: string): MediaStreamTrack | null
      getTracks(): MediaStreamTrack[]
      getVideoTracks(): MediaStreamTrack[]
      removeTrack(track: MediaStreamTrack): void
      onaddtrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null
      onremovetrack: ((this: MediaStream, ev: MediaStreamTrackEvent) => any) | null
      }

      declare var MediaStream: {
      prototype: MediaStream
      new(): MediaStream
      new(stream: MediaStream): MediaStream
      new(tracks: MediaStreamTrack[]): MediaStream
      }

      interface MediaStreamTrack extends EventTarget {
      contentHint: string
      enabled: boolean
      readonly id: string
      readonly kind: string
      readonly label: string
      readonly muted: boolean
      readonly readyState: MediaStreamTrackState
      applyConstraints(constraints?: MediaTrackConstraints): Promise<void>
      clone(): MediaStreamTrack
      getCapabilities(): MediaTrackCapabilities
      getConstraints(): MediaTrackConstraints
      getSettings(): MediaTrackSettings
      stop(): void
      onended: ((this: MediaStreamTrack, ev: Event) => any) | null
      onmute: ((this: MediaStreamTrack, ev: Event) => any) | null
      onunmute: ((this: MediaStreamTrack, ev: Event) => any) | null
      }

      declare var MediaStreamTrack: {
      prototype: MediaStreamTrack
      }

      interface MediaStreamTrackEvent extends Event {
      readonly track: MediaStreamTrack
      }

      declare var MediaStreamTrackEvent: {
      prototype: MediaStreamTrackEvent
      new(type: string, eventInitDict: MediaStreamTrackEventInit): MediaStreamTrackEvent
      }

      interface MediaStreamTrackEventInit extends EventInit {
      track: MediaStreamTrack
      }

      type MediaDeviceKind = 'audioinput' | 'audiooutput' | 'videoinput'

      interface MediaTrackCapabilities {
      aspectRatio?: DoubleRange
      autoGainControl?: boolean[]
      channelCount?: ULongRange
      deviceId?: string
      displaySurface?: string
      echoCancellation?: boolean[]
      facingMode?: string[]
      frameRate?: DoubleRange
      groupId?: string
      height?: ULongRange
      noiseSuppression?: boolean[]
      sampleRate?: ULongRange
      sampleSize?: ULongRange
      width?: ULongRange
      }

      interface MediaTrackSupportedConstraints {
      aspectRatio?: boolean
      autoGainControl?: boolean
      channelCount?: boolean
      deviceId?: boolean
      displaySurface?: boolean
      echoCancellation?: boolean
      facingMode?: boolean
      frameRate?: boolean
      groupId?: boolean
      height?: boolean
      noiseSuppression?: boolean
      sampleRate?: boolean
      sampleSize?: boolean
      width?: boolean
      }

      interface MediaStreamConstraints {
      audio?: boolean | MediaTrackConstraints
      peerIdentity?: string
      preferCurrentTab?: boolean
      video?: boolean | MediaTrackConstraints
      }

      interface MediaTrackConstraintSet {
      aspectRatio?: ConstrainDouble
      autoGainControl?: ConstrainBoolean
      channelCount?: ConstrainULong
      deviceId?: ConstrainDOMString
      displaySurface?: ConstrainDOMString
      echoCancellation?: ConstrainBoolean
      facingMode?: ConstrainDOMString
      frameRate?: ConstrainDouble
      groupId?: ConstrainDOMString
      height?: ConstrainULong
      noiseSuppression?: ConstrainBoolean
      sampleRate?: ConstrainULong
      sampleSize?: ConstrainULong
      width?: ConstrainULong
      }

      interface MediaTrackConstraints extends MediaTrackConstraintSet {
      advanced?: MediaTrackConstraintSet[]
      }

      interface MediaTrackSettings {
      aspectRatio?: number
      autoGainControl?: boolean
      channelCount?: number
      deviceId?: string
      displaySurface?: string
      echoCancellation?: boolean
      facingMode?: string
      frameRate?: number
      groupId?: string
      height?: number
      noiseSuppression?: boolean
      sampleRate?: number
      sampleSize?: number
      width?: number
      }

      链接

      URL Pattern API

      URL Pattern API 允许创建 URL 规则匹配器,用于匹配 URL 或 URL 相关组件

      创建匹配器

      直接调用 URLPattern() 构造函数来创建一个匹配器

      构造函数允许接收一个字符串参数,需要是一个代表绝对路径或相对路径 URL 的字符串

      构造函数允许接收两个字符串参数,需要是一个代表基础 URL 的字符串(对第一个参数是相对路径 URL 的情况是必需的)

      构造函数亦可替代地接收一个对象参数,各可选参数分别代表 URL 的各个部分,包括 protocol username password hostname port pathname search hash baseURL,若不指定等价于指定为通配符 *

      构造函数还可以接收一个可选的配置项参数,其唯一参数 ignoreCase 接收一个布尔值,指定匹配时是否忽略字母大小写

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      new URLPattern("https://example.com/books/:id")

      new URLPattern("/books/:id", "https://example.com")

      new URLPattern({
      protocol: "https",
      hostname: "example.com",
      pathname: "/books/:id",
      })

      new URLPattern({
      pathname: "/books/:id",
      baseURL: "https://example.com",
      })

      new URLPattern({
      protocol: "http{s}?",
      username: ":username",
      password: ":password",
      hostname: ":subdomain.example.com",
      port: ":port(80|443)",
      pathname: "/:path",
      search: "*",
      hash: "*",
      }, {
      ignoreCase: true,
      })

      匹配器参数

      URLPattern 接口的 hash 只读属性返回一个 string,代表 URL 的片段标识符匹配参数

      URLPattern 接口的 hostname 只读属性返回一个 string,代表 URL 的主机名匹配参数

      URLPattern 接口的 password 只读属性返回一个 string,代表 URL 的密码匹配参数

      URLPattern 接口的 pathname 只读属性返回一个 string,代表 URL 的路径匹配参数

      URLPattern 接口的 port 只读属性返回一个 string,代表 URL 的端口匹配参数

      URLPattern 接口的 protocol 只读属性返回一个 string,代表 URL 的协议匹配参数

      URLPattern 接口的 search 只读属性返回一个 string,代表 URL 的搜索参数匹配参数

      URLPattern 接口的 username 只读属性返回一个 string,代表 URL 的用户匹配参数

      使用匹配器

      URLPattern 接口的 test() 方法用于测试给定 URL 是否符合匹配器的规则,返回一个布尔值

      URLPattern 接口的 exec() 方法用于返回给定 URL 经匹配器的规则执行的匹配组,返回一个代表匹配结果的对象或 null,其 inputs 键返回传入的参数,其余分别为 URLPattern 接口的属性构成的匹配组

      两方法均可接收一个字符串或对象参数,代表待匹配 URL;第二个参数接收一个字符串,但首个参数为相对路径的 URL 时是必需的

      匹配语法

      匹配语法很大一部分来自 path-to-regexp

      直接匹配

      1
      2
      3
      const pattern = new URLPattern({ pathname: "/books" });
      console.log(pattern.test("https://example.com/books")); // true
      console.log(pattern.exec("https://example.com/books").pathname.groups); // {}

      通配符匹配

      1
      2
      3
      const pattern = new URLPattern({ pathname: "/books/*" });
      console.log(pattern.test("https://example.com/books/123")); // true
      console.log(pattern.exec("https://example.com/books/123").pathname.groups); // { 0: '123' }

      命名组匹配

      1
      2
      3
      const pattern = new URLPattern({ pathname: "/books/:id" });
      console.log(pattern.test("https://example.com/books/123")); // true
      console.log(pattern.exec("https://example.com/books/123").pathname.groups); // { id: '123' }

      正则表达式匹配

      1
      2
      3
      4
      const pattern = new URLPattern("/books/:id(\\d+)", "https://example.com");
      console.log(pattern.test("https://example.com/books/123")); // true
      console.log(pattern.test("https://example.com/books/abc")); // false
      console.log(pattern.test("https://example.com/books/")); // false

      类型

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      type URLPatternInput = USVString | URLPatternInit

      interface URLPattern {
      test(input?: URLPatternInput, baseURL?: USVString): boolean

      exec(input?: URLPatternInput, baseURL?: USVString): URLPatternResult | null

      readonly protocol: string
      readonly username: string
      readonly password: string
      readonly hostname: string
      readonly port: string
      readonly pathname: string
      readonly search: string
      readonly hash: string

      readonly hasRegExpGroups: boolean
      }

      declare var URLPattern: {
      prototype: URLPattern
      new (input: URLPatternInput, baseURL: string, options?: URLPatternOptions): URLPattern
      new (input: URLPatternInput, options?: URLPatternOptions): URLPattern
      }

      interface URLPatternInit {
      protocol: string
      username: string
      password: string
      hostname: string
      port: string
      pathname: string
      search: string
      hash: string
      baseURL: string
      }

      interface URLPatternOptions {
      ignoreCase?: boolean
      }

      interface URLPatternResult {
      inputs: Array<URLPatternInput>

      protocol: URLPatternComponentResult
      username: URLPatternComponentResult
      password: URLPatternComponentResult
      hostname: URLPatternComponentResult
      port: URLPatternComponentResult
      pathname: URLPatternComponentResult
      search: URLPatternComponentResult
      hash: URLPatternComponentResult
      }

      interface URLPatternComponentResult {
      input: string
      groups: Record<string, string | undefined>
      }

      链接

      URL API

      URL API 用于表示一个互联网资源的定位标识(URL 即 Uniform Resource Locator)

      创建 URL

      调用 URL() 构造函数以创建一个新的 URL 实例

      方法需要传递一个 string 参数,代表 URL 字符串

      方法可以传递一个可选的 string 参数,代表 URL 的基础路径;若前一个参数为绝对路径,则当前参数会被忽略;若前一个参数为相对路径,则当前参数会作为基础的 URL

      若传递的参数无法用于创建 URL,会抛出 TypeError 异常

      可以调用 URL 接口的 canParse() 静态方法检测参数是否支持创建 URL,该方法与 URL() 构造函数接收相同的参数

      URL 参数

      URL 接口的各属性表现 URL 的各项参数,部分参数与 Location 接口的对应参数类型相同

      URL 接口的 hash 属性返回一个 string,代表 URL 的片段标识符,包含 # 符号

      URL 接口的 host 属性返回一个 string,代表 URL 的主机(包含主机名及端口)

      URL 接口的 hostname 属性返回一个 string,代表 URL 的主机名

      URL 接口的 href 属性返回一个 string,代表 URL 本身

      URL 接口的 origin 只读属性返回一个 string,代表 URL 的源

      URL 接口的 password 属性返回一个 string,代表 URL 的密码

      URL 接口的 pathname 属性返回一个 string,代表 URL 的路径

      URL 接口的 port 属性返回一个 string,代表 URL 的端口

      URL 接口的 protocol 属性返回一个 string,代表 URL 的协议,包含 : 符号

      URL 接口的 search 属性返回一个 string,代表 URL 的搜索参数,包含 ? 符号

      URL 接口的 username 属性返回一个 string,代表 URL 的用户

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      const url = new URL('https://username:password@website.example.com:8888/path1/path2?key1=value1&key2=value2#hash')
      console.log(url.hash) // #hash
      console.log(url.host) // website.example.com:8888
      console.log(url.hostname) // website.example.com
      console.log(url.href) // https://username:password@website.example.com:8888/path1/path2?key1=value1&key2=value2#hash
      console.log(url.origin) // https://website.example.com:8888
      console.log(url.password) // password
      console.log(url.pathname) // /path1/path2
      console.log(url.port) // 8888
      console.log(url.protocol) // https:
      console.log(url.search) // ?key1=value1&key2=value2
      console.log(url.username) // username

      URL 接口的 searchParams 只读属性返回一个 URLSearchParams,代表 URL 的搜索参数

      URL 转换

      URL 接口的 toJSON() 方法返回 URL 的 JSON 版本,等价于获取 URL 接口的 href 属性

      URL 接口的 toString() 方法返回 URL 的字符串版本,等价于获取 URL 接口的 href 属性

      URL 参数

      URLSearchParams 接口专门用于处理 URL 参数

      URLSearchParams() 构造函数用于创建一个 URL 参数对象,可以可选地传递一个字符串或键值对对象或字符串二维数组

      URLSearchParams 接口与 Map 对象类似,其 size 属性、delete() 方法、entries() 方法、forEach() 方法、get() 方法、has() 方法、keys() 方法、set() 方法、values() 方法 均与 Map 对象的对应方法类似

      URLSearchParams 接口的 append() 方法用于追加 URL 参数键值对(与 set() 方法区别是 set() 方法若已存在对应的值会直接覆盖)

      URLSearchParams 接口的 getAll() 方法用于获取给定 URL 参数键对应的所有 URL 值,返回一个字符串数组(与 get() 方法区别是 get() 方法仅获取首个匹配的值)

      URLSearchParams 接口的 toString() 方法用于返回给定的 URL 参数字符串,特别注意的是其不返回 ? 符号,与 URL 接口的 search 属性、HTMLAnchorElement 接口的 search 属性、Location 接口的 search 属性不同

      URLSearchParams 接口的 sort() 方法用于对 URL 参数进行排序,排序规则是按照 Unicode 编码执行

      URLSearchParams 接口的 delete() 方法与 has() 方法允许传递可选的第二个参数,代表键值对的值,以更加精细地检测

      类型

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      interface URL {
      hash: string
      host: string
      hostname: string
      href: string
      toString(): string
      readonly origin: string
      password: string
      pathname: string
      port: string
      protocol: string
      search: string
      readonly searchParams: URLSearchParams
      username: string
      toJSON(): string
      }

      declare var URL: {
      prototype: URL
      new(url: string | URL, base?: string | URL): URL
      }

      type webkitURL = URL
      declare var webkitURL: typeof URL

      interface URLSearchParams {
      append(name: string, value: string): void
      delete(name: string): void
      get(name: string): string | null
      getAll(name: string): string[]
      has(name: string): boolean
      set(name: string, value: string): void
      sort(): void
      toString(): string
      forEach(callbackfn: (value: string, key: string, parent: URLSearchParams) => void, thisArg?: any): void
      }

      declare var URLSearchParams: {
      prototype: URLSearchParams
      new(init?: string[][] | Record<string, string> | string | URLSearchParams): URLSearchParams
      }

      链接

      Speculation Rules API

      Speculation Rules API 设计以用于支持改善导航的性能,通过允许指定一系列规则以实现对未来文档资源的预加载

      它主要用于增强和改进 <link rel="prefetch"> 的功能以及替代仅由 Chrome 支持的 <link rel="prerender"> 非标准弃用特性,通过提供可配置的语法实现

      特别注意的是,它仅支持文档资源的加载,不支持子资源的加载,那种情况下应当使用 <link rel="prefetch">

      Speculation Rules 语法

      Speculation Rules 通过 <script type="speculationrules"> 指定,支持 JSON 格式的语法

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      <script type="speculationrules">
      {
      "prerender": [
      {
      "source": "list",
      "urls": ["extra.html", "extra2.html"]
      }
      ],
      "prefetch": [
      {
      "source": "list",
      "urls": ["next.html", "next2.html"],
      "requires": ["anonymous-client-ip-when-cross-origin"],
      "referrer_policy": "no-referrer"
      }
      ]
      }
      </script>

      需要注意的是,<script> 标签的 src async nomodule defer crossorigin integrityreferrerpolicy 等属性不应当指定

      整个 JSON 为一个对象,分别可以指定 prefetch 键和 prerender 键,均接收一个对象数组,分别代表提前获取文档资源及提前获取并加载渲染文档资源的规则

      规则对象需指定 source 键,代表指定当前规则的模式,目前唯一允许的值为 list,表示 URL 将来自一组列表

      规则对象需指定 urls 键,接收一个字符串数组,代表需要加载的资源 URL 的列表(相对路径觉得路径均可)

      规则对象可以指定 requires 键,代表指定解析规则的要求,目前唯一允许的值为 anonymous-client-ip-when-cross-origin,仅适用于 prefetch 场景,表示规则是否匹配与用户代理能否在跨域请求中避免向远程服务器暴露本地用户的 IP 地址

      规则对象可以指定 referrer_policy 键,代表获取资源时使用的 referrer policy,允许的值同 Referrer-Policy

      prefetch 与 prerender 比较

      prefetch 允许提前获取文档资源并缓存

      prefetch 相较于 <link rel="prefetch"> 可用于加载跨域页面且不受 Cache-Control 头影响

      prerender 允许提前获取文档资源并进行预渲染,包括获取并加载所有子资源,执行 JavaScript 以及获取及加载由 JavaScript 执行产生的子资源,绝大多数 API 会延迟执行直至页面被激活

      跨域的 prerender 要求文档资源的 Supports-Loading-Mode 响应头设定为 credentialed-prerender 以允许执行预加载

      prerender 相较于 <link rel="prerender"> 可用于加载跨域页面且不受 Cache-Control 头影响,并且其是标准且将得到未来大多数浏览器的支持,该特性是否有效受用户代理的设定的影响

      prefetch 与 prerender 检测

      服务端可通过 Sec-Purpose 请求头检测请求的文档是否为 prefetch 或 prerender

      对于 prefetch 而言:

      1
      Sec-Purpose: prefetch

      对于 prerender 而言:

      1
      Sec-Purpose: prefetch;prerender

      可以通过返回非 200 状态码和 304 状态码的响应来阻止 prefetch 或 prerender

      客户端可分别利用 PerformanceResourceTiming 接口的 deliveryType 属性 或 Document 接口的 prerendering 属性检测

      DOM 相关

      Document 接口的 prerendering 属性返回一个 boolean,表示当前文档是否在预渲染进程中

      Document 接口的 prerenderingchange 事件在预渲染文档被激活时触发(如用户访问当前文档),返回一个 Event

      HTTP 相关

      Supports-Loading-Mode 响应头允许启用多个高风险的加载模式

      目前仅支持值 credentialed-prerender 以允许跨域同站的预渲染模式

      Content Security Policy 相关

      允许在 Content Security Policy 中使用 inline-speculation-rules 值,以限制 <script type="speculationrules"> 的使用以控制资源加载

      链接

      View Transitions API

      View Transitions API 提供了创建视图过渡的功能

      目前该 API 仅支持在单 Document 中的视图过渡,尚未支持跨 Document 的视图过渡

      视图过渡进程

      1. 调用 Document 接口上的 startViewTransition() 方法
      2. 截取当前 DOM 的截图以作为视图过渡前的 old 状态
      3. 暂停 DOM 的渲染
      4. updateCallback 回调函数参数,若提供的话会被调用
      5. ViewTransition 接口的 updateCallbackDone 属性对应的 Promise 兑现
      6. 截取当前 DOM 的截图以作为视图过渡后的 new 状态
      7. 创建各视图过渡伪元素
      8. 重启 DOM 的渲染以渲染各视图过渡伪元素
      9. ViewTransition 接口的 ready 属性对应的 Promise 兑现
      10. 各视图过渡伪元素开始执行动画直至结束
      11. 移除各视图过渡伪元素
      12. ViewTransition 接口的 finished 属性对应的 Promise 兑现

      视图过渡结构

      通常情况下,视图过渡有关的伪元素的结构如下所示

      Text
      1
      2
      3
      4
      5
      ::view-transition
      └─ ::view-transition-group(root)
      └─ ::view-transition-image-pair(root)
      ├─ ::view-transition-old(root)
      └─ ::view-transition-new(root)

      可以通过指定 view-transition-name 属性来应用给定的动画

      1
      2
      3
      figcaption {
      view-transition-name: figure-caption;
      }

      此时视图过渡有关的伪元素的结构如下所示

      Text
      1
      2
      3
      4
      5
      6
      7
      8
      9
      ::view-transition
      ├─ ::view-transition-group(root)
      │ └─ ::view-transition-image-pair(root)
      │ ├─ ::view-transition-old(root)
      │ └─ ::view-transition-new(root)
      └─ ::view-transition-group(figure-caption)
      └─ ::view-transition-image-pair(figure-caption)
      ├─ ::view-transition-old(figure-caption)
      └─ ::view-transition-new(figure-caption)

      API 相关

      Document 接口的 startViewTransition() 方法用于创建视图过渡

      方法接收一个可选的 updateCallback 回调函数参数,该回调函数允许返回一个 Promise

      方法返回一个 ViewTransition 实例

      ViewTransition 接口反映了一个视图过渡

      ViewTransition 接口的 finished 属性返回一个 Promise,在视图过渡完成并且视图过渡伪元素完全移除时兑现,若 updateCallback 回调函数返回的 Promise 拒绝时拒绝

      ViewTransition 接口的 ready 属性返回一个 Promise,在视图过渡伪元素完成创建并且视图过渡将要开始时兑现,若 updateCallback 回调函数返回的 Promise 拒绝时或出现重复 view-transition-name 名称时拒绝

      ViewTransition 接口的 updateCallbackDone 属性返回一个 Promise,在 updateCallback 回调函数返回的 Promise 兑现时兑现,拒绝时拒绝

      ViewTransition 接口的 skipTransition() 方法可用于忽略执行视图过渡,但不会忽略执行传入的 updateCallback 回调函数参数

      CSS 相关

      view-transition-name 属性指定为 none 以使当前元素不应用视图过渡

      该属性的值在整个文档中必须唯一,不同元素不能拥有相同的值,否则视图过渡会被忽略

      ::view-transition 伪元素选择器作为视图过渡遮蔽层的根元素,包含其他视图过渡组(包含多个 ::view-transition-group 伪元素)

      ::view-transition-group 伪元素选择器表示单个视图过渡组,可以接收 * root 或一个视图过渡组名称(包含单个 ::view-transition-image-pair 伪元素)

      ::view-transition-image-pair 伪元素选择器代表单个视图过渡的视图截图容器,允许值同上

      ::view-transition-new 伪元素选择器代表单个视图过渡新的视图截图,允许值同上

      ::view-transition-old 伪元素选择器代表单个视图过渡旧的视图截图,允许值同上

      示例

      0 0 0 0 0 0 0 0 0

      类型

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      interface Document {
      startViewTransition(updateCallback?: UpdateCallback): ViewTransition
      }

      type UpdateCallback = () => Promise<any>

      interface ViewTransition {
      readonly updateCallbackDone: Promise<undefined>
      readonly ready: Promise<undefined>
      readonly finished: Promise<undefined>
      skipTransition(): void
      }

      链接

      Content Security Policy

      Content Security Policy 简称 CSP,可用于应对跨站脚本攻击(XSS 攻击)及数据包嗅探攻击

      在不指定 Content Security Policy 的情况下,浏览器会使用默认的同源策略

      Content Security Policy 语法

      通常是通过 Content-Security-Policy 响应头指定

      1
      Content-Security-Policy: <policy>

      或者通过 <meta> 标签指定

      1
      <meta http-equiv="Content-Security-Policy" content="<policy>" />

      使用 Content-Security-Policy-Report-Only 响应头可以指定仅报告但不阻碍执行的规则,该响应头需要与 report-to 指定同时使用,并且该响应头会继承 Content-Security-Policy 响应头的规则(除 sandbox 之外)

      Content Security Policy 指令

      Directive name Directive description
      default-src 作为其他 fetch 相关指令的来源的后备值
      child-src 限制 Worker 脚本资源和内嵌浏览上下文来源
      worker-src 限制 Worker 脚本资源来源
      frame-src 限制内嵌浏览上下文来源
      script-src 限制 JavaScript 脚本和 WebAssembly 来源
      script-src-elem 限制 JavaScript 的 <script> 标签来源
      script-src-attr 限制 JavaScript 脚本在行内事件回调方法来源
      style-src 限制样式表来源
      style-src-elem 限制样式表在 <style> 标签和 <link rel="stylesheet"> 来源
      style-src-attr 限制样式表在内联样式中来源
      manifest-src 限制应用 manifest 文件来源
      img-src 限制 image 和 favicon 来源
      media-src 限制 <audio> <video> <track> 的媒体资源来源
      object-src 限制 <object> <embed> 的资源来源
      font-src 限制 @font-face 加载的字体资源来源
      connect-src 限制脚本加载的资源来源
      base-uri 限制 <base> 标签的内容
      sandbox 设置沙箱策略(类似 <iframe> 标签的 sandbox 属性)
      form-action 限制表单提交后允许的提交目标
      frame-ancestors 限制允许内嵌 <frame> <iframe> <object> <embed> 的浏览上下文
      report-to 允许在违反 CSP 事件发生时向指定源发送报告
      require-trusted-types-for 强制使用 Trusted Types 应对 XSS 攻击
      trusted-types 指定 Trusted Types 的允许指令列表
      upgrade-insecure-requests 强制将不安全链接升级为安全链接对待

      Content Security Policy 值

      Value name Value description
      none 不允许任何源的资源
      self 允许当前源的资源
      strict-dynamic 限制当前资源的规则应同时适用于其加载的资源
      report-sample 要求在报告中包含样例代码
      inline-speculation-rules 允许使用 speculation rules 脚本规则
      unsafe-eval 允许使用 eval 等动态执行代码方法
      wasm-unsafe-eval 允许使用加载执行 WebAssembly 模块(避免直接指定 unsafe-eval
      unsafe-hashes 允许使用特定的内联事件处理方法
      unsafe-inline 允许使用内联资源
      nonce-<base64-value> 允许 nonce 属性指定的标识符限制的资源
      <hash-algorithm>-<base64-value> 允许指定哈希算法(sha256 sha384 sha512)生成的标识符限制的资源
      <host-source> 允许给定的域的资源
      <scheme-source> 允许给定协议的资源

      Content Security Policy 示例

      1
      2
      3
      4
      5
      Content-Security-Policy: default-src 'self'
      Content-Security-Policy: default-src 'self' example.com *.example.com
      Content-Security-Policy: default-src 'self'; img-src *; media-src example.org example.net; script-src userscripts.example.com
      Content-Security-Policy: default-src https://onlinebanking.example.com
      Content-Security-Policy: default-src 'self' *.example.com; img-src *

      链接

      Visual Viewport API

      Visual Viewport API 提供了查询和监测屏幕可视区域的功能

      该 API 通过 Window 接口的 visualViewport 属性暴露的 VisualViewport 实例使用

      VisualViewport 概念

      Viewport 有两个相对的概念 —— Layout Viewport 和 Visual Viewport,Layout Viewport 包含当前文档用户可见的内容,而 Visual Viewport 仅包含当前文档用户当前可见的内容。例如,屏幕键盘等功能仅影响 Visual Viewport,不影响 Layout Viewport;缩放页面时,Visual Viewport 发生变化,而 Layout Viewport 不变

      获取 VisualViewport 信息

      主要通过 VisualViewport 接口的属性获取 Visual Viewport 信息

      VisualViewport 接口的 width 属性返回一个 number,表示 Visual Viewport 的宽度

      VisualViewport 接口的 height 属性返回一个 number,表示 Visual Viewport 的高度

      VisualViewport 接口的 offsetLeft 属性返回一个 number,表示 Visual Viewport 相对 Layout Viewport 左边缘的偏移量

      VisualViewport 接口的 offsetTop 属性返回一个 number,表示 Visual Viewport 相对 Layout Viewport 上边缘的偏移量

      VisualViewport 接口的 pageLeft 属性返回一个 number,表示 Visual Viewport 相对初始包含块的 x 坐标

      VisualViewport 接口的 pageTop 属性返回一个 number,表示 Visual Viewport 相对初始包含块的 y 坐标

      VisualViewport 接口的 resize 属性返回一个 number,表示 Visual Viewport 的缩放参数

      监听 VisualViewport 变化

      主要通过 VisualViewport 接口的事件监听 Visual Viewport 变化

      VisualViewport 接口的 resize 事件在 Visual Viewport 尺寸发生改变时触发

      VisualViewport 接口的 scroll 事件在 Visual Viewport 发生滚动时触发

      示例

      Width Height OffsetLeft OffsetTop PageLeft PageTop Scale
      0 0 0 0 0 0 0

      类型

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      interface Window {
      readonly visualViewport: VisualViewport
      }

      interface VisualViewport extends EventTarget {
      readonly offsetLeft: number
      readonly offsetTop: number

      readonly pageLeft: number
      readonly pageTop: number

      readonly width: number
      readonly height: number

      readonly scale: number

      onresize: ((this: VisualViewport, ev: Event) => any) | null
      onscroll: ((this: VisualViewport, ev: Event) => any) | null
      onscrollend: ((this: VisualViewport, ev: Event) => any) | null
      }

      链接

      Screen API

      Screen API 主要支持获取当前设备屏幕的一些信息

      该 API 通过 Window 接口的 screen 属性暴露的 Screen 实例使用

      屏幕信息

      Screen 接口的 height 属性返回一个 number,代表屏幕的高度

      Screen 接口的 width 属性返回一个 number,代表屏幕的宽度

      Screen 接口的 availHeight 属性返回一个 number,代表屏幕可用区域的高度

      Screen 接口的 availWidth 属性返回一个 number,代表屏幕可用区域的宽度

      Screen 接口的 colorDepth 属性返回一个 number,代表屏幕的颜色位深度

      Screen 接口的 pixelDepth 属性返回一个 number,代表屏幕的像素位深度

      类型

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      interface Window {
      readonly screen: Screen
      }

      interface Screen {
      readonly availHeight: number
      readonly availWidth: number
      readonly colorDepth: number
      readonly height: number
      readonly pixelDepth: number
      readonly width: number
      }

      declare var Screen: {
      prototype: Screen
      }

      链接

      Permissions Policy

      Permissions Policy 允许开发者定义在网页中控制功能的可用性,从而增加应用的安全性和隐私性

      Permissions Policy 与 Content Security Policy 类似,但其专注于控制功能特性而非内容

      需要注意的是 Permissions Policy 曾经被称为 Feature Policy,但其现在已重命名

      指定 Permissions Policy

      可以利用 Permissions-Policy 请求头来指定 Permissions Policy,或使用与之等价的 <meta> 标签

      可以利用 <iframe> 标签的 allow 属性给内嵌网页指定 Permissions Policy

      指定单个 Permissions Policy 时通常包含与之对应的一条指令与允许列表

      检测 Permissions Policy

      可以通过 Document 接口的 featurePolicy 属性或 HTMLIFrameElement 接口的 featurePolicy 属性暴露的 FeaturePolicy 实例检测 Permissions Policy 的状态

      注意:标准已将 FeaturePolicy 接口重命名为 PermissionsPolicy 接口, featurePolicy 属性重命名为 permissionsPolicy 属性

      FeaturePolicy 接口的 allowedFeatures() 方法获取当前用户代理在当前浏览上下文允许使用的所有特性

      FeaturePolicy 接口的 allowsFeature() 方法检测指定特性在指定的域下是否可用

      FeaturePolicy 接口的 features() 方法获取当前用户代理支持的所有特性

      FeaturePolicy 接口的 allowedFeatures() 方法列举当前用户代理设置的特性策略中指定特性允许使用的域

      Permissions Policy 与 Permissions API 的联系

      Permissions Policy 允许开发者设置权限的策略,而 Permissions API 允许用户授予权限

      Permissions Policy 指令

      Directive name Directive description
      accelerometer Accelerometer
      ambient-light-sensor AmbientLightSensor
      autoplay HTMLMediaElement.play() <audio> & <video> autoplay
      battery Battery Status API - Navigator.getBattery()
      camera video input devices MediaDevices.getUserMedia()
      display-capture MediaDevices.getDisplayMedia()
      document-domain set document.domain
      encrypted-media Encrypted Media Extensions API - Navigator.requestMediaKeySystemAccess()
      execution-while-not-rendered script execution of renderer status
      execution-while-out-of-viewport script execution of viewport status
      fullscreen Element.requestFullscreen()
      gamepad Gamepad API - Navigator.getGamepads() Window:gamepadconnected Window:gamepaddisconnected
      geolocation Geolocation API - Geolocation.getCurrentPosition() Geolocation.watchPosition()
      gyroscope Gyroscope
      hid WebHID API
      identity-credentials-get FedCM API
      idle-detection Idle Detection API
      local-fonts Local Font Access API - Window.queryLocalFonts()
      magnetometer Magnetometer
      microphone audio input devices MediaDevices.getUserMedia()
      midi Web MIDI API - Navigator.requestMIDIAccess()
      otp-credentials WebOTP API
      payment Payment Request API - PaymentRequest
      picture-in-picture Picture In Picture API
      publickey-credentials-create Web Authentication API
      publickey-credentials-get Web Authentication API
      screen-wake-lock Screen Wake Lock API
      serial Web Serial API
      speaker-selection Audio Output Devices API
      storage-access Storage Access API
      usb WebUSB API
      web-share Web Share API - Navigator.share()
      window-management Window Management API
      xr-spatial-tracking WebXR Device API

      Permissions Policy 允许列表

      • * 允许在顶层浏览上下文及其嵌入浏览上下文中使用
      • () 禁止在顶层浏览上下文及其嵌入浏览上下文中使用,在 <iframe> 标签的 allow 属性的值为 none
      • self 允许在顶层浏览上下文及其同源的嵌入浏览上下文中使用,禁止在嵌入的跨域的嵌入浏览上下文中使用
      • src 仅限在 <iframe> 标签的 allow 属性中使用,允许在当前嵌入浏览上下文中使用
      • <origin> 允许在指定源的浏览上下文中使用
      1
      2
      3
      4
      5
      6
      7
      8
      9
      *
      ()
      (self)
      (src)
      ("https://a.example.com")
      ("https://a.example.com" "https://b.example.com")
      (self "https://a.example.com" "https://b.example.com")
      (src "https://a.example.com" "https://b.example.com")
      ("https://*.example.com")

      Permissions-Policy 响应头语法

      基本语法

      1
      Permissions-Policy: <directive>=<allowlist>

      示例

      1
      2
      3
      Permissions-Policy: geolocation=()
      Permissions-Policy: geolocation=(self "https://a.example.com" "https://b.example.com")
      Permissions-Policy: picture-in-picture=(), geolocation=(self https://example.com), camera=*;

      另外值得注意的是,该响应头无法被编程式修改

      <iframe> 标签 allow 属性语法

      一般建议在 Permissions-Policy 响应头中指定相对宽泛的 Permissions Policy,并在对应内嵌浏览上下文中通过 <iframe> 标签 allow 属性指定更加严格的 Permissions Policy

      基本语法

      1
      <iframe src="<origin>" allow="<directive> <allowlist>"></iframe>

      示例

      1
      2
      3
      <iframe src="https://example.com" allow="geolocation 'none'"></iframe>
      <iframe src="https://example.com" allow="geolocation 'self' https://a.example.com https://b.example.com"></iframe>
      <iframe src="https://example.com" allow="geolocation 'self' https://a.example.com https://b.example.com; fullscreen 'none'"></iframe>

      链接

      Popover API

      Popover API 提供了标准化的显示弹出窗口的形式

      Popover API 可以通过 HTML 控制或通过 JavaScript 控制

      设置弹出元素

      向 HTML 元素指定 popover 属性,以将元素指定为可弹出的,值需要为 automanual 或空字符串之一

      auto 代表仅允许显示单个弹出窗口,允许自动关闭弹出窗口

      manual 代表允许显示多个弹出窗口,允许手动关闭弹出窗口

      1
      <div id="popover" popover="auto"></div>

      同样可以通过 HTMLElement 接口的 popover 属性指定

      1
      popoverElement.popover = 'auto';

      设置弹出元素的控制元素

      控制元素必须为 <button> 元素或 <input type="button" /> 元素

      向 HTML 元素指定 popovertarget 属性以设置控制元素控制的弹出元素,值是弹出元素的 id

      向 HTML 元素指定 popovertargetaction 属性以设置控制元素的控制行为,值为 hide show toggle 之一

      1
      <button popovertarget="popover" popovertargetaction="toggle">popover</button>

      同样可以通过 HTMLElement 接口的 popoverTargetElement 属性指定控制元素控制的弹出元素,值需要接受一个 HTMLElement

      同样可以通过 HTMLElement 接口的 popoverTargetAction 属性指定控制元素的控制行为

      1
      2
      targetElement.popoverTargetElement = popoverElement;
      targetElement.popoverTargetAction = 'toggle';

      控制弹出元素

      调用 HTMLElement 接口的 showPopover() 方法显示弹出窗口

      调用 HTMLElement 接口的 hidePopover() 方法隐藏弹出窗口

      showPopover() 方法与 hidePopover() 方法在已处于相应状态时会抛出 InvalidStateError 异常

      调用 HTMLElement 接口的 togglePopover() 方法切换弹出窗口

      togglePopover() 方法允许接受一个 force 参数,以指定期望的行为,但不会抛出异常;并且会返回执行的结果

      1
      2
      3
      popoverElement.showPopover();
      popoverElement.hidePopover();
      popoverElement.togglePopover();

      弹出元素事件

      beforetoggle 事件在元素的弹出状态改变前触发

      toggle 事件在元素的弹出状态改变后触发

      两事件均返回一个 ToggleEvent 事件,事件的 newState 属性和 oldState 属性返回 closedopen 之一

      弹出元素 CSS 相关

      可以利用 :popover-open 伪类选择器选中处于 popover 显示状态的元素

      可以利用 ::backdrop 伪元素选择器选中 top-layer 背后的内容并进行特殊的定制

      示例

      popover window

      链接


      :D 一言句子获取中...