Device Memory API

Device Memory API 允许获取运行内存容量的大小

JS 使用

通过 Navigator 接口或 WorkerNavigator 接口的 deviceMemory 只读属性使用

返回的值是一个 number 值,0.25 0.5 1 2 4 8

HTTP 使用

服务器在 Accept-CH 响应头中指定 Device-Memory 值,或通过 HTML <meta> 标签的 http-equiv 属性指定

1
Accept-CH: Device-Memory

之后用户代理会通过 Device-Memory 请求头携带对应的信息,具体值同 deviceMemory 属性,如:

1
Device-Memory: 1

类型

1
2
3
4
5
6
7
interface NavigatorDeviceMemory {
readonly deviceMemory: number
}

interface Navigator extends NavigatorDeviceMemory {}

interface WorkerNavigator extends NavigatorDeviceMemory {}

链接

History API

History API 提供了管理浏览会话历史记录的方式

通过 window.history 暴露的 History 接口实例使用

浏览会话历史记录前进后退

History 接口的 back() 方法使浏览会话历史记录后退一条

History 接口的 forward() 方法使浏览会话历史记录前进一条

1
2
history.back()
history.forward()

浏览会话历史记录指定跳转

History 接口的 go() 方法使浏览会话历史记录前进或后退指定数量的记录

传递正数则前进,传递负数则后退

特别的,传递 1 等价于调用 history.forward(),传递 -1 等价于调用 history.back(),传递 0 或不传递参数等价于调用 location.reload()

1
2
3
4
history.go(-1)
history.go(1)
history.go(0)
history.go()

浏览会话历史记录信息

History 接口的 length 只读属性指定当前浏览会话历史记录的数量

1
history.length

History 接口的 scrollRestoration 属性读取或设置浏览会话历史记录默认的导航恢复滚动行为

auto 代表会存储滚动位置,恢复后会自动滚动到存储的位置

manual 代表不会存储滚动位置,恢复后不会自动滚动到存储的位置

1
history.scrollRestoration

浏览会话历史记录数据

History 接口的 state 只读属性反映当前浏览会话历史记录对应的数据,初始为 null 直至调用 pushState() 方法或 replaceState() 方法修改

History 接口的 pushState() 方法向浏览会话历史记录中添加一条历史记录,并更新数据与 URL

History 接口的 replaceState() 方法在浏览会话历史记录中替换当前历史记录,并更新数据与 URL

两方法接收一个 state 参数,可以为任意可序列化的对象或 null,代表与对应的浏览会话历史记录相关的数据

两方法接收一个 unused 参数,因历史原因保留但不再使用,建议传递一个空字符串

两方法接收一个可选的 url 参数,代表与对应的浏览会话历史记录的 URL,受同源策略限制

监听浏览会话历史记录变化

Window 接口的 popstate 事件在浏览会话历史记录变化时触发,返回一个 PopStateEvent 事件

可通过 PopStateEvent 事件的 state 参数读取对应浏览会话历史记录的数据

类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface History {
readonly length: number
scrollRestoration: ScrollRestoration
readonly state: any
back(): void
forward(): void
go(delta?: number): void
pushState(data: any, unused: string, url?: string | URL | null): void
replaceState(data: any, unused: string, url?: string | URL | null): void
}

declare var History: {
prototype: History
}

type ScrollRestoration = "auto" | "manual"

链接

Location API

Location API 提供获取和管理当前网页的 URL 的方法

通过 document.locationwindow.location 暴露的 Location 接口实例使用

Location 属性

Location 接口的 ancestorOrigins 只读属性返回一个 DOMStringList,倒序返回所有祖先浏览上下文的源

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

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

Location 接口的 hostname 属性返回一个 string,代表当前文档 URL 的主机名

Location 接口的 href 属性返回一个 string,代表当前文档 URL 本身

Location 接口的 origin 只读属性返回一个 string,代表当前文档 URL 的源

Location 接口的 pathname 属性返回一个 string,代表当前文档 URL 的路径

Location 接口的 port 属性返回一个 string,代表当前文档 URL 的端口

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

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

1
2
3
4
5
6
7
8
9
10
11
12
/**
* assume current document's URL is https://example.org:8080/foo/bar?q=baz#bang
*/
location.hash // #bang
location.host // example.org:8080
location.hostname // example.org
location.href // https://example.org:8080/foo/bar?q=baz#bang
location.origin // https://example.org:8080
location.pathname // /foo/bar
location.port // ?q=baz
location.protocol // 8080
location.search // https:

Location 方法

Location 接口的 assign() 方法使用给定 URL 加载新文档(不会替换当前文档对应的历史记录)

方法可能抛出 SecurityError 异常,若调用该方法的域与原域不同源时发生

方法可能抛出 SyntaxError 异常,若尝试解析 URL 参数失败

Location 接口的 reload() 方法用于重新加载当前文档

方法可能抛出 SecurityError 异常,若调用该方法的域与原域不同源时发生

Location 接口的 replace() 方法用于使用给定 URL 重新加载当前文档(会替换当前文档对应的历史记录)

方法可能抛出 SyntaxError 异常,若尝试解析 URL 参数失败

Location 接口的 toString() 方法用于获取当前文档 URL 本身,效果同 href 属性

示例

Hash Host Hostname Href Origin Pathname Port Protocol Search

类型

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
interface Location {
readonly ancestorOrigins: DOMStringList
hash: string
host: string
hostname: string
href: string;
toString(): string
readonly origin: string
pathname: string
port: string
protocol: string
search: string
assign(url: string | URL): void
reload(): void
replace(url: string | URL): void
}

declare var Location: {
prototype: Location
}

interface Document {
get location(): Location
set location(href: string | Location)
}

interface Window {
get location(): Location
set location(href: string | Location)
}

链接

Navigation API

Navigation API 提供了启动、拦截和管理浏览器导航行为的能力,同时允许检查应用的历史条目

该 API 是对 History API 和 Location 的扩展和补充

该 API 旨在提供 SPA (Single-Page Applications) 应用所需的功能

该 API 通过 Window 接口的 navigation 指定属性访问全局的 Navigation 实例使用

导航历史记录获取

Navigation 接口的 entries() 方法返回所有导航历史记录

方法返回一个 NavigationHistoryEntry 数组

1
2
3
function getNavigateEntries() {
return window.navigation.entries()
}

Navigation 接口的 currentEntry 只读属性返回一个 NavigationHistoryEntry,返回当前的导航历史记录

导航历史记录操作

Navigation 接口的 navigate() 方法用于导航至指定 URL,并更新导航历史记录

方法接受一个字符串参数,代表导航目标的 URL

方法接受一个可选的配置项:参数 info 允许传递自定义的任何类型的数据,该参数可通过触发的 navigate 事件后通过返回的 NavigateEvent 事件的 info 参数传递;参数 state 允许传递自定义的任何可结构化克隆类型的数据,该参数可通过与之相应的 NavigationHistoryEntry 实例的 getState() 方法获取;参数 history 允许传递 auto (默认 push,特定情况下 replacepush (新增一条 NavigationHistoryEntry 记录) replace (替代当前 NavigationHistoryEntry 记录) 字符串中之一,默认值 auto

两方法均返回一个对象,对象的 committed 参数在可见 URL 改变,同时新的 NavigationHistoryEntry 实例创建时完成,对象的 finished 参数在所有 intercept() 方法完成时完成(等价于 NavigationTransition 接口的 finished 属性完成,同时 navigatesuccess 事件触发),两参数均返回 Promise 的 NavigationHistoryEntry 实例

方法可能抛出 SyntaxError 异常,如 URL 解析失败

方法可能抛出 NotSupportedError 异常,如 history 选项设定为 push 且当前显示 about:blank 页面或 URL 协议为 javascript

方法可能抛出 DataCloneError 异常,如 state 选项数据无法被结构化克隆

方法可能抛出 InvalidStateError 异常,如当前文档未处于活跃状态或当前文档处于卸载中状态或当前记录处于第一条或最后一条

方法可能抛出 AbortError 异常,若当前导航被终止

1
2
3
4
5
6
async function handleNavigate() {
await window.navigation.navigate('/newPage', {
info: { newInfo: 'newInfo' },
state: { newState: 'newState' },
}).finished
}

Navigation 接口的 reload() 方法用于重新加载当前 URL

方法接受一个可选的配置项:参数 info 允许传递自定义的任何类型的数据,该参数可通过触发的 navigate 事件后通过返回的 NavigateEvent 事件的 info 参数传递;参数 state 允许传递自定义的任何可结构化克隆类型的数据,该参数可通过与之相应的 NavigationHistoryEntry 实例的 getState() 方法获取

两方法均返回一个对象,对象的 committed 参数在可见 URL 改变,同时新的 NavigationHistoryEntry 实例创建时完成,对象的 finished 参数在所有 intercept() 方法完成时完成(等价于 NavigationTransition 接口的 finished 属性完成,同时 navigatesuccess 事件触发),两参数均返回 Promise 的 NavigationHistoryEntry 实例

方法可能抛出 DataCloneError 异常,如 state 选项数据无法被结构化克隆

方法可能抛出 InvalidStateError 异常,如当前文档未处于活跃状态或当前文档处于卸载中状态或当前记录处于第一条或最后一条

1
2
3
4
5
async function handleReload() {
await window.navigation.reload({
state: { ...navigation.currentEntry.getState(), newState: 'newState' },
}).finished
}

Navigation 接口的 updateCurrentEntry() 方法用于更新当前导航历史记录的 state 数据,同时避免执行重新加载和导航操作

方法可能抛出 DataCloneError 异常,如 state 选项数据无法被结构化克隆

方法可能抛出 InvalidStateError 异常,如 Navigation.currentEntrynull,即当前页面为 about:blank

1
2
3
4
5
function updateCurrentState() {
window.navigation.updateCurrentEntry({
state: { newState: 'newState' },
})
}

导航历史记录前进或后退

Navigation 接口的 canGoBack 只读属性返回一个 boolean,表示当前是否可以进行导航后退,例如当前记录为导航历史记录中第一条

Navigation 接口的 canGoForward 只读属性返回一个 boolean,表示当前是否可以进行导航前进,例如当前记录为导航历史记录中最后一条

Navigation 接口的 back() 方法在导航历史记录向后导航一条记录

Navigation 接口的 forward() 方法在导航历史记录向前导航一条记录

两方法均接受一个可选的配置项,配置项唯一参数 info 允许传递自定义的任何类型的数据,该参数通过触发的 navigate 事件后通过返回的 NavigateEvent 事件的 info 参数传递

两方法均返回一个对象,对象的 committed 参数在可见 URL 改变,同时新的 NavigationHistoryEntry 实例创建时完成,对象的 finished 参数在所有 intercept() 方法完成时完成(等价于 NavigationTransition 接口的 finished 属性完成,同时 navigatesuccess 事件触发),两参数均返回 Promise 的 NavigationHistoryEntry 实例

两方法均在导航目标超出范围时抛出 InvalidStateError 异常,如当前文档未处于活跃状态或当前文档处于卸载中状态或当前记录处于第一条或最后一条

1
2
3
4
5
6
7
8
9
10
11
async function goBack() {
if (window.navigation.canGoBack) {
await window.navigation.back().finished
}
}

async function goForward() {
if (window.navigation.canGoForward) {
await window.navigation.forward().finished
}
}

导航历史记录指定跳转

Navigation 接口的 traverseTo() 方法在导航历史记录中导航至指定历史记录

方法接受一个字符串参数,代表指定历史记录的唯一标识,与 NavigationHistoryEntry 实例的 key 参数类似

方法接受一个可选的配置项,配置项唯一参数 info 允许传递自定义的任何类型的数据,该参数通过触发的 navigate 事件后通过返回的 NavigateEvent 事件的 info 参数传递

方法在导航目标超出范围时抛出 InvalidStateError 异常,如当前文档未处于活跃状态或 key 参数对应的记录不存在

1
2
3
function initBackToHomeButton() {
BackToHomeButton.onclick = window.navigation.traverseTo(window.navigation.currentEntry.key)
}

导航历史记录跳转监听

Navigation 接口的 currententrychange 事件在当前导航记录内容变化时触发,返回一个 NavigationCurrentEntryChangeEvent 事件

可能原因包括,相同文档内导航 forward() back() traverseTo();替换当前记录 navigate() 方法并设置 history 参数为 replace;更新当前记录数据 updateCurrentEntry() 等等

NavigationCurrentEntryChangeEvent 事件继承自 Event 事件,反映了 currententrychange 事件触发时返回的事件实例

NavigationCurrentEntryChangeEvent 事件的 from 只读属性返回一个 NavigationHistoryEntry,代表来源的导航历史记录

NavigationCurrentEntryChangeEvent 事件的 navigationType 只读属性返回一个 string,值为 push (至新纪录) replace (替换当前记录) reload (重新加载当前记录) traverse (至已有记录) 之一;若因为调用 Navigation 接口的 updateCurrentEntry() 方法导致的,返回 null

1
2
3
4
5
6
7
8
window.navigation.addEventListener("currententrychange", () => {
const data = window.navigation.currentEntry.getState()
// to do something with the data

window.navigation.currentEntry.addEventListener("dispose", () => {
// do something when disposing
})
})

Navigation 接口的 navigate 事件在任一导航类型事件发生时触发,返回一个 NavigateEvent 事件

NavigateEvent 事件继承自 Event 事件,反映了 navigate 事件触发时返回的事件实例

NavigateEvent 事件的 destination 只读属性返回一个 NavigationDestination 实例,反映导航的目标

NavigationDestination 接口类似于 NavigationHistoryEntry 接口,除其不支持 dispose 事件外类似

NavigateEvent 事件的 navigationType 只读属性返回一个 string,值为 push(至新纪录) replace(替换当前记录) reload(重新加载当前记录) traverse(至已有记录)之一,代表导航的类型

NavigateEvent 事件的 canIntercept 只读属性返回一个 boolean,表示导航是否可被拦截并重写 URL(通常跨域导航无法被拦截)

NavigateEvent 事件的 userInitiated 只读属性返回一个 boolean,表示导航是否因用户行为而发生的

NavigateEvent 事件的 hashChange 只读属性返回一个 boolean,表示导航是否是一个片段导航,即仅 URL 的 hash 部分发生改变

NavigateEvent 事件的 signal 只读属性返回一个 AbortSignal,其会在导航取消时终止(一个使用场合是传递给导航内的 fetch 函数以安全地取消请求)

NavigateEvent 事件的 formData 只读属性返回一个 FormData,若导航因为提交表单发生;否则返回 null

NavigateEvent 事件的 downloadRequest 只读属性返回一个 string,代表请求下载的文件名,若请求因为点击 download 的链接导致;否则返回 null

NavigateEvent 事件的 info 只读属性返回在导航操作中传递的 info 参数;若为传递则返回 undefined

NavigateEvent 事件的 hasUAVisualTransition 只读属性返回一个 boolean,表示用户代理是否进行了可视化的导航过渡进程

NavigateEvent 事件的 intercept() 方法允许拦截导航并控制导航的行为

NavigateEvent 事件的 scroll() 方法允许主动触发导航滚动行为

Navigation 接口的 navigateerror 事件在导航操作失败时触发,返回一个 Event 事件

Navigation 接口的 navigatesuccess 事件在导航操作成功完成时触发,返回一个 Event 事件

此时刻 intercept() 方法中传递的所有 Promise 均完成且 NavigationTransition.finished 同样完成

1
2
3
4
5
6
7
8
9
window.navigation.addEventListener("navigatesuccess", () => {
loadingIndicator.hidden = true
})

window.navigation.addEventListener("navigateerror", (event) => {
loadingIndicator.hidden = true

showMessage(`Failed to load page: ${event.message}`)
})

导航历史记录信息

NavigationHistoryEntry 接口表示单条导航历史记录

NavigationHistoryEntry 接口的 id 只读属性返回一个 string,代表当前导航历史记录的 id,该值是一个唯一的由用户代理生成的值

NavigationHistoryEntry 接口的 index 只读属性返回一个 number,代表当前导航历史记录在导航历史记录列表中的下标,若不在时返回 -1

NavigationHistoryEntry 接口的 key 只读属性返回一个 string,代表当前导航历史记录在导航历史记录列表中的位置的 key,该值是一个唯一的由用户代理生成的值,可以用于 Navigation 接口的 traverseTo() 方法

NavigationHistoryEntry 接口的 sameDocument 只读属性返回一个 boolean,代表当前的当前导航历史记录对应的 document 对象是否与 document 对象相同

NavigationHistoryEntry 接口的 url 只读属性返回一个 string,代表当前导航历史记录的绝对 URL,若受 Referer Policy 限制可能返回 null

NavigationHistoryEntry 接口的 getState() 方法返回与当前导航历史记录绑定的 state 数据的拷贝,若不存在则返回 undefined

NavigationHistoryEntry 接口的 dispose 事件在当前导航历史记录被移除时触发,返回一个 Event 事件

导航历史记录进程

NavigationTransition 接口代表正在进行中的导航(即尚未触发 navigatesuccessnavigateerror 事件的导航),通过 Navigation 接口的 transition 属性访问

NavigationTransition 接口的 navigationType 只读属性返回一个 string,值为 push(至新纪录) replace(替换当前记录) reload(重新加载当前记录) traverse(至已有记录)之一,代表导航的类型

NavigationTransition 接口的 from 只读属性返回一个 NavigationHistoryEntry,代表来源的导航历史记录

NavigationTransition 接口的 finished 只读属性返回一个 Promise,在 navigatesuccessnavigateerror 事件触发同时兑现或拒绝

1
2
3
4
5
6
7
async function handleTransition() {
if (navigation.transition != null) {
showLoadingSpinner();
await navigation.transition.finished;
hideLoadingSpinner();
}
}

导航历史记录拦截

NavigateEvent 事件的 intercept() 方法允许拦截导航并控制导航的行为

方法允许接收一个配置项:

选项 handler 指定拦截器的处理回调方法,回调方法允许返回一个 Promise

选项 focusReset 指定导航的聚焦行为,值可以为 after-transition(默认值)或 manual

选项 scroll 指定导航的滚动行为,值可以为 after-transition(默认值)或 manual

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
window.navigation.addEventListener("navigate", (event) => {
if (shouldNotIntercept(navigateEvent)) {
return;
}
const url = new URL(event.destination.url);

if (url.pathname.startsWith("/articles/")) {
event.intercept({
async handler() {
const articleContent = await getArticleContent(url.pathname);
renderArticlePage(articleContent);

event.scroll();

const secondaryContent = await getSecondaryContent(url.pathname);
addSecondaryContent(secondaryContent);
},
});
}
});

类型

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
interface Window {
readonly navigation: Navigation
}

interface Navigation extends EventTarget {
entries(): NavigationHistoryEntry[]
readonly currentEntry?: NavigationHistoryEntry
updateCurrentEntry(options: NavigationUpdateCurrentEntryOptions): void
readonly transition?: NavigationTransition

navigate(url: string, options?: NavigationNavigateOptions): NavigationResult
reload(options?: NavigationReloadOptions): NavigationResult

readonly canGoBack: boolean
readonly canGoForward: boolean

back(options?: NavigationOptions): NavigationResult
forward(options?: NavigationOptions): NavigationResult
traverseTo(key: string, options?: NavigationOptions): NavigationResult

oncurrententrychange: ((this: Navigation, ev: NavigationCurrentEntryChangeEvent) => any) | null
onnavigate: ((this: Navigation, ev: NavigateEvent) => any) | null
onnavigateerror: ((this: Navigation, ev: Event) => any) | null
onnavigatesuccess: ((this: Navigation, ev: Event) => any) | null
}

declare var Navigation: {
prototype: Navigation
}

interface NavigationUpdateCurrentEntryOptions {
state: any
}

interface NavigationOptions {
info?: any
}

interface NavigationNavigateOptions extends NavigationOptions {
state?: any
history?: NavigationHistoryBehavior
}

interface NavigationReloadOptions extends NavigationOptions {
state?: any
}

interface NavigationResult {
committed: Promise<NavigationHistoryEntry>
finished: Promise<NavigationHistoryEntry>
}

enum NavigationHistoryBehavior {
"auto",
"push",
"replace",
}

enum NavigationType {
"push",
"replace",
"reload",
"traverse",
}

interface NavigationHistoryEntry extends EventTarget {
readonly url: string | null
readonly key: string
readonly id: string
readonly index: number
readonly sameDocument: boolean

getState(): any

ondispose: ((this: NavigationHistoryEntry, ev: Event) => any) | null
}

declare var NavigationHistoryEntry: {
prototype: NavigationHistoryEntry
}

interface NavigationTransition {
readonly navigationType: NavigationType
readonly from: NavigationHistoryEntry
readonly finished: Promise<undefined>
}

declare var NavigationTransition: {
prototype: NavigationTransition
}

interface NavigationCurrentEntryChangeEvent extends Event {
readonly navigationType: NavigationType | null
readonly from: NavigationHistoryEntry
}

declare var NavigationCurrentEntryChangeEvent: {
new(type: string, eventInitDict: NavigationCurrentEntryChangeEventInit): NavigationCurrentEntryChangeEvent
prototype: NavigationCurrentEntryChangeEvent
}

interface NavigationCurrentEntryChangeEventInit extends EventInit {
navigationType?: NavigationType
from: NavigationHistoryEntry
}

interface NavigateEvent extends Event {
readonly navigationType: NavigationType
readonly destination: NavigationDestination
readonly canIntercept: boolean
readonly userInitiated: boolean
readonly hashChange: boolean
readonly signal: AbortSignal
readonly formData?: FormData
readonly downloadRequest?: string
readonly info: any
readonly hasUAVisualTransition: boolean

intercept(options?: NavigationInterceptOptions): void
scroll(): void
}

declare var NavigateEvent: {
new(type: string, eventInitDict: NavigateEventInit): NavigateEvent
prototype: NavigateEvent
}

interface NavigateEventInit extends EventInit {
navigationType?: NavigationType
destination: NavigationDestination
canIntercept?: boolean
userInitiated?: boolean
hashChange?: boolean
signal: AbortSignal
formData?: FormData
downloadRequest?: string
info: any
hasUAVisualTransition?: boolean
}

interface NavigationInterceptOptions {
handler?: NavigationInterceptHandler
focusReset?: NavigationFocusReset
scroll?: NavigationScrollBehavior
}

enum NavigationFocusReset {
"after-transition",
"manual",
}

enum NavigationScrollBehavior {
"after-transition",
"manual",
}

type NavigationInterceptHandler = () => Promise<undefined>

interface NavigationDestination {
readonly url: string
readonly key: string
readonly id: string
readonly index: number
readonly sameDocument: boolean

getState(): any
}

declare var NavigationDestination: {
prototype: NavigationDestination
}

链接

Pointer Events

Pointer Events 定义指针相关的一系列事件

旨在为 Mouse Events 和 Touch Events 在不同平台上提供统一的行为

指针事件列表

事件名称 事件类型 事件目标 事件是否冒泡 事件是否可取消 事件描述
pointerenter PointerEvent Window,Document,HTMLElement,SVGElement,MathMLElement 指针移入元素及其子元素
pointerleave PointerEvent Window,Document,HTMLElement,SVGElement,MathMLElement 指针移出元素及其子元素
pointerdown PointerEvent Window,Document,HTMLElement,SVGElement,MathMLElement 元素上按下指针
pointermove PointerEvent Window,Document,HTMLElement,SVGElement,MathMLElement 指针在元素内移动
pointerup PointerEvent Window,Document,HTMLElement,SVGElement,MathMLElement 元素上释放指针
pointerover PointerEvent Window,Document,HTMLElement,SVGElement,MathMLElement 指针移入元素及其子元素
pointerout PointerEvent Window,Document,HTMLElement,SVGElement,MathMLElement 指针移出元素及其子元素
pointercancel PointerEvent Window,Document,HTMLElement,SVGElement,MathMLElement 指针操作被取消
pointerrawupdate PointerEvent Window,Document,HTMLElement,SVGElement,MathMLElement 指针操作不触发 pointerdown 与 pointerup 事件
gotpointercapture PointerEvent Window,Document,HTMLElement,SVGElement,MathMLElement 进入指针捕获模式
lostpointercapture PointerEvent Window,Document,HTMLElement,SVGElement,MathMLElement 离开指针捕获模式

其中 pointerrawupdate 事件仅限严格模式使用

指针事件

PointerEvent 接口表示一个指针事件

指针捕获

Element 接口的 setPointerCapture() 方法用于给指定的指针ID设置一个指针捕获

Element 接口的 releasePointerCapture() 方法用于给指定的指针ID释放一个指针捕获

Element 接口的 hasPointerCapture() 方法用于检测当前元素是否处于指定的指针ID下的指针捕获状态,返回一个 boolean

以上三个方法均接受一个 number 参数,代表指针 ID

触摸点数量

Navigator 接口的 maxTouchPoints 只读属性返回 number,代表设备能够同时支持的触摸点的最大数量

类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
interface Element {
hasPointerCapture(pointerId: number): boolean
releasePointerCapture(pointerId: number): void
setPointerCapture(pointerId: number): void
}

interface GlobalEventHandlers {
ongotpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null
onlostpointercapture: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null
onpointercancel: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null
onpointerdown: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null
onpointerenter: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null
onpointerleave: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null
onpointermove: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null
onpointerout: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null
onpointerover: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null
onpointerrawupdate: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null
onpointerup: ((this: GlobalEventHandlers, ev: PointerEvent) => any) | null
}

interface Navigator {
readonly maxTouchPoints: number
}

链接

Touch Events

Touch Events 定义与用户触摸交互的事件

触摸事件列表

事件名称 事件类型 事件目标 事件是否冒泡 事件是否可取消 事件描述
touchstart TouchEvent Window,Document,HTMLElement,SVGElement,MathMLElement 视情况而定 触摸点放置到触摸面上
touchmove TouchEvent Window,Document,HTMLElement,SVGElement,MathMLElement 视情况而定 触摸点在触摸面上移动
touchend TouchEvent Window,Document,HTMLElement,SVGElement,MathMLElement 视情况而定 触摸点从触摸板上移除
touchcancel TouchEvent Window,Document,HTMLElement,SVGElement,MathMLElement 触摸行为被特定于实现被中断

触摸事件

TouchEvent 接口表示一个触摸事件

TouchList 接口表示一组触摸点

Touch 接口表示单个触摸点

类型

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
interface GlobalEventHandlers {
ontouchcancel?: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null | undefined
ontouchend?: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null | undefined
ontouchmove?: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null | undefined
ontouchstart?: ((this: GlobalEventHandlers, ev: TouchEvent) => any) | null | undefined
}

interface Touch {
readonly clientX: number
readonly clientY: number
readonly force: number
readonly identifier: number
readonly pageX: number
readonly pageY: number
readonly radiusX: number
readonly radiusY: number
readonly rotationAngle: number
readonly screenX: number
readonly screenY: number
readonly target: EventTarget
}

declare var Touch: {
prototype: Touch
new(touchInitDict: TouchInit): Touch
}

interface TouchInit {
altitudeAngle?: number
azimuthAngle?: number
clientX?: number
clientY?: number
force?: number
identifier: number
pageX?: number
pageY?: number
radiusX?: number
radiusY?: number
rotationAngle?: number
screenX?: number
screenY?: number
target: EventTarget
touchType?: TouchType
}

interface TouchEvent extends UIEvent {
readonly altKey: boolean
readonly changedTouches: TouchList
readonly ctrlKey: boolean
readonly metaKey: boolean
readonly shiftKey: boolean
readonly targetTouches: TouchList
readonly touches: TouchList
}

declare var TouchEvent: {
prototype: TouchEvent
new(type: string, eventInitDict?: TouchEventInit): TouchEvent
}

interface TouchEventInit extends EventModifierInit {
changedTouches?: Touch[]
targetTouches?: Touch[]
touches?: Touch[]
}

interface TouchList {
readonly length: number
item(index: number): Touch | null
[index: number]: Touch
}

declare var TouchList: {
prototype: TouchList
}

type TouchType = 'direct' | 'stylus'

链接

Web App Launch Handler API

Web App Launch Handler API 允许管理 Progressive Web App 的启动导航方式(针对已开启的 PWA 应用)

配置启动行为

通过配置 manifest 文件的 launch_handler 字段来管理应用启动行为

该字段的唯一子字段 client_mode 指定应用启动时导航的行为,允许的值如下

  • auto 由用户代理根据平台等因素决定行为,亦是默认值(如移动端使用 navigate-existing,桌面端使用 navigate-new
  • navigate-new 将创建新的浏览上下文以加载目标 URL
  • navigate-existing 最近交互的浏览上下文将聚焦并导航至目标 URL
  • focus-existing 最近交互的浏览上下文将聚焦并用于处理目标 URL(但不会自动导航)

该子字段亦允许指定多个值,以提供后备的执行行为

手动执行启动行为

通过 LaunchQueue 接口使用,该接口实例通过 window.launchQueue 暴露

LaunchQueue 接口的 setConsumer() 方法用于管理应用的启动导航行为

该方法接收一个回调方法,代表在发生应用启动导航行为时需调用的回调方法,并传递一个 LaunchParams 实例

LaunchParams 接口的 targetURL 属性返回一个 string,代表导航的目标 URL,可能为 null

LaunchParams 接口的 files 属性返回一个 FileSystemHandle 数组,代表通过 POST 方法传递的文件

1
2
3
4
5
6
7
8
9
10
11
12
window.launchQueue.setConsumer((launchParams) => {
if (launchParams.targetURL) {
const params = new URL(launchParams.targetURL).searchParams

const track = params.get("track")
if (track) {
audio.src = track
title.textContent = new URL(track).pathname.substr(1)
audio.play()
}
}
})

类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
type LaunchConsumer = (params: LaunchParams) => any

interface LaunchParams {
readonly targetURL?: string
readonly files: ReadonlyArray<FileSystemHandle>
}

interface LaunchQueue {
setConsumer(consumer: LaunchConsumer): void
}

interface Window {
readonly launchQueue: LaunchQueue
}

链接

File System Access API

File System Access API 允许访问本地文件系统

获取选择资源的文件句柄

使用 Window 接口的 showOpenFilePicker() 方法选取单个或多个文件,返回对应的文件句柄

方法传入一组可选的配置项

  • excludeAcceptAllOption 可选选项指定选择器是否启用筛选文件类型的选项,默认值是 false
  • id 选项用于和当前目录配对,会自动记忆与之相关的目录,后续选择时若指定相同的 id 可以自动打开与之前选择相同的目录,接收一个字符串
  • startIn 选项指定初始打开目录,接收一个 FileSystemHandle 或预设的目录 "desktop" "documents" "downloads" "music" "pictures""videos"
  • multiple 可选选项指定是否允许多选,默认值是 false
  • types 选项指定允许选择的文件类型,传递一个数组,数组各项支持 accept 选项,指定文件类型的 MIME 类型和 description 可选选项,指定文件类型的描述

返回一个 Promise 的 FileSystemFileHandle 数组

方法在用户未选择目录或用户代理拒绝目录访问时抛出 AbortError 异常

方法要求在调用需基于发生用户交互

获取新增资源的文件句柄

使用 Window 接口的 showSaveFilePicker() 方法新增文件(可以是已有文件或新文件),返回对应的文件句柄

方法传入一组可选的配置项

  • excludeAcceptAllOption 可选选项同上
  • id 选项同上
  • startIn 选项同上
  • suggestedName 可选选项指定建议的新增文件名称
  • types 选项同上

返回一个 Promise 的 FileSystemFileHandle

方法在用户未选择目录或用户代理拒绝目录访问时抛出 AbortError 异常

方法要求在调用需基于发生用户交互

获取选择资源的目录句柄

使用 Window 接口的 showDirectoryPicker() 选取目录,返回对应的目录句柄

方法传入一组可选的配置项

  • id 选项同上
  • mode 可选选项用于指定权限模式,接收字符串枚举 "read""readwrite",默认值为 "read"
  • startIn 选项同上

返回一个 Promise 的 FileSystemDirectoryHandle

方法在用户未选择目录或用户代理拒绝目录访问时抛出 AbortError 异常

方法要求在调用需基于发生用户交互

获取拖动资源的文件句柄或目录句柄

使用 DataTransferItem 接口的 getAsFileSystemHandle() 方法获取拖动资源的文件句柄或目录句柄

返回一个 Promise 的 FileSystemFileHandleFileSystemDirectoryHandle

类型

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
interface Window {
showOpenFilePicker: (options?: OpenFilePickerOptions) => Promise<FileSystemFileHandle[]>
showSaveFilePicker: (options?: SaveFilePickerOptions) => Promise<FileSystemFileHandle>
showDirectoryPicker: (options?: DirectoryPickerOptions) => Promise<FileSystemDirectoryHandle>
}

interface FilePickerAcceptType {
description?: string
accept: Record<string, string | string[]>
}

interface FilePickerOptions {
excludeAcceptAllOption?: boolean
id?: string
types?: FilePickerAcceptType[]
startIn?: StartInDirectory
}

interface OpenFilePickerOptions extends FilePickerOptions {
multiple?: boolean
}

interface SaveFilePickerOptions extends FilePickerOptions {
suggestedName?: string
}

interface DirectoryPickerOptions {
id?: string
startIn?: StartInDirectory
mode?: FileSystemPermissionMode
}

type WellKnownDirectory = 'desktop' | 'documents' | 'downloads' | 'music' | 'pictures' | 'videos'

type StartInDirectory = WellKnownDirectory | FileSystemHandle

type FileSystemPermissionMode = 'read' | 'readwrite'

链接

File API

File API 允许获取文件及其内容

二进制对象

Blob 接口用于表示二进制对象

Blob 接口的 Blob() 构造方法用于创建一个二进制对象

方法接受一个可选的对象数组,各项可以为 stringArrayBufferBlob 本身,代表创建的二进制对象的内容

方法接受一个可选的配置项:

type 可选参数接收一个 string,指定二进制对象的 MIME 类型,默认值为空字符串

endings 可选参数接收一个 string,指定二进制对象编码时对换行符的处理方式,值 transparent 代表对换行符不作处理,值 native 代表转换换行符为系统支持的形式,默认值为 transparent

1
const blob = new Blob(['text', new ArrayBuffer(10), new Blob()], { type: 'text/plain', endings: 'native' })

Blob 接口的 size 属性返回一个 number,代表二进制对象中数据的大小

Blob 接口的 type 属性返回一个 string,代表二进制对象的 MIME 类型

1
2
blob.size
blob.type

Blob 接口的 slice() 方法用于截取二进制对象

方法的 start 可选参数接收一个 number,代表截取的起始位置,默认值为 0

方法的 end 可选参数接收一个 number,代表截取的终止位置,默认值同 size 参数

方法的 contentType 可选参数接收一个 string,代表新二进制对象的 type 参数

方法返回一个新二进制对象

1
const b = blob.slice(1, 11)

Blob 接口的 stream() 方法用于将二进制对象转换为流,返回一个 ReadableStream

Blob 接口的 text() 方法用于将二进制对象转换为 UTF-8 格式的字符串,返回一个 Promise 的 string

Blob 接口的 arrayBuffer() 方法用于将二进制对象转换为 Buffer,返回一个 Promise 的 ArrayBuffer

1
2
3
const stream = blob.stream()
const text = await blob.text()
const arrayBuffer = await blob.arrayBuffer()

文件对象

File 接口用于表示文件对象

File 接口的 File() 构造方法用于创建一个文件对象

方法接受一个对象数组,各项可以为 stringArrayBufferBlob 本身,代表创建的文件对象的内容

方法接受一个可选的配置项:

type 可选参数接收一个 string,指定二进制对象的 MIME 类型,默认值为空字符串

endings 可选参数接收一个 string,指定二进制对象编码时对换行符的处理方式,值 transparent 代表对换行符不作处理,值 native 代表转换换行符为系统支持的形式,默认值为 transparent

lastModified 可选参数接收一个 number,指定文件最后更改时间

1
const file = new File(['text', new ArrayBuffer(10), new Blob()], 'file', { type: 'text/plain', endings: 'native', lastModified: Date.now() })

File 接口的 name 属性返回一个 string,代表文件对象的名称

File 接口的 lastModified 属性返回一个 number,代表文件对象的最后更改时间,若无则返回当前时间

1
2
file.name
file.lastModified

文件列表对象

FileList 接口用于表示文件列表对象

FileList 接口的 length 属性返回一个 number,代表文件列表长度

FileList 接口的 item() 方法根据给定的 index 返回对应的文件

FileList 接口支持使用 [] 访问。亦支持使用 iterator 遍历

文件异步读取对象

FileReader 接口用于异步地读取文件

FileReader 接口的 FileReader() 构造方法用于创建异步读取文件对象

FileReader 接口的 EMPTY 常量值为 0,表示实例刚刚创建但尚未开始读取文件

FileReader 接口的 LOADING 常量值为 1,表示正在开始读取文件

FileReader 接口的 DONE 常量值为 2,表示读取文件完成,无论是否读取成功或失败抑或手动终止

FileReader 接口的 readyState 属性返回一个 string,代表文件读取进度,值为 EMPTYLOADINGDONE 之一

FileReader 接口的 result 属性返回一个 stringArrayBuffernull,表示文件读取结果,具体返回值类型取决于调用的方法

FileReader 接口的 error 属性返回一个 DOMExceptionnull,表示文件读取错误

FileReader 接口的 readAsArrayBuffer() 方法用于异步地将二进制对象读取为 ArrayBuffer

FileReader 接口的 readAsDataURL() 方法用于异步地将二进制对象读取为 Object URL

FileReader 接口的 readAsText() 方法用于异步地将二进制对象读取为指定编码的 string

以上三个方法接收一个 Blob 对象,无返回值

FileReader 接口的 abort() 方法用于终止读取进程

FileReader 接口的 abort 事件在读取文件进程被终止时触发,即调用 abort() 方法

FileReader 接口的 error 事件在读取文件进程失败时触发

FileReader 接口的 load 事件在读取文件进程成功完成时触发

FileReader 接口的 loadend 事件在读取文件进程完成时触发,无论成功与否

FileReader 接口的 loadstart 事件在读取文件进程开始时触发

FileReader 接口的 progress 事件在读取文件进程中周期性触发

事件均返回一个 ProgressEvent

1
2
3
4
5
6
7
const reader = new FileReader()

reader.addEventListener('load', () => {
console.log(reader.result)
})

reader.readAsText(blob)

文件同步读取对象

FileReaderSync 接口用于同步地读取文件内容

该接口仅在除 ServiceWorker 外的其他 Worker 环境中可用

FileReaderSync 接口的 FileReaderSync() 构造方法用于创建同步读取文件对象

FileReaderSync 接口的 readAsArrayBuffer() 方法用于同步地将二进制对象读取为 ArrayBuffer

FileReaderSync 接口的 readAsDataURL() 方法用于同步地将二进制对象读取为 Object URL

FileReaderSync 接口的 readAsText() 方法用于同步地将二进制对象读取为指定编码的 string

以上三个方法接收一个 Blob 对象,返回一个 string

以上三个方法可能抛出 NotFoundError,若资源不存在(如已被删除)

以上三个方法可能抛出 NotReadableError,若资源因为权限问题无法被读取(如资源锁)或资源快照与本地存储不符

以上三个方法可能抛出 SecurityError,若资源被用户代理判断为网络使用不安全,或进行了过于频繁的读取,或已被第三方修改

以上三个方法可能抛出 EncodingError,若资源被编码为 data URL 且超出了用户代理限制

1
2
3
4
5
const reader = new FileReaderSync()

const buffer = reader.readAsArrayBuffer()
const url = reader.readAsDataURL()
const text = reader.readAsText()

Object URL

使用 URL 接口的 createObjectURL() 创建一个 Object URL

方法接收一个 BlobMediaSource 参数,代表源二进制对象

方法返回一个 string,代表创建的 Object URL

使用 URL 接口的 revokeObjectURL() 释放一个已创建的 Object URL

方法接收一个 string,代表需释放的 Object URL

以上两方法在除 ServiceWorker 外的其他环境中可用

类型

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
interface Blob {
readonly size: number
readonly type: string

slice(start?: number, end?: number, contentType?: string): Blob

stream(): ReadableStream
text(): Promise<string>
arrayBuffer(): Promise<ArrayBuffer>
}

declare var Blob: {
new (blobParts?: BlobPart[], options?: BlobPropertyBag): Blob
prototype: Blob
}

enum EndingType {
transparent = 'transparent',
native = 'native',
}

interface BlobPropertyBag {
type?: string
endings?: EndingType
}

type BlobPart = Blob | string | BufferSource

interface File extends Blob {
readonly name: string
readonly lastModified: number
}

declare var File: {
new (fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File
prototype: File
}

interface FilePropertyBag extends BlobPropertyBag {
lastModified?: number
}

interface FileList {
item(index: number): File | null
readonly length: number
[index: number]: File
[Symbol.iterator](): IterableIterator<File>
}

declare var FileList: {
prototype: FileList
}

interface FileReader extends EventTarget {
readAsArrayBuffer(blob: Blob): void
readAsBinaryString(blob: Blob): void
readAsText(blob: Blob, encoding?: string): void
readAsDataURL(blob: Blob): void

abort(): void

readonly EMPTY: 0
readonly LOADING: 1
readonly DONE: 2

readonly readyState: FileReader['EMPTY' | 'LOADING' | 'DONE']

readonly result: string | ArrayBuffer | null

readonly error: DOMException | null

onloadstart: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null
onprogress: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null
onload: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null
onabort: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null
onerror: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null
onloadend: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null
}

declare var FileReader: {
new(): FileReader
prototype: FileReader
readonly EMPTY: 0
readonly LOADING: 1
readonly DONE: 2
}

interface FileReaderSync {
readAsArrayBuffer(blob: Blob): ArrayBuffer
readAsBinaryString(blob: Blob): string
readAsText(blob: Blob, encoding?: string): string
readAsDataURL(blob: Blob): string
}

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

declare var URL: {
new(url: string | URL, base?: string | URL): URL
prototype: URL
createObjectURL(obj: Blob | MediaSource): string
revokeObjectURL(url: string): void
}

链接

Barcode Detection API

Barcode Detection API 支持检测并扫描条形码和二维码

该 API 主要通过 BarcodeDetector 类使用

获取支持扫描类型

通过 BarcodeDetector 类的 getSupportedFormats() 静态方法用于获取支持扫描的条形码和二维码类型

方法返回一个 Promise 的字符串数组,结果各项在 BarcodeFormat 中

1
2
3
4
5
const supportedFormats = await BarcodeDetector.getSupportedFormats()

supportedFormats.forEach((format) => {
console.log(format)
})

扫描条形码或二维码

调用 BarcodeDetector 类构造函数创建 BarcodeDetector 实例

构造函数允许传入一个配置项,其参数 formats 代表限制识别的范围,需为支持识别的类型之一,同时需在 BarcodeFormat 中

构造函数可能抛出 TypeError 异常,如传入参数为空列表或列表某项不受支持

1
const detector = new BarcodeDetector()

调用 BarcodeDetector 类的 detect() 方法识别条形码和二维码

方法传入一个 image 参数,可以为 ImageData Blob VideoFrame OffscreenCanvas ImageBitmap HTMLCanvasElement HTMLVideoElement HTMLImageElement SVGImageElement 类型

方法返回一个 Promise 的对象数组,代表识别结果

各项 rawValue 参数返回一个字符串,代表识别的结果

各项 format 参数返回一个字符串,代表识别的格式,为 BarcodeFormat 中

各项 boundingBox 参数返回一个 DOMRectReadOnly,代表识别的条形码或二维码相对于图像的相对定位

各项 cornerPoints 参数返回一个对象数组,各项均包含 x 属性和 y 属性,代表识别的条形码或二维码相对于图像的四个顶点的相对定位

方法可能抛出 SecurityError 异常,如传入图像具有源且与当前脚本执行源不相同,或传入图像为 HTMLCanvasElement 且其中图像 origin-clean 标识为 false

方法可能抛出 InvalidStateError 异常,如传入图像为 HTMLImageElement 且加载失败(error 状态)或未完全完成解码,或传入图像为 HTMLVideoElement 且视频未加载完成(HAVE_NOTHINGHAVE_METADATA 状态)

1
2
3
4
5
const results = await detector.detect(image)

for (const result of results) {
console.log(result.rawValue)
}

类型

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
interface BarcodeDetector {
detect(image: ImageBitmapSource): Promise<DetectedBarcode[]>
}

declare var BarcodeDetector: {
new (barcodeDetectorOptions?: BarcodeDetectorOptions): BarcodeDetector
prototype: BarcodeDetector

getSupportedFormats(): Promise<BarcodeFormat[]>
}

interface BarcodeDetectorOptions {
formats: BarcodeFormat[]
}

interface DetectedBarcode {
boundingBox: DOMRectReadOnly
rawValue: string
format: BarcodeFormat
cornerPoints: ReadonlyArray<Point2D>
}

enum BarcodeFormat {
"aztec",
"code_128",
"code_39",
"code_93",
"codabar",
"data_matrix",
"ean_13",
"ean_8",
"itf",
"pdf417",
"qr_code",
"unknown",
"upc_a",
"upc_e"
}

链接


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