目录

  1. 1 概述
  2. 2 公共基础设施
  3. 3 HTML 文档的语义,结构,与API
  4. 4 HTML 元素
  5. 5 微数据
  6. 6 用户交互
  7. 7 加载 Web 页面
  8. 8 Web 应用 API
  9. 9 通信
  10. 10 Web 工作线程
  11. 11 Worklets
  12. 12 Web 存储
  13. 13 HTML 语法
  14. 14 XML 语法
  15. 15 渲染
  16. 16 废弃的特性
  17. 17 IANA 注意事项
  18. 索引
  19. References
  20. 致谢
  21. Intellectual property rights

详细目录

  1. 1 概述
    1. 1.1 本标准的适用范围
    2. 1.2 这是 HTML5 吗?
    3. 1.3 背景
    4. 1.4 受众
    5. 1.5 范围
    6. 1.6 历史
    7. 1.7 设计笔记
      1. 1.7.1 脚本执行的可串行性
      2. 1.7.2 与其他标准的兼容性
      3. 1.7.3 可扩展性
    8. 1.8 HTML 和 XML 语法
    9. 1.9 本标准的结构
      1. 1.9.1 如何阅读本标准
      2. 1.9.2 排版惯例
    10. 1.10 HTML 的简单介绍
      1. 1.10.1 使用 HTML 编写安全应用
      2. 1.10.2 使用脚本 API 时常见的陷阱
      3. 1.10.3 编写 HTML 时如何发现错误:验证器和一致性检查器
    11. 1.11 对页面作者的一致性要求
      1. 1.11.1 表示性的标记
      2. 1.11.2 语法错误
      3. 1.11.3 内容模型和属性值的限制
    12. 1.12 推荐阅读
  2. 2 公共基础设施
    1. 2.1 术语
      1. 2.1.1 Parallelism
      2. 2.1.2 资源
      3. 2.1.3 XML 兼容性
      4. 2.1.4 DOM 树
      5. 2.1.5 脚本
      6. 2.1.6 插件
      7. 2.1.7 字符编码
      8. 2.1.8 符合性类别
      9. 2.1.9 Dependencies
      10. 2.1.10 可扩展性
      11. 2.1.11 与 XPath 和 XSLT 交互
    2. 2.2 String comparison
    3. 2.3 Policy-controlled features
    4. 2.4 公共微语法
      1. 2.4.1 常见的解析器风格
      2. 2.4.2 布尔属性
      3. 2.4.3 关键字和枚举属性
      4. 2.4.4 数字
        1. 2.4.4.1 有符号整数
        2. 2.4.4.2 非负整数
        3. 2.4.4.3 浮点数
        4. 2.4.4.4 百分数和长度
        5. 2.4.4.5 非零百分数和长度
        6. 2.4.4.6 浮点数列表
        7. 2.4.4.7 维度值列表
      5. 2.4.5 日期和时间
        1. 2.4.5.1 月份
        2. 2.4.5.2 日期
        3. 2.4.5.3 无年的日期
        4. 2.4.5.4 时间
        5. 2.4.5.5 本地日期和时间
        6. 2.4.5.6 时区
        7. 2.4.5.7 全球日期和时间
        8. 2.4.5.8 星期
        9. 2.4.5.9 时间间隔
        10. 2.4.5.10 模糊的时间
      6. 2.4.6 颜色
      7. 2.4.7 空格分隔的令牌
      8. 2.4.8 逗号分隔的字符集
      9. 2.4.9 引用
      10. 2.4.10 媒体查询
    5. 2.5 URL
      1. 2.5.1 术语
      2. 2.5.2 解析 URL
      3. 2.5.3 基 URL 的动态变化
    6. 2.6 获取资源
      1. 2.6.1 术语
      2. 2.6.2 确定响应类型
      3. 2.6.3meta 元素提取字符编码
      4. 2.6.4 CORS 设置属性
      5. 2.6.5 引荐来源策略属性
      6. 2.6.6 Nonce attributes
      7. 2.6.7 Lazy loading attributes
    7. 2.7 通用 DOM 接口
      1. 2.7.1 在 IDL 属性中反映内容属性
      2. 2.7.2 集合
        1. 2.7.2.1 The HTMLAllCollection interface
          1. 2.7.2.1.1 [[Call]] ( thisArgument, argumentsList )
        2. 2.7.2.2 HTMLFormControlsCollection 接口
        3. 2.7.2.3 HTMLOptionsCollection 接口
      3. 2.7.3 DOMStringList 接口
    8. 2.8 安全地传递结构化数据
      1. 2.8.1 可序列化对象
      2. 2.8.2 可传输对象
      3. 2.8.3 StructuredSerializeInternal ( value, forStorage [ , memory ] )
      4. 2.8.4 StructuredSerialize ( value )
      5. 2.8.5 StructuredSerializeForStorage ( value )
      6. 2.8.6 StructuredDeserialize ( serialized, targetRealm [ , memory ] )
      7. 2.8.7 StructuredSerializeWithTransfer ( value, transferList )
      8. 2.8.8 StructuredDeserializeWithTransfer ( serializeWithTransferResult, targetRealm )
      9. 2.8.9 在其他规范中执行序列化和传输
  3. 3 HTML 文档的语义,结构,与API
    1. 3.1 文档
      1. 3.1.1 Document 对象
      2. 3.1.2 The DocumentOrShadowRoot interface
      3. 3.1.3 资源元数据管理
      4. 3.1.4 DOM 树访问器
    2. 3.2 元素
      1. 3.2.1 语义
      2. 3.2.2 DOM 中的元素
      3. 3.2.3 HTML 元素构造器
      4. 3.2.4 元素定义
        1. 3.2.4.1 属性
      5. 3.2.5 内容模型
        1. 3.2.5.1 "nothing" 内容模型
        2. 3.2.5.2 内容的种类
          1. 3.2.5.2.1 元数据内容
          2. 3.2.5.2.2 流式内容
          3. 3.2.5.2.3 章节内容
          4. 3.2.5.2.4 标题内容
          5. 3.2.5.2.5 短语内容
          6. 3.2.5.2.6 嵌入内容
          7. 3.2.5.2.7 交互式内容
          8. 3.2.5.2.8 可感知内容
          9. 3.2.5.2.9 脚本支持元素
        3. 3.2.5.3 透明内容模型
        4. 3.2.5.4 段落
      6. 3.2.6 全局属性
        1. 3.2.6.1 title 属性
        2. 3.2.6.2 langxml:lang 属性
        3. 3.2.6.3 translate 属性
        4. 3.2.6.4 dir 属性
        5. 3.2.6.5 style 属性
        6. 3.2.6.6 使用 data-* 属性 嵌入自定义不可见数据
      7. 3.2.7 The innerText getter and setter
      8. 3.2.8 与双向算法相关的要求
        1. 3.2.8.1 双向算法格式化字符的编写一致性标准
        2. 3.2.8.2 用户代理一致性标准
      9. 3.2.9 ARIA 与 平台可访问性 API 相关的要求
  4. 4 HTML 元素
    1. 4.1 文档元素
      1. 4.1.1 html 元素
    2. 4.2 文档元数据
      1. 4.2.1 head 元素
      2. 4.2.2 title 元素
      3. 4.2.3 base 元素
      4. 4.2.4 link 元素
        1. 4.2.4.1 处理 media 属性
        2. 4.2.4.2 处理 type 属性
        3. 4.2.4.3link 元素获取和处理资源
        4. 4.2.4.4 处理 `Link` 协议头
        5. 4.2.4.5 为用户提供一种跟随使用 link 元素创建的超链接的方式
      5. 4.2.5 meta 元素
        1. 4.2.5.1 标准元数据名
        2. 4.2.5.2 其他元数据名称
        3. 4.2.5.3 Pragma directives
        4. 4.2.5.4 Specifying the document's character encoding
      6. 4.2.6 The style element
      7. 4.2.7 Interactions of styling and scripting
    3. 4.3 Section
      1. 4.3.1 The body element
      2. 4.3.2 The article element
      3. 4.3.3 The section element
      4. 4.3.4 The nav element
      5. 4.3.5 The aside element
      6. 4.3.6 The h1, h2, h3, h4, h5, and h6 elements
      7. 4.3.7 The hgroup element
      8. 4.3.8 The header element
      9. 4.3.9 The footer element
      10. 4.3.10 The address element
      11. 4.3.11 标题和章节
        1. 4.3.11.1 Creating an outline
        2. 4.3.11.2 Sample outlines
        3. 4.3.11.3 暴露目录给用户
      12. 4.3.12 Usage summary
        1. 4.3.12.1 使用 article 还是 section?
    4. 4.4 Grouping content
      1. 4.4.1 The p element
      2. 4.4.2 The hr element
      3. 4.4.3 The pre element
      4. 4.4.4 The blockquote element
      5. 4.4.5 The ol element
      6. 4.4.6 The ul element
      7. 4.4.7 The menu element
      8. 4.4.8 The li element
      9. 4.4.9 The dl element
      10. 4.4.10 The dt element
      11. 4.4.11 The dd element
      12. 4.4.12 The figure element
      13. 4.4.13 The figcaption element
      14. 4.4.14 The main element
      15. 4.4.15 The div element
    5. 4.5 Text-level semantics
      1. 4.5.1 The a element
      2. 4.5.2 The em element
      3. 4.5.3 The strong element
      4. 4.5.4 The small element
      5. 4.5.5 The s element
      6. 4.5.6 The cite element
      7. 4.5.7 The q element
      8. 4.5.8 The dfn element
      9. 4.5.9 The abbr element
      10. 4.5.10 The ruby element
      11. 4.5.11 The rt element
      12. 4.5.12 The rp element
      13. 4.5.13 The data element
      14. 4.5.14 The time element
      15. 4.5.15 The code element
      16. 4.5.16 The var element
      17. 4.5.17 The samp element
      18. 4.5.18 The kbd element
      19. 4.5.19 The sub and sup elements
      20. 4.5.20 The i element
      21. 4.5.21 The b element
      22. 4.5.22 The u element
      23. 4.5.23 The mark element
      24. 4.5.24 The bdi element
      25. 4.5.25 The bdo element
      26. 4.5.26 The span element
      27. 4.5.27 The br element
      28. 4.5.28 The wbr element
      29. 4.5.29 Usage summary
    6. 4.6 Links
      1. 4.6.1 概述
      2. 4.6.2 Links created by a and area elements
      3. 4.6.3 API for a and area elements
      4. 4.6.4 Following hyperlinks
      5. 4.6.5 Downloading resources
        1. 4.6.5.1 Hyperlink auditing
      6. 4.6.6 Link types
        1. 4.6.6.1 Link type "alternate"
        2. 4.6.6.2 "author" 链接类型
        3. 4.6.6.3 "bookmark" 链接类型
        4. 4.6.6.4 Link type "canonical"
        5. 4.6.6.5 "dns-prefetch" 链接类型
        6. 4.6.6.6 "external" 链接类型
        7. 4.6.6.7 "help" 链接类型
        8. 4.6.6.8 Link type "icon"
        9. 4.6.6.9 "license" 链接类型
        10. 4.6.6.10 Link type "manifest"
        11. 4.6.6.11 Link type "modulepreload"
        12. 4.6.6.12 "nofollow" 链接类型
        13. 4.6.6.13 Link type "noopener"
        14. 4.6.6.14 Link type "noreferrer"
        15. 4.6.6.15 Link type "opener"
        16. 4.6.6.16 "pingback" 链接类型
        17. 4.6.6.17 "preconnect 链接类型"
        18. 4.6.6.18 "prefetch" 链接类型
        19. 4.6.6.19 Link type "preload"
        20. 4.6.6.20 "prerender" 链接类型
        21. 4.6.6.21 Link type "search"
        22. 4.6.6.22 Link type "stylesheet"
        23. 4.6.6.23 "tag" 链接类型
        24. 4.6.6.24 顺序链接类型
          1. 4.6.6.24.1 "next" 链接类型
          2. 4.6.6.24.2 "prev" 链接类型
        25. 4.6.6.25 其他链接类型
    7. 4.7 Edits
      1. 4.7.1 The ins element
      2. 4.7.2 The del element
      3. 4.7.3 Attributes common to ins and del elements
      4. 4.7.4 编辑与段落
      5. 4.7.5 编辑与列表
      6. 4.7.6 编辑与表格
    8. 4.8 嵌入内容
      1. 4.8.1 The picture element
      2. 4.8.2 The source element
      3. 4.8.3 The img element
      4. 4.8.4 图片
        1. 4.8.4.1 概述
          1. 4.8.4.1.1 自适应图片
        2. 4.8.4.2 Attributes common to source, img, and link elements
          1. 4.8.4.2.1 Srcset attributes
          2. 4.8.4.2.2 Sizes attributes
        3. 4.8.4.3 Processing model
          1. 4.8.4.3.1 When to obtain images
          2. 4.8.4.3.2 响应 DOM 变化
          3. 4.8.4.3.3 The list of available images
          4. 4.8.4.3.4 Decoding images
          5. 4.8.4.3.5 Updating the image data
          6. 4.8.4.3.6 Selecting an image source
          7. 4.8.4.3.7 Updating the source set
          8. 4.8.4.3.8 Parsing a srcset attribute
          9. 4.8.4.3.9 Parsing a sizes attribute
          10. 4.8.4.3.10 源像素密度规范化
          11. 4.8.4.3.11 Reacting to environment changes
        4. 4.8.4.4 为图片提供替代文字的要求
          1. 4.8.4.4.1 通用指引
          2. 4.8.4.4.2 只包含图片的链接或按钮
          3. 4.8.4.4.3 A phrase or paragraph with an alternative graphical representation: charts, diagrams, graphs, maps, illustrations
          4. 4.8.4.4.4 带有替代图形表示的短语或标签:图标,徽标
          5. 4.8.4.4.5 Text that has been rendered to a graphic for typographical effect
          6. 4.8.4.4.6 A graphical representation of some of the surrounding text
          7. 4.8.4.4.7 辅助性图片
          8. 4.8.4.4.8 不提供任何信息的纯装饰性图片
          9. 4.8.4.4.9 组成但个没有链接的大图的图片组
          10. 4.8.4.4.10 组成单个有链接的大图的图片组
          11. 4.8.4.4.11 内容的关键部分
          12. 4.8.4.4.12 不是给用户看的图片
          13. 4.8.4.4.13 An image in an email or private document intended for a specific person who is known to be able to view images
          14. 4.8.4.4.14 Guidance for markup generators
          15. 4.8.4.4.15 规范检查工具指引
      5. 4.8.5 The iframe element
      6. 4.8.6 The embed element
      7. 4.8.7 The object element
      8. 4.8.8 The param element
      9. 4.8.9 video 元素
      10. 4.8.10 The audio element
      11. 4.8.11 The track element
      12. 4.8.12 Media elements
        1. 4.8.12.1 Error codes
        2. 4.8.12.2 Location of the media resource
        3. 4.8.12.3 MIME types
        4. 4.8.12.4 网络状态
        5. 4.8.12.5 Loading the media resource
        6. 4.8.12.6 Offsets into the media resource
        7. 4.8.12.7 Ready states
        8. 4.8.12.8 Playing the media resource
        9. 4.8.12.9 Seeking
        10. 4.8.12.10 多媒体轨道的媒体资源
          1. 4.8.12.10.1 AudioTrackList and VideoTrackList objects
          2. 4.8.12.10.2 声明式地选择特定的音频和视频轨道
        11. 4.8.12.11 计时字幕
          1. 4.8.12.11.1 Text track model
          2. 4.8.12.11.2 Sourcing in-band text tracks
          3. 4.8.12.11.3 Sourcing out-of-band text tracks
          4. 4.8.12.11.4 显示各种格式的 字幕提示 的 指南
          5. 4.8.12.11.5 Text track API
          6. 4.8.12.11.6 Event handlers for objects of the text track APIs
          7. 4.8.12.11.7 元数据字幕的最佳实践
        12. 4.8.12.12 通过 URL 识别轨道类型
        13. 4.8.12.13 User interface
        14. 4.8.12.14 Time ranges
        15. 4.8.12.15 The TrackEvent interface
        16. 4.8.12.16 Events summary
        17. 4.8.12.17 Security and privacy considerations
        18. 4.8.12.18 作者使用媒体元素的最佳实践
        19. 4.8.12.19 Best practices for implementers of media elements
      13. 4.8.13 The map element
      14. 4.8.14 The area element
      15. 4.8.15 图片映射
        1. 4.8.15.1 编写
        2. 4.8.15.2 Processing model
      16. 4.8.16 MathML
      17. 4.8.17 SVG
      18. 4.8.18 Dimension attributes
    9. 4.9 表格数据
      1. 4.9.1 The table element
        1. 4.9.1.1 描述表格的技术
        2. 4.9.1.2 表格设计技术
      2. 4.9.2 The caption element
      3. 4.9.3 The colgroup element
      4. 4.9.4 The col element
      5. 4.9.5 The tbody element
      6. 4.9.6 The thead element
      7. 4.9.7 The tfoot element
      8. 4.9.8 The tr element
      9. 4.9.9 The td element
      10. 4.9.10 The th element
      11. 4.9.11 Attributes common to td and th elements
      12. 4.9.12 Processing model
        1. 4.9.12.1 Forming a table
        2. 4.9.12.2 Forming relationships between data cells and header cells
      13. 4.9.13 示例
    10. 4.10 表单
      1. 4.10.1 概述
        1. 4.10.1.1 编写表单的用户界面
        2. 4.10.1.2 实现服务器端表单处理
        3. 4.10.1.3 配置表单与服务器通信
        4. 4.10.1.4 客户端表单验证
        5. 4.10.1.5 启用表单控件的客户端自动填充
        6. 4.10.1.6 Improving the user experience on mobile devices
        7. 4.10.1.7 The difference between the field type, the autofill field name, and the input modality
        8. 4.10.1.8 日期、时间和数字格式
      2. 4.10.2 Categories
      3. 4.10.3 The form element
      4. 4.10.4 The label element
      5. 4.10.5 The input element
        1. 4.10.5.1 type 属性的状态
          1. 4.10.5.1.1 Hidden state (type=hidden)
          2. 4.10.5.1.2 Text (type=text) state and Search state (type=search)
          3. 4.10.5.1.3 Telephone state (type=tel)
          4. 4.10.5.1.4 URL state (type=url)
          5. 4.10.5.1.5 Email state (type=email)
          6. 4.10.5.1.6 Password state (type=password)
          7. 4.10.5.1.7 Date state (type=date)
          8. 4.10.5.1.8 Month state (type=month)
          9. 4.10.5.1.9 Week state (type=week)
          10. 4.10.5.1.10 Time state (type=time)
          11. 4.10.5.1.11 Local Date and Time state (type=datetime-local)
          12. 4.10.5.1.12 Number state (type=number)
          13. 4.10.5.1.13 Range state (type=range)
          14. 4.10.5.1.14 Color state (type=color)
          15. 4.10.5.1.15 Checkbox state (type=checkbox)
          16. 4.10.5.1.16 Radio Button state (type=radio)
          17. 4.10.5.1.17 File Upload state (type=file)
          18. 4.10.5.1.18 Submit Button state (type=submit)
          19. 4.10.5.1.19 Image Button state (type=image)
          20. 4.10.5.1.20 Reset Button state (type=reset)
          21. 4.10.5.1.21 Button state (type=button)
        2. 4.10.5.2 关于表单控件的本地化的实现笔记
        3. 4.10.5.3 通用 input 元素属性
          1. 4.10.5.3.1 The maxlength and minlength attributes
          2. 4.10.5.3.2 size 属性
          3. 4.10.5.3.3 readonly 属性
          4. 4.10.5.3.4 required 属性
          5. 4.10.5.3.5 multiple 属性
          6. 4.10.5.3.6 pattern 属性
          7. 4.10.5.3.7 minmax 属性
          8. 4.10.5.3.8 The step attribute
          9. 4.10.5.3.9 list 属性
          10. 4.10.5.3.10 The placeholder attribute
        4. 4.10.5.4 Common input element APIs
        5. 4.10.5.5 通用事件行为
      6. 4.10.6 The button element
      7. 4.10.7 The select element
      8. 4.10.8 The datalist element
      9. 4.10.9 The optgroup element
      10. 4.10.10 The option element
      11. 4.10.11 The textarea element
      12. 4.10.12 The output element
      13. 4.10.13 The progress element
      14. 4.10.14 The meter element
      15. 4.10.15 The fieldset element
      16. 4.10.16 The legend element
      17. 4.10.17 Form control infrastructure
        1. 4.10.17.1 A form control's value
        2. 4.10.17.2 可变性
        3. 4.10.17.3 Association of controls and forms
      18. 4.10.18 表单控件通用的属性
        1. 4.10.18.1 Naming form controls: the name attribute
        2. 4.10.18.2 提交元素 element directionality: the dirname attribute
        3. 4.10.18.3 Limiting user input length: the maxlength attribute
        4. 4.10.18.4 Setting minimum input length requirements: the minlength attribute
        5. 4.10.18.5 Enabling and disabling form controls: the disabled attribute
        6. 4.10.18.6 Form submission attributes
        7. 4.10.18.7 自动填充
          1. 4.10.18.7.1 Autofilling form controls: the autocomplete attribute
          2. 4.10.18.7.2 Processing model
      19. 4.10.19 APIs for the text control selections
      20. 4.10.20 约束
        1. 4.10.20.1 定义
        2. 4.10.20.2 Constraint validation
        3. 4.10.20.3 The constraint validation API
        4. 4.10.20.4 安全性
      21. 4.10.21 表单提交
        1. 4.10.21.1 概述
        2. 4.10.21.2 隐式提交
        3. 4.10.21.3 Form submission algorithm
        4. 4.10.21.4 Constructing the entry list
        5. 4.10.21.5 Selecting a form submission encoding
        6. 4.10.21.6 URL 编码的表单数据
        7. 4.10.21.7 Multipart form data
        8. 4.10.21.8 Plain text form data
        9. 4.10.21.9 The SubmitEvent interface
        10. 4.10.21.10 The FormDataEvent interface
      22. 4.10.22 表单重置
    11. 4.11 Interactive elements
      1. 4.11.1 The details element
      2. 4.11.2 The summary element
      3. 4.11.3 命令
        1. 4.11.3.1 Facets
        2. 4.11.3.2 使用 a 元素来定义命令
        3. 4.11.3.3 使用 button 元素来定义命令
        4. 4.11.3.4 使用 input 元素来定义命令
        5. 4.11.3.5 Using the option element to define a command
        6. 4.11.3.6legend 元素上 使用 accesskey 属性 来定义一个命令
        7. 4.11.3.7 使用 accesskey 属性给其他元素定义命令
      4. 4.11.4 The dialog element
    12. 4.12 脚本
      1. 4.12.1 The script element
        1. 4.12.1.1 Processing model
        2. 4.12.1.2 Scripting languages
        3. 4.12.1.3 script 元素内容的限制
        4. 4.12.1.4 Inline documentation for external scripts
        5. 4.12.1.5 Interaction of script elements and XSLT
      2. 4.12.2 The noscript element
      3. 4.12.3 The template element
        1. 4.12.3.1 Interaction of template elements with XSLT and XPath
      4. 4.12.4 The slot element
      5. 4.12.5 The canvas element
        1. 4.12.5.1 The 2D rendering context
          1. 4.12.5.1.1 实现说明
          2. 4.12.5.1.2 Canvas 状态
          3. 4.12.5.1.3 Line styles
          4. 4.12.5.1.4 Text styles
          5. 4.12.5.1.5 Building paths
          6. 4.12.5.1.6 Path2D objects
          7. 4.12.5.1.7 Transformations
          8. 4.12.5.1.8 Image sources for 2D rendering contexts
          9. 4.12.5.1.9 Fill and stroke styles
          10. 4.12.5.1.10 Drawing rectangles to the bitmap
          11. 4.12.5.1.11 Drawing text to the bitmap
          12. 4.12.5.1.12 Drawing paths to the canvas
          13. 4.12.5.1.13 Drawing focus rings and scrolling paths into view
          14. 4.12.5.1.14 Drawing images
          15. 4.12.5.1.15 Pixel manipulation
          16. 4.12.5.1.16 合成
          17. 4.12.5.1.17 Image smoothing
          18. 4.12.5.1.18 Shadows
          19. 4.12.5.1.19 滤镜
          20. 4.12.5.1.20 使用外部定义的 SVG 滤镜
          21. 4.12.5.1.21 Drawing model
          22. 4.12.5.1.22 最佳实践
          23. 4.12.5.1.23 示例
        2. 4.12.5.2 ImageBitmap 渲染上下文
          1. 4.12.5.2.1 Introduction
          2. 4.12.5.2.2 The ImageBitmapRenderingContext interface
        3. 4.12.5.3 The OffscreenCanvas interface
          1. 4.12.5.3.1 The offscreen 2D rendering context
        4. 4.12.5.4 Color spaces and color correction
        5. 4.12.5.5 Serializing bitmaps to a file
        6. 4.12.5.6 canvas 元素的安全问题
    13. 4.13 Custom elements
      1. 4.13.1 概述
        1. 4.13.1.1 创建自主的 Custom Element
        2. 4.13.1.2 Creating a form-associated custom element
        3. 4.13.1.3 Creating a custom element with default accessible roles, states, and properties
        4. 4.13.1.4 创建定制的内建元素
        5. 4.13.1.5 自主 custom element 的缺点
        6. 4.13.1.6 在创建之后升级元素
      2. 4.13.2 Requirements for custom element constructors and reactions
      3. 4.13.3 核心概念
      4. 4.13.4 CustomElementRegistry 接口
      5. 4.13.5 升级
      6. 4.13.6 Custom element reactions
      7. 4.13.7 Element internals
        1. 4.13.7.1 The ElementInternals interface
        2. 4.13.7.2 Shadow root access
        3. 4.13.7.3 Form-associated custom elements
        4. 4.13.7.4 Accessibility semantics
    14. 4.14 Common idioms without dedicated elements
      1. 4.14.1 面包屑导航
      2. 4.14.2 标签云
      3. 4.14.3 对话
      4. 4.14.4 脚注
    15. 4.15 Disabled elements
    16. 4.16 使用选择符和 CSS 匹配 HTML 元素
      1. 4.16.1 CSS 'attr()' 函数的大小写敏感性
      2. 4.16.2 Case-sensitivity of selectors
      3. 4.16.3 Pseudo-classes
  5. 5 微数据
    1. 5.1 概述
      1. 5.1.1 Overview
      2. 5.1.2 The basic syntax
      3. 5.1.3 Typed items
      4. 5.1.4 Global identifiers for items
      5. 5.1.5 Selecting names when defining vocabularies
    2. 5.2 Encoding microdata
      1. 5.2.1 The microdata model
      2. 5.2.2 Items
      3. 5.2.3 Names: the itemprop attribute
      4. 5.2.4 Values
      5. 5.2.5 Associating names with items
      6. 5.2.6 Microdata and other namespaces
    3. 5.3 Sample microdata vocabularies
      1. 5.3.1 vCard
        1. 5.3.1.1 Conversion to vCard
        2. 5.3.1.2 Examples
      2. 5.3.2 vEvent
        1. 5.3.2.1 Conversion to iCalendar
        2. 5.3.2.2 Examples
      3. 5.3.3 Licensing works
        1. 5.3.3.1 Examples
    4. 5.4 Converting HTML to other formats
      1. 5.4.1 JSON
  6. 6 用户交互
    1. 6.1 hidden 属性
    2. 6.2 Inert subtrees
    3. 6.3 Tracking user activation
      1. 6.3.1 Data model
      2. 6.3.2 Processing model
      3. 6.3.3 APIs gated by user activation
    4. 6.4 Activation behavior of elements
    5. 6.5 焦点
      1. 6.5.1 概述
      2. 6.5.2 数据模型
      3. 6.5.3 The tabindex attribute
      4. 6.5.4 Processing model
      5. 6.5.5 Sequential focus navigation
      6. 6.5.6 Focus management APIs
      7. 6.5.7 The autofocus attribute
    6. 6.6 指定快捷键
      1. 6.6.1 概述
      2. 6.6.2 The accesskey attribute
      3. 6.6.3 Processing model
    7. 6.7 编辑
      1. 6.7.1 Making document regions editable: The contenteditable content attribute
      2. 6.7.2 Making entire documents editable: the designMode getter and setter
      3. 6.7.3 Best practices for in-page editors
      4. 6.7.4 Editing APIs
      5. 6.7.5 Spelling and grammar checking
      6. 6.7.6 Autocapitalization
      7. 6.7.7 Input modalities: the inputmode attribute
      8. 6.7.8 Input modalities: the enterkeyhint attribute
    8. 6.8 Find-in-page
      1. 6.8.1 Introduction
      2. 6.8.2 Interaction with selection
    9. 6.9 Drag and drop
      1. 6.9.1 Introduction
      2. 6.9.2 The drag data store
      3. 6.9.3 The DataTransfer interface
        1. 6.9.3.1 The DataTransferItemList interface
        2. 6.9.3.2 The DataTransferItem interface
      4. 6.9.4 The DragEvent interface
      5. 6.9.5 Processing model
      6. 6.9.6 Events summary
      7. 6.9.7 The draggable attribute
      8. 6.9.8 拖放模型中的安全风险
  7. 7 加载 Web 页面
    1. 7.1 Browsing contexts
      1. 7.1.1 Creating browsing contexts
      2. 7.1.2 Related browsing contexts
        1. 7.1.2.1 Navigating related browsing contexts in the DOM
      3. 7.1.3 Security
      4. 7.1.4 浏览上下文分组
      5. 7.1.5 Browsing context names
    2. 7.2 Window, WindowProxy, 和 Location 对象的安全基础设施
      1. 7.2.1 Integration with IDL
      2. 7.2.2 Shared internal slot: [[CrossOriginPropertyDescriptorMap]]
      3. 7.2.3 Shared abstract operations
        1. 7.2.3.1 CrossOriginProperties ( O )
        2. 7.2.3.2 CrossOriginPropertyFallback ( P )
        3. 7.2.3.3 IsPlatformObjectSameOrigin ( O )
        4. 7.2.3.4 CrossOriginGetOwnPropertyHelper ( O, P )
        5. 7.2.3.5 CrossOriginGet ( O, P, Receiver )
        6. 7.2.3.6 CrossOriginSet ( O, P, V, Receiver )
        7. 7.2.3.7 CrossOriginOwnPropertyKeys ( O )
    3. 7.3 The Window object
      1. 7.3.1 APIs for creating and navigating browsing contexts by name
      2. 7.3.2 Accessing other browsing contexts
      3. 7.3.3 Named access on the Window object
      4. 7.3.4 Discarding browsing contexts
      5. 7.3.5 Closing browsing contexts
      6. 7.3.6 Browser interface elements
      7. 7.3.7 Script settings for Window objects
    4. 7.4 The WindowProxy exotic object
      1. 7.4.1 [[GetPrototypeOf]] ( )
      2. 7.4.2 [[SetPrototypeOf]] ( V )
      3. 7.4.3 [[IsExtensible]] ( )
      4. 7.4.4 [[PreventExtensions]] ( )
      5. 7.4.5 [[GetOwnProperty]] ( P )
      6. 7.4.6 [[DefineOwnProperty]] ( P, Desc )
      7. 7.4.7 [[Get]] ( P, Receiver )
      8. 7.4.8 [[Set]] ( P, V, Receiver )
      9. 7.4.9 [[Delete]] ( P )
      10. 7.4.10 [[OwnPropertyKeys]] ( )
    5. 7.5 Origin
      1. 7.5.1 Sites
      2. 7.5.2 Relaxing the same-origin restriction
      3. 7.5.3 Origin isolation
    6. 7.6 Sandboxing
    7. 7.7 Cross-origin opener policies
      1. 7.7.1 The `Cross-Origin-Opener-Policy` header
      2. 7.7.2 Browsing context group switches due to cross-origin opener policy
    8. 7.8 Cross-origin embedder policies
      1. 7.8.1 The headers
      2. 7.8.2 Embedder policy checks
    9. 7.9 Session history and navigation
      1. 7.9.1 Browsing sessions
      2. 7.9.2 The session history of browsing contexts
      3. 7.9.3 The History interface
      4. 7.9.4 Implementation notes for session history
      5. 7.9.5 The Location interface
        1. 7.9.5.1 [[GetPrototypeOf]] ( )
        2. 7.9.5.2 [[SetPrototypeOf]] ( V )
        3. 7.9.5.3 [[IsExtensible]] ( )
        4. 7.9.5.4 [[PreventExtensions]] ( )
        5. 7.9.5.5 [[GetOwnProperty]] ( P )
        6. 7.9.5.6 [[DefineOwnProperty]] ( P, Desc )
        7. 7.9.5.7 [[Get]] ( P, Receiver )
        8. 7.9.5.8 [[Set]] ( P, V, Receiver )
        9. 7.9.5.9 [[Delete]] ( P )
        10. 7.9.5.10 [[OwnPropertyKeys]] ( )
    10. 7.10 Browsing the web
      1. 7.10.1 Navigating across documents
      2. 7.10.2 HTML 文件的页面加载处理模型
      3. 7.10.3 XML 文件的页面加载处理模型
      4. 7.10.4 文本文件的页面加载处理模型
      5. 7.10.5 multipart/x-mixed-replace 资源的媒体的页面加载处理模型
      6. 7.10.6 媒体的页面加载处理模型
      7. 7.10.7 使用插件的内容的页面加载处理模型
      8. 7.10.8 没有 DOM 的内联内容的页面加载处理模型
      9. 7.10.9 Navigating to a fragment
      10. 7.10.10 History traversal
        1. 7.10.10.1 Persisted history entry state
        2. 7.10.10.2 The PopStateEvent interface
        3. 7.10.10.3 The HashChangeEvent interface
        4. 7.10.10.4 The PageTransitionEvent interface
      11. 7.10.11 Loading documents
      12. 7.10.12 Unloading documents
        1. 7.10.12.1 The BeforeUnloadEvent interface
      13. 7.10.13 Aborting a document load
      14. 7.10.14 The `X-Frame-Options` header
    11. 7.11 Offline web applications
      1. 7.11.1 概述
        1. 7.11.1.1 支持遗留应用的离线缓存
        2. 7.11.1.2 Events summary
      2. 7.11.2 Application caches
      3. 7.11.3 缓存清单语法
        1. 7.11.3.1 一些示例清单
        2. 7.11.3.2 Writing cache manifests
        3. 7.11.3.3 Parsing cache manifests
      4. 7.11.4 Downloading or updating an application cache
      5. 7.11.5 应用缓存选择算法
      6. 7.11.6 Changes to the networking model
      7. 7.11.7 应用缓存过期
      8. 7.11.8 磁盘空间
      9. 7.11.9 离线应用缓存的安全问题
      10. 7.11.10 Application cache API
      11. 7.11.11 Browser state
  8. 8 Web 应用 API
    1. 8.1 脚本
      1. 8.1.1 概述
      2. 8.1.2 Agents and agent clusters
        1. 8.1.2.1 Integration with the JavaScript agent formalism
        2. 8.1.2.2 Integration with the JavaScript agent cluster formalism
      3. 8.1.3 Realms and their counterparts
        1. 8.1.3.1 Environments
        2. 8.1.3.2 Environment settings objects
        3. 8.1.3.3 Realms, settings objects, and global objects
          1. 8.1.3.3.1 Entry
          2. 8.1.3.3.2 Incumbent
          3. 8.1.3.3.3 Current
          4. 8.1.3.3.4 Relevant
        4. 8.1.3.4 Enabling and disabling scripting
        5. 8.1.3.5 Secure contexts
      4. 8.1.4 Script processing model
        1. 8.1.4.1 Scripts
        2. 8.1.4.2 Fetching scripts
        3. 8.1.4.3 Creating scripts
        4. 8.1.4.4 Calling scripts
        5. 8.1.4.5 Killing scripts
        6. 8.1.4.6 Runtime script errors
        7. 8.1.4.7 Unhandled promise rejections
      5. 8.1.5 JavaScript specification host hooks
        1. 8.1.5.1 HostEnqueuePromiseJob(job, realm)
        2. 8.1.5.2 HostEnsureCanCompileStrings(callerRealm, calleeRealm)
        3. 8.1.5.3 HostPromiseRejectionTracker(promise, operation)
        4. 8.1.5.4 Module-related host hooks
          1. 8.1.5.4.1 HostGetImportMetaProperties(moduleRecord)
          2. 8.1.5.4.2 HostImportModuleDynamically(referencingScriptOrModule, specifier, promiseCapability)
          3. 8.1.5.4.3 HostResolveImportedModule(referencingScriptOrModule, specifier)
      6. 8.1.6 事件循环
        1. 8.1.6.1 定义
        2. 8.1.6.2 Queuing tasks
        3. 8.1.6.3 处理模型
        4. 8.1.6.4 Generic task sources
        5. 8.1.6.5 Dealing with the event loop from other specifications
      7. 8.1.7 事件
        1. 8.1.7.1 Event handlers
        2. 8.1.7.2 Event handlers on elements, Document objects, and Window objects
          1. 8.1.7.2.1 IDL definitions
        3. 8.1.7.3 Event firing
    2. 8.2 The WindowOrWorkerGlobalScope mixin
    3. 8.3 Base64 utility methods
    4. 8.4 Dynamic markup insertion
      1. 8.4.1 Opening the input stream
      2. 8.4.2 Closing the input stream
      3. 8.4.3 document.write()
      4. 8.4.4 document.writeln()
    5. 8.5 DOM parsing
    6. 8.6 Timers
    7. 8.7 Microtask queuing
    8. 8.8 用户提示
      1. 8.8.1 Simple dialogs
      2. 8.8.2 Printing
    9. 8.9 System state and capabilities
      1. 8.9.1 The Navigator object
        1. 8.9.1.1 Client identification
        2. 8.9.1.2 Language preferences
        3. 8.9.1.3 Custom scheme handlers: the registerProtocolHandler() method
          1. 8.9.1.3.1 Security and privacy
        4. 8.9.1.4 Cookies
        5. 8.9.1.5 Plugins
    10. 8.10 Images
    11. 8.11 Animation frames
  9. 9 通信
    1. 9.1 MessageEvent 接口
    2. 9.2 服务器发送的事件
      1. 9.2.1 概述
      2. 9.2.2 The EventSource interface
      3. 9.2.3 Processing model
      4. 9.2.4 Parsing an event stream
      5. 9.2.5 Interpreting an event stream
      6. 9.2.6 Authoring notes
      7. 9.2.7 无连接推送和其他特性
      8. 9.2.8 垃圾回收
      9. 9.2.9 Implementation advice
    3. 9.3 Web sockets
      1. 9.3.1 概述
      2. 9.3.2 The WebSocket interface
      3. 9.3.3 Feedback from the protocol
      4. 9.3.4 Ping and Pong frames
      5. 9.3.5 The CloseEvent interface
      6. 9.3.6 Garbage collection
    4. 9.4 跨文档通信
      1. 9.4.1 概述
      2. 9.4.2 安全
        1. 9.4.2.1 作者
        2. 9.4.2.2 用户代理
      3. 9.4.3 发布消息
    5. 9.5 通道
      1. 9.5.1 概述
        1. 9.5.1.1 示例
        2. 9.5.1.2 端口作为 Web 上对象能力模型的基础
        3. 9.5.1.3 端口作为抽象服务实现的基础
      2. 9.5.2 消息通道
      3. 9.5.3 消息端口
      4. 9.5.4 广播给多个端口
      5. 9.5.5 端口与垃圾回收
    6. 9.6 向其他浏览上下文广播
  10. 10 Web 工作线程
    1. 10.1 概述
      1. 10.1.1 涵盖范围
      2. 10.1.2 示例
        1. 10.1.2.1 数字密集型计算的后台 worker
        2. 10.1.2.2 使用 JavaScript 模块作为 worker
        3. 10.1.2.3 共享 worker 概述
        4. 10.1.2.4 通过共享 Worker 来共享状态
        5. 10.1.2.5 委托
        6. 10.1.2.6 Providing libraries
      3. 10.1.3 教程
        1. 10.1.3.1 创建专用工作线程
        2. 10.1.3.2 与专用 Worker 通信
        3. 10.1.3.3 共享工作线程
    2. 10.2 基础设施
      1. 10.2.1 全局作用域
        1. 10.2.1.1 WorkerGlobalScope 通用接口
        2. 10.2.1.2 专用 Worker 与 DedicatedWorkerGlobalScope 接口
        3. 10.2.1.3 共享 worker 与 SharedWorkerGlobalScope 接口
      2. 10.2.2 事件循环
      3. 10.2.3 The worker's lifetime
      4. 10.2.4 Processing model
      5. 10.2.5 Runtime script errors
      6. 10.2.6 创建 Worker
        1. 10.2.6.1 The AbstractWorker mixin
        2. 10.2.6.2 Script settings for workers
        3. 10.2.6.3 Dedicated workers and the Worker interface
        4. 10.2.6.4 Shared workers and the SharedWorker interface
      7. 10.2.7 Concurrent hardware capabilities
    3. 10.3 Worker 中可用的 API
      1. 10.3.1 Importing scripts and libraries
      2. 10.3.2 The WorkerNavigator interface
      3. 10.3.3 The WorkerLocation interface
  11. 11 Worklets
    1. 11.1 Introduction
      1. 11.1.1 Motivations
      2. 11.1.2 Code idempotence
      3. 11.1.3 Speculative evaluation
    2. 11.2 Examples
      1. 11.2.1 Loading scripts
      2. 11.2.2 Registering a class and invoking its methods
    3. 11.3 Infrastructure
      1. 11.3.1 The global scope
        1. 11.3.1.1 Agents and event loops
        2. 11.3.1.2 Creation and termination
        3. 11.3.1.3 Script settings for worklets
      2. 11.3.2 The Worklet class
      3. 11.3.3 The worklet's lifetime
  12. 12 Web 存储
    1. 12.1 Introduction
    2. 12.2 API
      1. 12.2.1 The Storage interface
      2. 12.2.2 The sessionStorage getter
      3. 12.2.3 The localStorage getter
      4. 12.2.4 The StorageEvent interface
    3. 12.3 隐私
      1. 12.3.1 User tracking
      2. 12.3.2 Sensitivity of data
    4. 12.4 安全
      1. 12.4.1 DNS 欺骗攻击
      2. 12.4.2 Cross-directory attacks
      3. 12.4.3 Implementation risks
  13. 13 HTML 语法
    1. 13.1 Writing HTML documents
      1. 13.1.1 The DOCTYPE
      2. 13.1.2 Elements
        1. 13.1.2.1 Start tags
        2. 13.1.2.2 End tags
        3. 13.1.2.3 Attributes
        4. 13.1.2.4 Optional tags
        5. 13.1.2.5 内容模型限制
        6. 13.1.2.6 对原始文本和可转义的原始文本元素的内容的限制
      3. 13.1.3 文本
        1. 13.1.3.1 换行
      4. 13.1.4 Character references
      5. 13.1.5 CDATA 部分
      6. 13.1.6 注释
    2. 13.2 Parsing HTML documents
      1. 13.2.1 Overview of the parsing model
      2. 13.2.2 Parse errors
      3. 13.2.3 输入字节流
        1. 13.2.3.1 使用已知字符编码进行解析
        2. 13.2.3.2 Determining the character encoding
        3. 13.2.3.3 字符编码
        4. 13.2.3.4 Changing the encoding while parsing
        5. 13.2.3.5 Preprocessing the input stream
      4. 13.2.4 解析状态
        1. 13.2.4.1 The insertion mode
        2. 13.2.4.2 The stack of open elements
        3. 13.2.4.3 活动格式化元素列表
        4. 13.2.4.4 元素指针
        5. 13.2.4.5 其他解析状态标志
      5. 13.2.5 Tokenization
        1. 13.2.5.1 Data state
        2. 13.2.5.2 RCDATA state
        3. 13.2.5.3 RAWTEXT state
        4. 13.2.5.4 Script data state
        5. 13.2.5.5 PLAINTEXT state
        6. 13.2.5.6 Tag open state
        7. 13.2.5.7 End tag open state
        8. 13.2.5.8 Tag name state
        9. 13.2.5.9 RCDATA 小于号状态
        10. 13.2.5.10 RCDATA 结束标签打开状态
        11. 13.2.5.11 RCDATA end tag name state
        12. 13.2.5.12 RAWTEXT 小于号状态
        13. 13.2.5.13 RAWTEXT end tag open state
        14. 13.2.5.14 RAWTEXT end tag name state
        15. 13.2.5.15
        16. 13.2.5.16 Script data end tag open state
        17. 13.2.5.17 Script data end tag name state
        18. 13.2.5.18 脚本数据转义开始状态
        19. 13.2.5.19 脚本数据转义开始
        20. 13.2.5.20 脚本数据转义状态
        21. 13.2.5.21 脚本数据转义横线状态
        22. 13.2.5.22 Script data escaped dash dash state
        23. 13.2.5.23 脚本数据转义小于号状态
        24. 13.2.5.24 Script data escaped end tag open state
        25. 13.2.5.25 Script data escaped end tag name state
        26. 13.2.5.26 脚本数据双重转义开始状态
        27. 13.2.5.27 Script data double escaped state
        28. 13.2.5.28 脚本数据双重转义横线状态
        29. 13.2.5.29 Script data double escaped dash dash state
        30. 13.2.5.30 脚本数据双重转义小于号状态
        31. 13.2.5.31 脚本数据双重转义结束状态
        32. 13.2.5.32 Before attribute name state
        33. 13.2.5.33 Attribute name state
        34. 13.2.5.34 After attribute name state
        35. 13.2.5.35 Before attribute value state
        36. 13.2.5.36 Attribute value (double-quoted) state
        37. 13.2.5.37 Attribute value (single-quoted) state
        38. 13.2.5.38 Attribute value (unquoted) state
        39. 13.2.5.39 After attribute value (quoted) state
        40. 13.2.5.40 Self-closing start tag state
        41. 13.2.5.41 Bogus comment state
        42. 13.2.5.42 Markup declaration open state
        43. 13.2.5.43 Comment start state
        44. 13.2.5.44 Comment start dash state
        45. 13.2.5.45 Comment state
        46. 13.2.5.46 注释小于号状态
        47. 13.2.5.47 注释小于号感叹号状态
        48. 13.2.5.48 注释小于号感叹号横线状态
        49. 13.2.5.49 Comment less-than sign bang dash dash state
        50. 13.2.5.50 Comment end dash state
        51. 13.2.5.51 Comment end state
        52. 13.2.5.52 Comment end bang state
        53. 13.2.5.53 DOCTYPE state
        54. 13.2.5.54 Before DOCTYPE name state
        55. 13.2.5.55 DOCTYPE name state
        56. 13.2.5.56 After DOCTYPE name state
        57. 13.2.5.57 After DOCTYPE public keyword state
        58. 13.2.5.58 Before DOCTYPE public identifier state
        59. 13.2.5.59 DOCTYPE public identifier (double-quoted) state
        60. 13.2.5.60 DOCTYPE public identifier (single-quoted) state
        61. 13.2.5.61 After DOCTYPE public identifier state
        62. 13.2.5.62 Between DOCTYPE public and system identifiers state
        63. 13.2.5.63 After DOCTYPE system keyword state
        64. 13.2.5.64 Before DOCTYPE system identifier state
        65. 13.2.5.65 DOCTYPE system identifier (double-quoted) state
        66. 13.2.5.66 DOCTYPE system identifier (single-quoted) state
        67. 13.2.5.67 After DOCTYPE system identifier state
        68. 13.2.5.68 Bogus DOCTYPE state
        69. 13.2.5.69 CDATA 部分状态
        70. 13.2.5.70 CDATA 部分括号状态
        71. 13.2.5.71 CDATA 部分结束状态
        72. 13.2.5.72 Character reference state
        73. 13.2.5.73 Named character reference state
        74. 13.2.5.74 Ambiguous ampersand state
        75. 13.2.5.75 数字字符引用状态
        76. 13.2.5.76 Hexadecimal character reference start state
        77. 13.2.5.77 Decimal character reference start state
        78. 13.2.5.78 Hexadecimal character reference state
        79. 13.2.5.79 Decimal character reference state
        80. 13.2.5.80 数字字符引用结束状态
      6. 13.2.6 Tree construction
        1. 13.2.6.1 Creating and inserting nodes
        2. 13.2.6.2 解析只包含文本的元素
        3. 13.2.6.3 Closing elements that have implied end tags
        4. 13.2.6.4 解析 HTML 内容中的标记的规则
          1. 13.2.6.4.1 "initial" 插入模式
          2. 13.2.6.4.2 "before html" 插入模式
          3. 13.2.6.4.3 "before head" 插入模式
          4. 13.2.6.4.4 The "in head" insertion mode
          5. 13.2.6.4.5 "in head noscript" 插入模式
          6. 13.2.6.4.6 "after head" 插入模式
          7. 13.2.6.4.7 The "in body" insertion mode
          8. 13.2.6.4.8 The "text" insertion mode
          9. 13.2.6.4.9 "in table" 插入模式
          10. 13.2.6.4.10 The "in table text" insertion mode
          11. 13.2.6.4.11 The "in caption" 插入模式
          12. 13.2.6.4.12 "in column group" 插入模式
          13. 13.2.6.4.13 "in table body" 插入模式
          14. 13.2.6.4.14 "in row" 插入模式
          15. 13.2.6.4.15 "in cell" 插入模式
          16. 13.2.6.4.16 "in select" 插入模式
          17. 13.2.6.4.17 "in select in table" 插入模式
          18. 13.2.6.4.18 "in template" 插入模式
          19. 13.2.6.4.19 "after body" 插入模式
          20. 13.2.6.4.20 "in frameset" 插入模式
          21. 13.2.6.4.21 "after frameset" 插入模式
          22. 13.2.6.4.22 "after after body" 插入模式
          23. 13.2.6.4.23 "after after frameset" 插入模式
        5. 13.2.6.5 The rules for parsing tokens in foreign content
      7. 13.2.7 The end
      8. 13.2.8 Coercing an HTML DOM into an infoset
      9. 13.2.9 解析器的错误处理和奇怪的场景介绍
        1. 13.2.9.1 错误嵌套的标签:<b><i></b></i>
        2. 13.2.9.2 错误嵌套的标签:<b><p></b></p>
        3. 13.2.9.3 Unexpected markup in tables
        4. 13.2.9.4 解析时修改页面的脚本
        5. 13.2.9.5 在多个文档中移动的脚本的执行
        6. 13.2.9.6 Unclosed formatting elements
    3. 13.3 序列化 HTML 片段
    4. 13.4 解析 HTML 片段
    5. 13.5 Named character references
  14. 14 XML 语法
    1. 14.1 以 XML 语法编写文档
    2. 14.2 Parsing XML documents
    3. 14.3 Serializing XML fragments
    4. 14.4 Parsing XML fragments
  15. 15 渲染
    1. 15.1 Introduction
    2. 15.2 The CSS user agent style sheet and presentational hints
    3. 15.3 Non-replaced elements
      1. 15.3.1 Hidden elements
      2. 15.3.2 The page
      3. 15.3.3 Flow content
      4. 15.3.4 Phrasing content
      5. 15.3.5 Bidirectional text
      6. 15.3.6 Sections and headings
      7. 15.3.7 Lists
      8. 15.3.8 Tables
      9. 15.3.9 Margin collapsing quirks
      10. 15.3.10 Form controls
      11. 15.3.11 The hr element
      12. 15.3.12 The fieldset and legend elements
    4. 15.4 Replaced elements
      1. 15.4.1 Embedded content
      2. 15.4.2 Images
      3. 15.4.3 Attributes for embedded content and images
      4. 15.4.4 Image maps
    5. 15.5 微件
      1. 15.5.1 简介
      2. 15.5.2 Button layout
      3. 15.5.3 button 元素
      4. 15.5.4 detailssummary 元素
      5. 15.5.5 input 元素作为文本输入微件
      6. 15.5.6 The input element as domain-specific widgets
      7. 15.5.7 The input element as a range control
      8. 15.5.8 The input element as a color well
      9. 15.5.9 The input element as a checkbox and radio button widgets
      10. 15.5.10 The input element as a file upload control
      11. 15.5.11 The input element as a button
      12. 15.5.12 The marquee element
      13. 15.5.13 The meter element
      14. 15.5.14 The progress element
      15. 15.5.15 The select element
      16. 15.5.16 The textarea element
    6. 15.6 Frames and framesets
    7. 15.7 Interactive media
      1. 15.7.1 Links, forms, and navigation
      2. 15.7.2 The title attribute
      3. 15.7.3 Editing hosts
      4. 15.7.4 Text rendered in native user interfaces
    8. 15.8 Print media
    9. 15.9 Unstyled XML documents
  16. 16 废弃的特性
    1. 16.1 Obsolete but conforming features
      1. 16.1.1 Warnings for obsolete but conforming features
    2. 16.2 Non-conforming features
    3. 16.3 Requirements for implementations
      1. 16.3.1 The marquee element
      2. 16.3.2 Frames
      3. 16.3.3 Other elements, attributes and APIs
  17. 17 IANA 注意事项
    1. 17.1 text/html
    2. 17.2 multipart/x-mixed-replace
    3. 17.3 application/xhtml+xml
    4. 17.4 text/cache-manifest
    5. 17.5 text/ping
    6. 17.6 application/microdata+json
    7. 17.7 text/event-stream
    8. 17.8 `Cross-Origin-Embedder-Policy`
    9. 17.9 `Cross-Origin-Embedder-Policy-Report-Only`
    10. 17.10 `Cross-Origin-Opener-Policy`
    11. 17.11 `Origin-Isolation`
    12. 17.12 `Ping-From`
    13. 17.13 `Ping-To`
    14. 17.14 `Refresh`
    15. 17.15 `Last-Event-ID`
    16. 17.16 `X-Frame-Options`
    17. 17.17 web+ scheme prefix
  18. 索引
    1. Elements
    2. Element content categories
    3. Attributes
    4. Element Interfaces
    5. 所有接口
    6. Events
    7. MIME 类型
  19. References
  20. 致谢
  21. Intellectual property rights

1 概述

1.1 本标准的适用范围

本标准详细地定义了 Web 平台的很大一部分内容。Web 平台的标准栈中,它相对于其他标准的定位可以总结为:

CSS SVG MathML NPAPI Geo Fetch CSP JPEG GIF PNG THIS SPECIFICATION HTTP TLS MQ DOM Unicode Web IDL MIME URL XML JavaScript Encodings

1.2 这是 HTML5 吗?

This section is non-normative.

简单地说:是的。

详细地说,广义的 "HTML5" 是指一系列的现代 Web 技术。 这些技术中很多都由 WHATWG 开发,本文档就是其中之一。 其他的可以在这里访问: the WHATWG Standards overview

1.3 背景

This section is non-normative.

HTML 是万维网的核心标记语言。最初 HTML 主要设计为在语义级别描述科学文档的语言。 然而它的总体设计使它在接下来的几年中能够适配一些其他类型的文档,甚至包括应用程序。

1.4 受众

This section is non-normative.

本标准是为以下读者提供的:使用了本标准定义的特性的文档和脚本的作者, 用于操作那些使用了本标准定义的特性的页面的工具的实现者, 希望根据本标准的要求确认文档或实现的正确性的个人。

本文档对还没有整体熟悉 Web 技术的读者可能不合适, 因为在有些地方为精确性而省略了具体阐述,为完整性而较为简洁概括。 易懂的教程和编写指南可以为这个话题提供更加温和的介绍。

具体地,为了完整地理解本标准中那些更加技术的部分,对 DOM 基础的熟悉是必要的。 对 Web IDL,HTTP,XML,Unicode,字符编码,JavaScript 和 CSS 的理解在有些地方也有帮助,但并非完全必要。

1.5 范围

This section is non-normative.

本标准只限于为编写可访问的 Web 页面(从静态文档到动态应用) 提供语义级别的标记语言,以及相应的语义级别的脚本 API。

本标准的范围不包括提供具体媒体的自定义呈现机制(尽管 Web 浏览器的默认渲染规则在本标准末尾有所涵盖, 一些挂钩到 CSS 的机制也作为语言的一部分加以提供)。

本标准的范围并非要描述整个操作系统。具体地,硬件配置软件、图像操作工具、 以及用户在高端工作站日常使用的应用程序都在范围之外。 对于应用软件,本标准只针对用户偶尔使用的,或定期使用但在不同地点的, 且 CPU 要求较低的特定应用。这样的应用例如在线购物系统、搜索系统、游戏(尤其是多人在线游戏)、 公开电话簿或地址簿、通信软件(邮件客户端、即时通信客户端、讨论软件), 文档编辑软件等。

1.6 历史

This section is non-normative.

在最初的5年中(1990-1995),HTML经历了若干次修订和扩展。最初由 CERN 主要托管,随后是 IETF。

随着 W3C 的诞生,HTML 的开发再次易主。1995 年第一次扩展 HTML 的尝试(HTML 3.0)以失败告终,随后转变为更加务实的 HTML 3.2,在 1997 年完成。 就在同年很快开始了 HTML4 的开发。

随后一年 W3C 成员决定停止 HTML 的演变,并开始开发基于 XML 的替代品 XHTML。 该 工作首先将 HTML4 重新规划为 XML,也就是著名的 XHTML 1.0。 唯一增加的特性就是新的序列化,该工作在 2000 年完成。 XHTML 1.0 之后,在 XHTML 模块化的口号下 W3C 的主要精力转向让其他工作组更容易地扩展 XHTML。 与此同时,W3C 致力于一门新的、与此前的 HTML 和 XHTML 都不兼容的语言:XHTML2。

大概在 1998 年 HTML 停止演化的时候,浏览器厂商开发的部分 HTML API 被标准化和发布在 DOM Level 1(1998) 和 DOM Level 2 Core,以及 DOM Level 2 HTML(2000年开始2003年完成)中。 在 2004 年发布了一些 DOM Level 3 标准,但是 Level 3 草案尚未全部完成工作组就关闭了。 这些工作也最终不了了之。

2003 年 XForms (一项定位于下一代 Web 表单的技术)的发布 重新激起了对 HTML 演化的兴趣,而不是像从前那样寻求新的替代品。 这时人们发现 XML 作为 Web 技术的部署只局限于全新的技术(比如 RSS 和后来的 Atom), 而不是取代已经部署的技术(比如 HTML)。

概念验证显示,在不要求浏览器实现与现存 HTML Web 页面不兼容的渲染引擎的情况下, 也可能扩展 HTML4 的表单来提供 XForms 1.0 引入的很多特性。 这一概念验证是对 HTML 重新燃起的兴趣产生的第一项成果。 在这早期阶段,虽然本草案已经公开可用且已广泛征求建议,该标准只在 Opera Software 版权下发布。

应该重新开启 HTML 演化的想法在 W3C 工作组得到了测试。 Mozilla 和 Opera 共同向 W3C 工作组提交了提议,包括 HTML5 工作背后的一些原则(见下文),以及前述的只涉及表单特性的早期草案。 该提议因为与此前选择的 Web 演化方向冲突而被拒绝, W3C 职员和会员投票支持继续开发基于 XML 的替代品。

此后 Apple,Mozilla 和 Opera 共同声明他们将继续在 WHATWG(一个新的组织)团体下投入工作。 他们为此创建了一个公开的邮件列表,草案也移交到了 WHATWG 网站。随后版权也修改为这三家共同拥有, 同时允许该标准的重用。

WHATWG 基于若干核心原则,具体地:技术需要向后兼容,标准和实现需要相符(即使这意味着更改标准而不是实现), 标准需要足够详细来使得一个实现在不需对其他实现进行逆向工程的情况下,就能可达到完全的互操作性。

其中后一个原则,要求 HTML5 标准的范围应包括先前在 HTML4,XHTML1,和 DOM2 HTML 这三篇独立的文档中标准化的内容。 同时意味着相比于此前的考虑,需要显著地引入更多的细节。

2006 年,W3C 暗示了参与 HTML5 开发的兴趣,并于 2007 年组建了工作组来与 WHATWG 共同开发 HTML5 标准。 Apple,Mozilla,和 Opera 允许 W3C 在 W3C 版权下发布该标准, 只要保留一版 WHATWG 网站的那份较少限制的许可协议。

数年中各方一同工作,然而在 2011 年,这些工作组最终发现他们有着不同的目标: W3C 希望发布一个"完成的" HTML5 版本,而 WHATWG 希望持续地维护一个 HTML Living Standard, 持续地维护该标准而不是锁定在一个带着已知问题的状态, 同时按照需求增加新的特性来发展整个平台。

从此 WHATWG 一直在(与其他组织一同)开发该标准, W3C 则复制 WHATWG 的修复工作到他们所在的文档分支(也有其他的一些改动)。

1.7 设计笔记

This section is non-normative.

必须承认 HTML 的很多方面乍一看毫无意义或者不太一致。

HTML,它的 DOM API,以及很多其他的支持技术是由互不相识的有着不同目的的人,经数十年开发完成。

因此特性的出现有着不同的来源,也未经专门的一致的方式设计。 而且由于 Web 独有的特点,实现的 Bug 常常会变成事实上的惯例,以及现在合法的、标准的行为。 因为编写的内容常常会无意地依赖于这些未能及时修复的实现。

尽管这样,人们还是为坚持某些设计目标而付出努力。在接下来的几个小节中描述了这些努力。

1.7.1 脚本执行的可串行性

This section is non-normative.

为了避免让 Web 作者处理多线程的复杂性,HTML 和 DOM API 的设计使得脚本无法检测同时运行的其他脚本。 甚至在使用 workers 时,设计意图中实现的行为可以被认为是 在所有 浏览环境 中串行地执行所有脚本。

1.7.2 与其他标准的兼容性

This section is non-normative.

本标准和多种多样的其他有相互影响和依赖。很不幸在某些情况下,相互冲突的需求使得本标准违反了其他标准的要求。 当这种情况发生时,每一项冲突都会标记为 "willful violation",而且会说明该冲突的原因。

1.7.3 可扩展性

This section is non-normative.

HTML 有广泛的可扩展性机制,可用来安全地添加语义:

1.8 HTML 和 XML 语法

This section is non-normative.

本标准定义了一个描述文档和应用的抽象语言,以及一些 API 来与使用该语言的资源的内存表示进行交互。

这一内存表示又称为 "DOM HTML",或简称为 "DOM"。

对于传输使用了该抽象语言的资源,有很多不同的具体语法。本标准中定义了其中两种。

第一个这样的具体语法是 HTML 语法。这是对多数作者推荐的格式,它与多数遗留的 Web 浏览器相兼容。 如果一个文档以text/html MIME type进行传输, 然后它将会被 Web 浏览器作为 HTML 文档处理。 本标准定义了最新的 HTML 语法,简单地称为 "HTML"。

第二个具体的语法是 XML。当一篇文档以XML MIME type(比如application/xhtml+xml) 传输时,它将会被 Web 浏览器当做 XML 文档处理,被 XML 处理器解析。 作者需要注意 XML 和 HTML 的处理存在差别;具体地,即使很小的语法错误都将阻止 XML 文档的完整渲染, 然而它们在 HTML 语法中将会被忽略。

给 HTML 用的 XML 语法此前被称为 "XHTML",但本标准不适用该术语 (原因之一是 MathML 和 SVG 的 HTML 语法中未使用该术语)。

DOM,HTML 语法,XML 语法不能用来表示同样的内容。 例如 HTML 语法不能表示命名空间,但 DOM 和 XML 语法却支持。 类似地,HTML 语法可以表示使用 noscript 特性的文档, 但 DOM 和 XML 语法却不能。 包含 "-->" 的注释只能在 DOM 中表示,HTML 和 XML 语法却不行。

1.9 本标准的结构

This section is non-normative.

本标准分为以下主要的部分:

概述
为 HTML 标准提供上下文的非规范性材料。
通用基础设施
合规的类、算法、定义、标准其余部分的通用基础。
HTML 文档的语义,结构,与 API
文档由元素构成,这些元素使用 DOM 组成一棵树。 这部分定义了该 DOM 的特性,介绍了所有元素共同的特性,以及在定义元素时用到的概念。
HTML 元素
每个元素都有一个预定义的含义,本章便解释了这些含义。 也给出了作者使用这些元素的规则,以及用户代理处理这些元素的要求。 这里包含了大量的 HTML 独有的特性,例如视频播放和副标题,表单控件和表单提交, 以及名为 HTML canvas 的 2D 图形 API。
微数据
本标准介绍了为文档增加机器可读注解的机制,这样工具可以从文档中抽取键值对的树。 这部分文档描述了该机制 和用于将 HTML 文档转换为其他格式的一些算法。 这部分还为联系信息、日历事件和许可协议定义了一些示例的微数据词汇。
用户交互
HTML 文档可以提供一些用户与内容交互以及用户修改内容的机制,在本章中给出了这些机制的描述。 比如焦点的工作机制、以及拖放操作。
加载 Web 页面
HTML 文档不是空中楼阁 — 这部分定义了很多影响处理多页面环境的特性,比如 Web 浏览器和 Web 应用的离线缓存。
Web 应用 API
这部分介绍了 HTML 应用脚本的基本特性。
Web workers
这部分定义了 JavaScript 后台线程的 API。
通信 API
这部分描述了 HTML 编写的应用可用来与同一客户端中的,不同域名的其他应用通信的一些机制。 也介绍了一个服务器推送事件流机制,称为 Server Sent Events 或 EventSource, 以及一个为脚本提供的双向全双工套接字协议,称为 Web Sockets。
Web storage
这部分定义了一个基于键值对的客户端存储机制。
HTML 语法
XML 语法
只有表示为序列化的形式并发送给其他人,所有的这些特性才会有意义。 所以这两部分定义了 HTML 和 XML 的语法 ,以及如何使用这些语法来解析内容的规则。
渲染
这部分定义了 Web 浏览器默认的渲染规则。

还有一些附录,列出了 废弃的特性IANA 考虑,以及一些索引。

1.9.1 如何阅读本标准

阅读本标准的方式与其他标准类似。首先应该完整地阅读多次,然后至少倒着读一次, 然后应该从目录中随机选入章节并跟着所有交叉引用读一次。

如下面一致性要求部分所述,本标准描述了各一致性等级的一致性标准。 特别地,有些一致性要求适用于生产者(例如作者和他们创建的文档), 也有一些适用于消费者(例如 Web 浏览器)。 他们的要求是不同的:对生产者的要求声明了什么是允许的,而对消费者的要求声明了软件的行为。

例如,“foo 属性的值必须是一个合法的整数” 是对生产者的要求,因为它规定了允许的取值;相反, “foo 属性的值必须使用 解析整数的规则来解析” 是对消费者的要求,因为它描述了如何处理内容。

对生产者的要求不会对消费者产生任何影响。

继续上述例子,“属性值必须是合法的整数”刻意地没有暗示对消费者的要求。 事实上消费者可能被要求把该属性当做透明的字符串,完全不关心它的值是否满足要求。 也可能被要求以指定的规则来解析它的值(就像上述例子中那样),这些规则就定义了如何处理不合法的值(在本例子中就是非数字的值)。

1.9.2 排版惯例

这是定义、要求,或者解释。

这是注意事项。

这是翻译者的注释。

这是例子。

这是未解决的问题。

这是警告

[Exposed=Window]
interface Example {
  // 这是一个 IDL 定义(接口描述语言)
};
variable = object . method( [ optionalArgument ] )

这是给作者看的,描述了接口的使用。

/* 这是一个 CSS 片段 */

术语的定义标记为 这样。 该术语的使用标记为 这样这样

元素、属性或 API 的定义标记为这样。 该元素、属性或 API 的引用标记为 这样

其他代码片段标记为这样

变量标记为这样

在算法中,同步部分的步骤标记为 ⌛。

有些情况下,要求以列表的形式给出,列表项包括条件和对应的要求。 在该情况下,适用于某项条件的要求紧跟着条件出现,这些要求的条件可能有很多个。例如:

这是一个条件
这是另一个条件
这是适用于上述条件的要求
这是第三个条件
这是适用于第三个条件的要求

1.10 HTML 的简单介绍

This section is non-normative.

一个基本的 HTML 文档看起来像这样:

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Sample page</title>
 </head>
 <body>
  <h1>Sample page</h1>
  <p>This is a <a href="demo.html">simple</a> sample.</p>
  <!-- this is a comment -->
 </body>
</html>

HTML 文档由树状的元素和文本组成。源码中每个元素由 一个 开始标签(例如 "<body>") 和一个 结束标签(例如 "</body>")表示。 (某些开始标签和结束标签在某些情况下可以 省略。)

标签的嵌套必须使所有标签都完全在其他标签内部,不应出现重叠:

<p>This is <em>very <strong>wrong</em>!</strong></p>
<p>This <em>is <strong>correct</strong>.</em></p>

本标准定义了 HTML 中使用的一些元素,以及它们的嵌套规则。

元素可以有属性来控制元素的行为。在下面的例子中是一个 超链接, 由一个a元素和它的 href 属性组成:

<a href="demo.html">simple</a>

属性 应放置在开始标签中,由 属性名属性值构成, 以 "=" 分隔。 如果不包含空格" ' ` = <>, 属性值可以保持 没有引号 ; 否则必须使用单引号或双引号。 如果属性值是空字符串,属性值以及 "=" 可以一起省略。

<!-- empty attributes -->
<input name=address disabled>
<input name=address disabled="">

<!-- attributes with a value -->
<input name=address maxlength=200>
<input name=address maxlength='200'>
<input name=address maxlength="200">

HTML 用户代理(比如 Web 浏览器)解析这些标记,把它转化为 DOM(Document Object Model)树。 DOM 树是文档在内存中的表示。

DOM 数包含若干种节点,具体地:DocumentType 节点、 Element节点、Text 节点、Comment 节点, 以及有时会出现的 ProcessingInstruction 节点。

本章顶部的代码片段将会转化为下列 DOM 树:

树中的document 元素html 元素, 在 HTML 文档的这一位置总是应该有这样一个元素。它包含两个元素, headbody,以及它们之间的一个 Text 节点。

DOM 树中的 Text 节点比你预想的要多,因为源码包含一些空格(表示为"␣")和换行("⏎"), 这些都会变成 DOM 中的 Text 节点。然而因为历史原因,并非所有这些源码中的空格和换行都出现在 DOM 中。 具体地,所有head开始标签前的空白都会被悄悄地丢掉,所有body结束标签后的空白都会出现在body的尾部。

head 元素包含一个 title 元素,其中包含一个 内容为 "Sample page" 的 Text 节点。类似地,body 元素包含一个 h1 元素,一个p 元素,和一个注释。


页面中的脚本可以操作该 DOM 树。脚本(比如 JavaScript)是可以使用 script标签或 事件处理内容属性内嵌的小程序。 比如下面是一个表单,其中的脚本设置了表单中output元素的内容并输出 "Hello World":

<form name="main">
 Result: <output name="result"></output>
 <script>
  document.forms.main.elements.result.value = 'Hello World';
 </script>
</form>

DOM 树中的每个元素表示为一个对象,这些对象提供 API 以供操作。 例如,一个链接(比如上述树中的a元素)的 "href"属性可以通过多种方式改变:

var a = document.links[0]; // obtain the first link in the document
a.href = 'sample.html'; // change the destination URL of the link
a.protocol = 'https'; // change just the scheme part of the URL
a.setAttribute('href', 'https://example.com/'); // change the content attribute directly

由于 DOM 树是实现者(尤其是像 Web 浏览器这样的交互式实现)用来处理和显示 HTML 文档的, 本标准更多地是按照 DOM 树来介绍的,而不是按照上面描述的标记代码。


HTML 文档表示了交互式内容的一种媒体无关的描述。HTML 文档可能会渲染在屏幕、语音合成器、或者盲文点触设备。 为了精确地控制渲染行为,作者可以使用一个像 CSS 这样的样式语言。

在下列例子中,使用 CSS 将页面设置为蓝底白字。

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>Sample styled page</title>
  <style>
   body { background: navy; color: yellow; }
  </style>
 </head>
 <body>
  <h1>Sample styled page</h1>
  <p>This page is just a demo.</p>
 </body>
</html>

关于更多 HTML 的使用细节,鼓励作者参考教程和指南。 本标准中的一些示例可能也有用,但新手作者需要注意本标准必须非常详细地定义该语言, 以至于一开始可能很难理解。

1.10.1 使用 HTML 编写安全应用

This section is non-normative.

当使用 HTML 创建交互式网站时,需要注意避免引入漏洞,使得攻击者通过这些漏洞危害网站本身或网站用户信息的完整性。

对这一问题的全面研究超出了本文档的范围,我们强烈建议网站作者去更详细地研究这一问题。 即便如此,本节尝试对 HTML 应用程序开发中的一些常见陷阱作简单介绍。

Web 的安全模型基于“域”的概念,因此 Web 上许多潜在的攻击涉及跨域操作。[ORIGIN]

不验证用户输入
跨站脚本(XSS)
SQL 注入

当接受不可信输入时(例如文本评论这样的用户生成内容,URL 参数中的值,来自第三方网站的消息等), 必须在使用前验证数据,并在显示时正确转义。 否则就会允许恶意的用户执行各种攻击, 这些攻击可能是轻微的,例如提供诸如负的年龄这样的假的用户信息; 也可能是严重的,例如在每次用户查看包含该信息的页面时执行脚本; 也可能是传播性的攻击导致灾难性后果,比如删除服务器中的所有数据。

当编写过滤器验证用户输入时,过滤器应当是基于白名单的,允许已知的安全构造并禁止所有其他输入。 基于黑名单的过滤器(禁止已知的错误输入并允许其他所有输入)是不安全的, 因为并不是所有错误输入都是已知的(因为它可能会在未来发明)。

例如,一个页面查看它的 URL 查询字符串来决定显示的内容, 然后网站将用户重定向到显示该消息的页面。比如:

<ul>
 <li><a href="message.cgi?say=Hello">Say Hello</a>
 <li><a href="message.cgi?say=Welcome">Say Welcome</a>
 <li><a href="message.cgi?say=Kittens">Say Kittens</a>
</ul>

如果这一消息没有转义就显示给用户,恶意的攻击者可能会构造一个包含脚本元素的 URL:

https://example.com/message.cgi?say=%3Cscript%3Ealert%28%27Oh%20no%21%27%29%3C/script%3E

如果攻击者随后说服受害者访问此页面,攻击者选择的脚本将在页面上运行。 这样的脚本可以执行任意的恶意操作,只要是站点提供的。 例如站点是电子商务商店,这样的脚本可以导致在用户不知情的情况下进行任意的购买。

这称为跨站脚本攻击。

有很多构造可以欺骗网站执行代码。以下是网站作者在编写白名单过滤器时应考虑的事项:

跨站请求伪造 (CSRF)

如果网站允许用户提交的表单产生用户相关的影响,例如使用名字在论坛上发布消息, 进行购买或申请护照,那么很有必要核实该请求确实是用户有意发起的, 而不是由另一个站点欺骗用户不知情地发起请求。

该问题的存在是因为 HTML 表单可能被提交到其他域名。

站点可以通过为表单填充用户相关的隐藏标记或检查所有请求的`Origin`头字段, 来防止这样的攻击。

Clickjacking

如果页面为用户提供的界面中包含用户可能不希望执行的操作时, 该页面应当经过特殊设计来避免用户被欺骗以激活该界面的可能性。

一种用户被欺骗的可能是,如果恶意站点将受害站点放在一个小的 iframe 中然后让用户去点击, 例如让用户玩一个反应类游戏。一旦用户开始玩这个游戏,恶意站点可以在用户正要点击时快速地将这个 iframe 放到鼠标光标下。 以此来欺骗用户点击受害站点的界面。

为了避免这种情况,鼓励不期望在 iframe 下使用的站点只有检测(例如通过比较window对象和top属性的值) 到它们不在 iframe 下时才激活它们的界面。

1.10.2 使用脚本 API 时常见的陷阱

This section is non-normative.

HTML 中的脚本有着"运行到完成"的语义,这意味着浏览器通常在执行任何其他操作 (诸如触发进一步的事件或继续解析文档)之前会不中断地执行脚本。

另一方面,HTML 文件的解析是逐步发生的,这意味着解析器可以在任何地方暂停来让脚本运行。 这通常是一件好事,但确实意味着作者需要小心地避免在事件可能已经触发之后才绑定事件处理程序。

有两项技术能够可靠地完成这件事情:使用 事件处理程序内容属性, 或者在同一脚本中创建元素和添加事件处理程序。后一种更为安全,因为如前所述, 脚本会在进一步的事件发生前一直运行到完成。

一个可以表示此种情形的例子是img元素和load事件。 该事件在元素解析完成时就会触发,特别是当图片已经被缓存之后(这很常见)。

这里,作者在img标签上使用 onload 事件处理程序 来捕捉 load 事件:

<img src="games.png" alt="Games" onload="gamesLogoHasLoaded(event)">

如果使用脚本添加元素,那么只要在同一脚本中添加事件处理函数,该事件就不会被错过:

<script>
 var img = new Image();
 img.src = 'games.png';
 img.alt = 'Games';
 img.onload = gamesLogoHasLoaded;
 // img.addEventListener('load', gamesLogoHasLoaded, false); // would work also
</script>

然而如果作者首先创建了img元素,然后在另一个单独的脚本中添加了事件监听器, 那么有可能load事件会在两者之间触发,导致它被错过:

<!-- Do not use this style, it has a race condition! -->
 <img id="games" src="games.png" alt="Games">
 <!-- the 'load' event might fire here while the parser is taking a
      break, in which case you will not see it! -->
 <script>
  var img = document.getElementById('games');
  img.onload = gamesLogoHasLoaded; // might never fire!
 </script>

1.10.3 编写 HTML 时如何发现错误:验证器和一致性检查器

This section is non-normative.

鼓励作者使用一致性检查器(又称验证器)来发现常见的错误。 WHATWG 维护着这种工具的一个列表:https://validator.whatwg.org/

1.11 对页面作者的一致性要求

This section is non-normative.

与以前版本的 HTML 规范不同,此规范不仅定义了对有效文档的处理, 也详细定义了对无效文档的处理过程。

然而,即使无效内容的处理在大多数情况下是良好定义的,文档的一致性仍然很重要: 在实践中,互操作性(所有实现以可靠和相同或等同的方式处理特定内容的情况)并不是文档一致性要求的唯一目标。 本节详细地介绍了合法文档和错误文档仍然有所区别的一些常见原因。

1.11.1 表示性的标记

This section is non-normative.

先前 HTML 版本的大多数表示性特性不再被允许。一般来说,表示性的标记有这样一些问题:

表示性元素的使用导致较差的可访问性

尽管使用显示性的标记也可以为使用辅助技术(Assistive Technologies,AT)的用户 提供可接受的体验(比如使用 ARIA),但这样做显然比使用适当的语义标记更加困难。 此外,即使使用这样的技术也不能帮助那些既没有 AT 又没有图形的用户(比如使用文本模式浏览器的用户)访问页面。

另一方面,使用媒体无关的标记为编写更多用户(比如文本浏览器的用户)可用的文档提供了简单的方式。

更高的维护成本

使用样式无关的标记编写的站点,显然更容易维护。比如,对于到处都在使用 <font color=""> 的站点,更改颜色需要更改整个站点, 然而对基于 CSS 的站点做类似的改动,只需更改一个文件。

更大的文档大小

表示性标记往往会增加冗余,因此导致更大的文档大小。

出于这些原因,在本版本的 HTML 中移除了表示性的标记。 这一改动并不突然,HTML4 在很多年前就已经不推荐使用表示性标记, 并提供了一种模式(HTML4 Transitional) 来帮助作者从表示性标记进行迁移; 后来 XHTML 1.1 更进一步地一起废弃了那些特性。

HTML 中唯一保留下来的表示性标记特性是 style 属性和 style 元素。 生产环境中使用 style 属性也在某种程度上不再推荐, 但在创建原型(这些规则之后可以直接移动到单独的样式表中) 以及在特殊情况下(当单独的样式表不方便时)提供特定样式很有用。 类似地,style 元素在引入外部样式内容或者提供页面特定样式时很有用。 但一般来说,当样式适用于多个页面时,外部样式表可能更加方便。

值得注意的是有些先前的表示性元素在本标准中已经被重新定义为媒体无关的: b, i, hr, s, small, and u.

1.11.2 语法错误

This section is non-normative.

限制 HTML 的语法是为了避免各种各样的问题。

不直观的错误处理行为

某些不合法的语法构造在解析后会导致很不直观的 DOM 树。

例如,以下标记片段会导致 DOM 树中的 hr 元素 在相应的 table 元素之前

<table><hr>...
可选错误恢复的错误

为了允许在受控环境中使用的用户代理不必实现更奇怪和复杂的错误处理规则, 允许用户代理在遇到解析错误时失败。

错误处理行为与流式用户代理不兼容的的错误

一些错误处理行为(比如上面提到的<table><hr>...) 与流式用户代理(不存储状态且通过一次遍历来处理 HTML 文件的用户代理)不兼容。 为了避免与这样的用户代理的互操作性问题,任何导致该行为的语法都是无效的。

会导致信息集强制的错误

当一个基于 XML 的用户代理连接到一个 HTML 解析器时, 某些 XML 强制的不变式(比如元素或属性名不可包含多个冒号)可能被 HTML 文件违反。 处理这种情况可能要求解析器将 HTML DOM 信息强加给 XML 兼容的信息集。 要求这一处理的多数语法构造都是不合法的。 (包含两个连续的间隔符的注释,或以一个间隔符结尾的注释是特例,这在 HTML 语法中是允许的)。

这一规则意味着基于 XML 的用户代理只需连接一个 HTML 解析器(Parser)即可拥有理解 HTML 的能力。所以 HTML 与 XML 只是语法有所不同, 表达语义的能力应当是等价的。

会导致性能下降的错误

某些语法构造可能导致很差的性能。为了阻止这些构造的使用,通常把它们归为不合规范的。

例如,下列标记会导致很差的性能,因为所有未闭合的 i 元素必须在每个段落中重新构造, 导致每个段落中的元素累加地增多:

<p><i>She dreamt.
<p><i>She dreamt that she ate breakfast.
<p><i>Then lunch.
<p><i>And finally dinner.

该片段的结果 DOM 将会是:

涉及到脆弱的语法构造的错误

由于历史原因有一些语法构造相对脆弱。为了避免用户意外地掉到坑里,它们也被归为不合规范的。

例如,即使省略了关闭分号,对属性中命名的字符引用的解析也会发生。 可以安全地引入一个&以及紧随其后的不构成特殊命名的字符引用, 但如果这些字母改成构成命名的字符引用,它们将会被解释为那个特殊字符。

在这个代码片段中,属性值是“?bill&ted”:

<a href="?bill&ted">Bill and Ted</a>

在下面的代码片段中,属性值实际上会变成“?art©”, 而不是 期望的 “?art&copy”, 因为即使没有最后的分号“&copy”也会一样地被处理为 “&copy;”最终被解释为“©”:

<a href="?art&copy">Art and Copy</a>

为了避免这一问题,要求所有命名的字符引用以分号结束, 所有使用命名字符引用但未添加分号的都被标记为错误。

因此正确地表达上述情况的方式如下:

<a href="?bill&ted">Bill and Ted</a> <!-- &ted is ok, since it's not a named character reference -->
<a href="?art&amp;copy">Art and Copy</a> <!-- the & has to be escaped, since &copy is a named character reference -->
涉及旧用户代理中的已知互操作性问题的错误

某些语法构造在旧的用户代理中会造成一些已知的细微或严重的问题。 因此他们被标记为不合规范的来帮助作者避免这些问题。

例如 U+0060 重音符(`)不允许出现在没有引号的属性中。 因为在某些旧用户代理中,它有时会被当做一个引号。

另一个例子是必须使用 DOCTYPE 来触发 非怪异模式, 因为旧用户代理在 怪异模式 下的行为通常都没有文档。

可能引发对作者的安全攻击的错误

某些限制纯粹是为了避免已知的安全问题。

例如,对使用 UTF-7 的限制纯粹是为了避免作者成为使用 UTF-7 的已知跨站脚本攻击的的目标。[UTF7]

作者的意图不清楚的情况

作者意图不清楚的标记通常被划为不规范的。 尽早修复这些错误会使得后续维护更为容易。

例如,作者是要将以下内容作为 h1 标题还是 h2 标题的意图并不明确:

<h1>Contact details</h2>
可能是拼写错误的情况

当用户发生了拼写错误,提早捕获该错误是有帮助的,因为这可以节省作者很多调试时间。 因此本标准通常认为使用与本标准中定义的名字不匹配的元素名、属性名等是错误的。

例如,如果作者键入<capton> 而不是 <caption>,这将被标记为错误,作者可以立即更正错字。

将来可能会干扰新语法的错误

为了允许将来扩展语言语法,某些本来无害的特性也是不允许的。

例如,在结束标签中的“属性”目前被忽略,但它们是非法的。 以防未来使用该语法特性的语言变更与已部署(但是合法的!)内容产生冲突。

一些作者发现,在实践中总是用引号包含所有的属性并且总是包含所有的可选标签很有帮助, 相比于利用 HTML 语法的灵活性而带来的一点简洁,更偏好这一做法带来的一致性。 为了协助这样的作者,一致性检查器可以提供执行这一惯例的运行模式。

1.11.3 内容模型和属性值的限制

This section is non-normative.

除了语言的语法,本标准还对如何指定元素和属性做出了限制。 这些限制是出于类似的原因:

语义可疑的内容

为了避免误用定义了含义的元素, 定义内容模型时,限制了可疑的元素嵌套方式。

例如,本标准不允许 section 元素嵌套在 kbd 元素中,因为作者不太可能表示 应该键入整个 section

表达的语义存在冲突

类似地,为了让作者对元素使用中的错误引起注意, 表达出的语义存在明显的矛盾也被认为是一致性错误。

例如下面的片段中的语义是毫无意义的: 分隔符不能同时是单元格,单选按钮也不能是进度条。

<hr role="cell">
<input type=radio role=progressbar>

另一个例子是对ul元素的内容模型的限制, 该限制只允许 li 子元素。根据定义列表只可包含一些列表项。 所以如果 ul 元素包含一些除了 li 之外的元素, 它的含义就不清楚了。

默认样式可能会导致困惑的情况

某些元素有一些默认样式和行为,它们的某些组合可能会令人困惑。 如果存在没有这一问题的等效替代,就不允许这样令人困惑的组合。

例如,div 元素会被渲染为 block boxesspan 元素则为 inline boxes。将 block box 放到 inline box 中就会导致不必要的困惑;因为只嵌套 div 元素,或只嵌套 span 元素,或在div元素中嵌套 span 元素都可以与在span元素中嵌套div元素 达到同样的目的。但只有后者涉及到在 inline box 中嵌套 block box, 所以后者的组合方式是不允许的。

另一个可能的例子是 交互内容 不可嵌套。例如: button 元素不可包含 textarea 元素。 这是因为这样嵌套交互元素可能对用户造成困惑。可以并排放置这些元素。

对本标准可能的误解

有时,某些禁止是因为允许它将可能会让作者困惑。

例如,设置 disabled 属性为 "false" 是不允许的,因为表面上看起来它的含义是元素可用, 但实际上含义是元素被 禁用 (实现中起作用的是该属性是否存在,而非它的值)。

纯粹为了简化语言而强加的限制

一些一致性错误简化了作者需要学习的语言。

例如,area 元素的 shape 属性,在实践中虽然同时接受 circcircle 取值并作为同义词,但禁止 circ 值的使用, 以此来简化教程和其他学习材料。同时允许它们并没有好处, 但它们可能在学习语言时造成额外的困惑。

解析器的一些怪异行为

某些元素的解析有点奇怪(通常是由于历史原因), 它们的内容模型限制旨在避免作者碰到这些问题。

例如,phrasing content 中不允许 form 元素,因为当解析 HTML 时, form 元素的开始标签将会产生一个 p 元素的关闭标签。因此下面的标记会产生两个 段落(而不是一个):

<p>Welcome. <form><label>Name:</label> <input></form>

与下面代码的解析结果完全一样:

<p>Welcome. </p><form><label>Name:</label> <input></form>
可能导致难以调试的脚本错误的情况

有些错误旨在避免难以调试的脚本问题。

比如,这就是为什么有两个等值的 id 属性是不合法的。 重复的 ID 导致选择到错误的元素,有时会产生难以确定原因的灾难性后果。

会浪费编写时间的错误

某些构造被禁止是因为历史上它们曾浪费大量的编写时间。 鼓励作者避免使用这些构造,将来可以节省很多时间。

例如,script 元素的 src 属性会导致元素的内容被忽略。 然而这并不明显(尤其是元素内容是可执行脚本时)— 这会导致作者花费大量时间尝试调试内联脚本,却没意识到它并未执行。 为了减少这一问题,在本标准中src 属性出现时,script元素中不允许存在可执行脚本。 这意味着作者在验证他们的文档时,不太可能在这样的错误上浪费时间。

影响作者在 HTML 和 XML 语法间迁移的部分

有些作者喜欢编写用 XML 和 HTML 解释可以得到类似结果的文件。 由于种种微妙的复杂性(尤其是涉及脚本、样式、或其他任何自动的序列化), 一般并不鼓励这一做法,尽管如此,本标准也有一些限制意在在某种程度上减轻困难。 这让作者在 HTML 和 XML 语法之间迁移时,可以更容易地将其用于过渡步骤。

例如,围绕 langxml:lang 属性有一些复杂的规则, 就是为了让 HTML 和 XML 同步。

另一个例子可能是在 HTML 序列化中对 xmlns 属性值的限制,意在确保不管是 HTML 还是 XML 解析, 合法的文档中元素总在同一命名空间。

为将来扩充而保留的部分

对语法的某些限制是为了允许语言的未来版本中添加新的语法, 类似地,对元素和属性取值的内容模型的一些限制是为了允许将来对 HTML 词库进行扩充。

例如,限制 target 属性的值, 以 U+005F 下划线(_)起始的只能是特定的预定义值。这允许了在将来引入新的预定义值, 同时不会与作者定义的值产生冲突。

对其他标准的误用

某些限制意在支持其他标准作出的限制。

例如,使用媒体查询列表的属性只能使用 合法的 媒体查询列表,强调了遵循那一标准的一致性规则的重要性。

1.12 推荐阅读

This section is non-normative.

本标准的读者可能对以下文档感兴趣。

Character Model for the World Wide Web 1.0: Fundamentals [CHARMOD]

这个架构风格标准定义了 World Wide Web 中可互操作的文本操作。为其他标准的作者、软件开发者,以及内容开发者提供了通用的参考。 该标准构建在 Universal Character Set 之上,同时定义在 Unicode Standard 和 ISO/IEC 10646。 涉及的话题包括:字符、编码、字符串、引用处理模型、字符编码的选择和识别、字符转义,以及字符串索引。

Unicode 安全考虑 [UTR36]

由于 Unicode 包含大量的字符,引入了世界上不同的书写系统, 错误的使用会将程序和系统暴露在可能的安全攻击之下。随着越来越多的产品被国际化该问题尤为重要。 该标准描述了程序员、系统分析师、标准开发者,以及用户应当考虑的安全事项,为减少风险提供了明确的建议。

Web Content Accessibility Guidelines (WCAG) 2.0 [WCAG]

Web Content Accessibility Guidelines (WCAG) 2.0 对于提高 Web 内容的可访问性给出了广泛的建议。 遵循这些指导可以使更多的残障人士(包括失明和弱视、失聪和听觉损耗、学习和认知障碍、行动不便、语言障碍、光过敏等)可访问您的内容。 遵循这些指导也通常会使您的 Web 内容对普通用户更加可用。

Authoring Tool Accessibility Guidelines (ATAG) 2.0 [ATAG]

该标准为设计 Web 内容写作工具提供了指导意见,使得残障人士也可使用这些工具。 遵从这些指导的写作工具将会通过为残障作者提供可访问的用户界面以提升可访问性,以及为所有作者提供、支持和提升产出 Web 内容的可访问性。

User Agent Accessibility Guidelines (UAAG) 2.0 [UAAG]

该文档为设计降低残障人士 Web 访问门槛的用户代理提供了指导意见。 用户代理包括浏览器和其他获取和渲染 Web 内容的软件。 遵循这些指导的用户代理通过它自己的用户界面以及其他内部工具 (包括与其他技术通信的能力,尤其是辅助性技术)提升可访问性。 此外,除残障人士之外的所有用户都会发现遵循该标准用户代理更加可用。

2 公共基础设施

该标准依赖于 WHATWG Infra 标准。 [INFRA]

2.1 术语

该标准所说的属性,指的是 HTML,XML 和 IDL 属性,通常在同一个上下文中。当未具体提及所指时,HTML 和 XML 属性指的是 content attributes,而 IDL attributes指的是在 IDL 接口中定义的属性。同样,“属性”这个词也同时指 Javascript 对象属性和 CSS 属性。在可能产生混淆时, 该标准使用 object propertiesCSS properties 来区别。

一般而言,当该标准申明一个特性可以在 HTML 语法XML 语法 中应用,则在另一个中也可用。 当一个特性仅在两个语言之一中应用时,该标准将显式申明它不能在另一个语言中使用, 如:“可在 HTML 中使用,…… (该语法不可用于 XML)”。

该标准使用术语 文档指任何 HTML,从短小精悍的文档到长篇累牍的论文, 亦或是多媒体报告、完整的交互式应用程序。该术语同时指 Document 对象和他们的后裔 DOM 树。至于序列化的字节流, 则根据上下文使用 HTML 语法XML 语法 来表示。

在 DOM 结构的上下文中,使用的术语 HTML 文档XML 文档 定义在 DOM 标准中, 并且特指 Document 对象所处的两种不同模式。 [DOM] (这样的使用都会超链接到它们的定义)

在字节流的上下文中,术语 HTML 文档 指标记为 text/html 的资源, 术语 XML 文档 指标记为 XML MIME type 的资源。


简单起见,像 shown, displayed, 以及 visible 这样的术语可能会用来指明文档渲染给用户的方式, 这些术语并不是指应用于视觉媒介;必须考虑将它们以等价的方式应用于其他的媒介。

某个元素是visible的并不仅仅指该元素在视觉上可见,比如屏幕阅读器也应将该元素阅读给用户。

2.1.1 Parallelism

To run steps in parallel means those steps are to be run, one after another, at the same time as other logic in the standard (e.g., at the same time as the event loop). This standard does not define the precise mechanism by which this is achieved, be it time-sharing cooperative multitasking, fibers, threads, processes, using different hyperthreads, cores, CPUs, machines, etc. By contrast, an operation that is to run immediately must interrupt the currently running task, run itself, and then resume the previously running task.

For guidance on writing specifications that leverage parallelism, see Dealing with the event loop from other specifications.

To avoid race conditions between different in parallel algorithms that operate on the same data, a parallel queue can be used.

A parallel queue represents a queue of algorithm steps that must be run in series.

A parallel queue has an algorithm queue (a queue), initially empty.

To enqueue steps to a parallel queue, enqueue the algorithm steps to the parallel queue's algorithm queue.

To start a new parallel queue, run the following steps:

  1. Let parallelQueue be a new parallel queue.

  2. Run the following steps in parallel:

    1. While true:

      1. Let steps be the result of dequeueing from parallelQueue's algorithm queue.

      2. If steps is not nothing, then run steps.

      3. Assert: running steps did not throw an exception, as steps running in parallel are not allowed to throw.

      Implementations are not expected to implement this as a continuously running loop. Algorithms in standards are to be easy to understand and are not necessarily great for battery life or performance.

  3. Return parallelQueue.

Steps running in parallel can themselves run other steps in in parallel. E.g., inside a parallel queue it can be useful to run a series of steps in parallel with the queue.

Imagine a standard defined nameList (a list), along with a method to add a name to nameList, unless nameList already contains name, in which case it rejects.

The following solution suffers from race conditions:

  1. Let p be a new promise.

  2. Run the following steps in parallel:

    1. If nameList contains name, reject p with a TypeError and abort these steps.

    2. Do some potentially lengthy work.

    3. Append name to nameList.

    4. Resolve p with undefined.

  3. Return p.

Two invocations of the above could run simultaneously, meaning name isn't in nameList during step 2.1, but it might be added before step 2.3 runs, meaning name ends up in nameList twice.

Parallel queues solve this. The standard would let nameListQueue be the result of starting a new parallel queue, then:

  1. Let p be a new promise.

  2. Enqueue the following steps to nameListQueue:

    1. If nameList contains name, reject p with a TypeError and abort these steps.

    2. Do some potentially lengthy work.

    3. Append name to nameList.

    4. Resolve p with undefined.

  3. Return p.

The steps would now queue and the race is avoided.

2.1.2 资源

本标准中术语 支持 是指用户代理是否实现了对外部资源的语义的解码能力。 支持 某种格式或类型是指这一实现可以处理该格式或类型的外部资源,且处理过程不会忽略关键方面。 是否 支持 某种特定资源取决于该资源类型有哪些在用的特性。

例如,如果可以解码和渲染 PNG 图片的像素数据,就可以认为支持 PNG 图片格式。 即使这一实现不知道该图片还包含了动画数据。

如果不支持使用的压缩格式,即使实现可以从文件的元数据确定电影的尺寸,MPEG-4 视频文件也不会被视为支持的格式。

有些标准中(特别是 HTTP 标准)中称为 表示(representation) 的在本标准中称为 资源(resource)[HTTP]

资源的 关键子资源 是那些需要被正确处理的资源。 哪些资源被认为是关键的,由定义该资源格式的标准来定义。

2.1.3 XML 兼容性

为了方便从 HTML 迁移到 XML,遵循本标准的用户代理会把 HTML 中的元素放在 http://www.w3.org/1999/xhtml 命名空间, 至少是为了 DOM 和 CSS 的目的。 本标准中使用的术语 "HTML 元素",是指所有在那个命名空间中的元素, 包括 XML 文档中的。

除非另有声明,所有本标准中定义和提到的元素均位于 HTML ("http://www.w3.org/1999/xhtml"), 本标准中所有定义和提到的属性(Attribute)没有命名空间。

术语 元素类型 用于指代给定命名空间和局部名的那些元素。 例如,button 元素的元素类型为 button,意味着它们的局部名为 "button" 且(如上述定义地)命名空间为 HTML

如果属性名匹配 XML 中定义的 Name 生成式且不包含 U+003A COLON 字符(:),那么它就是 XML 兼容的 [XML]

2.1.4 DOM 树

当声明 忽略 某些元素或属性,或当作其他值处理,或当作其他东西处理时, 都是指节点在 DOM 中之后的处理。在这些情形下用户代理禁止改动 DOM。

只有内容属性的新值和原值不同时,才说内容属性的值发生了 改变; 将内容属性设置到它已有的值不会让它发生改变。

术语 用于属性值、文本 节点、或字符串时, 表示文本的长度是零(即不包含控制字符 或 U+0020 SPACE)。

插入节点 A 到节点 B 是指以 A 作为参数调用 插入步骤, 然后 A 新的父节点就是 B。类似地,从节点 B 移除节点 A 是指以 A 作为 removedNode 参数,以 B 作为 oldParent 参数调用 移除步骤

插入节点到文档 是指把它作为参数调用 插入步骤, 然后它就 在文档树中 了。类似地, 从文档中移除节点 是指把它作为参数调用 移除步骤, 然后它就不 在文档树中 了。

把节点作为参数调用 插入步骤 后, 节点就 变成已连接的。 类似地,把它作为参数调用 移除步骤 后, 节点就 变成了分离的

如果节点是 已连接的 且它的 包含 Shadow 的根浏览环境,那么它是 连接到浏览环境的。 把节点作为参数调用 插入步骤 后, 它就 连接到了浏览环境。 把节点作为参数调用移除步骤, 或者它的 包含 Shadow 的根 不再拥有 浏览环境 后, 它就 与浏览环境分离了

2.1.5 脚本

有时会用构造 "一个 Foo 对象" (其中 Foo 其实是一个接口), 来表示 "一个实现了 Foo 接口的对象"。

获取 IDL 属性的值称为 获取(例如在作者的脚本中), 将新的值赋值给 IDL 属性则称为 设置

如果 DOM 对象是 活的,该对象上的属性和方法 必须 在真正的底层数据(而不是数据快照)上进行操作。

2.1.6 插件

术语 插件 是指一些用户代理定义的内容处理程序,用户代理用它们 参与 Document 对象的渲染,但不会作为 Document子浏览环境,也不会给 Document 的 DOM 引入任何 Node 对象。

通常,这样的内容处理程序由第三方提供,尽管用户代理也可以将内置的内容处理程序指定为插件。

用户代理不得将 text/plainapplication/octet-stream 类型视为注册有 插件

插件的一个例子是当用户导航到PDF文件时在 浏览环境 中实例化的PDF查看器。 无论执行PDF查看器组件的一方是否与实现用户代理本身的方相同,这将被视为插件。 但是根据定义,与用户代理(而不是使用相同的接口)分开启动的PDF查看器应用程序不是插件。

该规范没有定义与插件交互的机制,因为插件预期就是用户代理和平台特定的。 UA 可以选择支持某种插件机制,比如 Netscape Plugin API; 也可以选择对某些类型使用远程内容转换器或提供内置支持。 实际上,本标准根本没有要求用户代理支持插件。[NPAPI]

安全 插件应该遵循 sandbox 属性的语义。

例如,在沙盒 iframe 中初始化的 安全插件应该阻止其中的内容创建弹出窗口。

在与 插件 的外部内容交互时,浏览器应该格外小心。 当第三方软件以与用户代理本身相同的权限运行时,第三方软件中的漏洞变得与用户代理中的漏洞同样危险。

因为不同的用户有不同的 插件,这提供了唯一识别用户的指纹向量, 推荐用户代理对每个用户都支持同样的 plugins

2.1.7 字符编码

字符编码 或着没有歧义时说的 编码,是一种字节流与 Unicode 字符串的转换, 定义在 Encoding 中。编码 包括一个 编码名称 和一个或更多的 编码标签,编码的 名称标签 定义在 Encoding 标准中。 [ENCODING]

2.1.8 符合性类别

本标准描述了 用户代理(实现者相关)和 文档 (作者和编写工具的实现者相关) 的符合性标准。

符合规范的文档 是符合所有符合性要求的文档。 为了提高可读性,有些符合性要求是对作者提出的;这些是对文档的隐性要求: 按照定义所有文档都有对应的作者。(有些情况下,作者本身可能是一个用户代理 — 这些用户代理受其他规则的约束,见下文。)

例如,如果一项要求声明 "作者 禁止使用 foobar 元素",意味着文档不允许包含名为 foobar 的元素。

文档的符合性要求与实现的符合性要求没有隐含的关系。 用户代理不能随意处理不合规范的文档;不论输入的文档是否合规,本标准中描述的处理模型都适用。

按照不同的符合性要求,用户代理分为(有重合的)几类。

Web 浏览器和其他交互式用户代理

支持 XML 语法 的 Web 浏览器必须按照本标准的描述 处理 XML 文档中 HTML 命名空间 的元素和属性, 以便用户与之交互,除非那些元素的语义已经被其他标准覆盖。

在 XML 文档中查找 script 元素时,符合规范的 Web 浏览器会执行该元素包含的脚本。然而,如果该元素处于 XSLT 变换中(假设用户代理也支持 XSLT), 那么处理器会将 script 元素作为组成这一变换的不透明元素处理。

支持 HTML 语法 的 Web 浏览器必须按照本标准的描述 处理标记为 HTML MIME 类型 的文档,以便用户与它们交互。

支持脚本的用户代理也必须一致地实现本标准中的 IDL 片段,IDL 片段定义在 Web IDL 标准中。 [WEBIDL]

除非明确声明,覆盖 HTML 元素语义的标准不覆盖对(表示这些元素的) DOM 对象的要求。 例如,上面例子中的 script 元素仍然实现 HTMLScriptElement 接口。

表示性的非交互式用户代理

处理 HTML 和 XML 文档并纯粹地渲染它们的非交互式版本的用户代理必须遵循与 Web 浏览器同样的符合性规范,除了它们可以免除用户交互的要求。

非交互式用户代理的典型例子就是打印机(静态 UA)和投影仪(动态 UA)。 多数静态的非交互式用户代理 不支持脚本

非交互式的动态 UA 仍然会执行脚本,以便动态提交表单。 但是因为没有获得焦点的概念,这些 UA 可能不需要实现焦点相关的 DOM API。

支持建议默认渲染的可视化用户代理

无论是交互式还是非交互式用户代理,都可以被指定(比如通过作为用户选项)本标准定义的建议默认渲染。

这并非强制要求,特别是即使用户代理实现了建议默认渲染,也建议为此提供设置来提升用户体验, 例如改变色彩对比度,使用不同的焦点样式,或者其他提升可访问性和可用性的方式。

如果指定了建议默认渲染,支持建议默认渲染的用户代理必须根据 渲染部分 定义的规则实现 用户代理 期望 实现的行为。

不支持脚本的用户代理

不支持脚本的实现(或者完全禁用了其脚本特性的用户代理)可以不支持本标准中提到的事件和 DOM 接口。 但对于本标准中定义的事件模型和 DOM,这些用户代理仍然必须表现地像支持事件和 DOM 一样。

脚本可能是构成应用的一部分。不支持脚本或禁用了脚本的 Web 浏览器可能无法完全表达作者的意图。

符合性检查器

符合性检查器必须验证文档是否符合 符合性检查程序必须验证文档是否符合本规范中描述的适用的一致性标准。 自动化的符合检查程序可以不必检测需要解释作者意图的错误(例如, blockquote 的内容不是引用文档就不符合标准,如果符合性检查程序在运行时没有人为判断的输入, 就不必检查 blockquote 元素是否只包含引用的内容)。

符合性检查器必须检查没有 浏览环境 (意味着没有脚本运行,并且禁用了解析器的 脚本标志 )时解析输入文档符合规范, 还应检查在会执行脚本的 浏览环境 下解析输入文档符合规范,并且脚本的执行永远不会导致不符合规范的状态(脚本执行过程中除外)出现。 (这只是一个“应该”而不是“必须”的要求,因为这已被证明是不可能的。[COMPUTABLE]

"HTML 校验器" 可以指代遵循本标准中的适用要求的符合性检查器。

XML DTD 无法表达本标准的所有符合性要求。因此 XML 校验器加 DTD 不能代替符合性检查器。 此外本标准中定义的这两种写作格式都不属于 SGML,因此 SGML 系统也不能代替符合性检查器。

换句话说,有三种符合性规则:

  1. DTD 可表达的规则。
  2. DTD 不可表达但仍然可以由机器检查的规则。
  3. 只能由人工检查的规则。

符合性检查器可以检查前面两种。简单的基于 DTD 的校验器只能检查第一类错误, 因此根据本标准,它不是一种遵循标准的符合性检查器。

数据挖掘工具

不是出于渲染文档或检查文档是否符合规范目的的,处理 HTML 和 XML 文档的应用程序和工具, 其行为应当与其处理的文档的语义保持一致。

只增加每个段落(paragraph)的嵌套层级但不增加每个章节(section)的嵌套层级的 文档大纲 生成工具是不合规范的。

只增加 <p> 的层级而不增加 <section> 的层级会破坏 DOM 原有的语义,比如让段落变成了子段落。

编写工具和标记生成器

编写工具和标记生成器必须生成 符合规范的文档。 在适当的地方,适用于作者的符合性规则也适用于编写工具。

如果编写工具还不能决定作者的意图,可以免除“只能按规定的用途使用元素”的严格要求。 但是编写工具禁止自动地错误使用元素或鼓励它们的用户这样做。

例如,将 address 元素用于任意的联系信息是不合规范的; 该元素只能用于标记文档或章节作者的联系信息。因为编写工具不能区分此意图,所以可以免除这项要求。 但这不意味着(比如)编写工具可以为了斜体字而任意地使用 address 元素; 只意味着编写工具可以在用户给章节插入联系信息时不验证它, 也不需保证用户没用它做别的事或插入别的东西。

在符合性检查方面,文本编辑器必须像符合性检查器一样输出符合规范的文档。

当使用编写工具编辑不符合规范的文档时,可以保持未编辑部分的符合性错误。 (即允许错误的内容经过编辑工具而不发生改变)。 但如果保持了错误,禁止编写工具声明其输出是符合规范的。

编写工具大致分为两类:在结构化或语义数据上进行编辑, 或者在所见即所得的(WYSIWYG)特定媒体上进行编辑。

前者是编写 HTML 工具的理想机制,因为源码信息中的结构可用于更好地选择 HTML 元素和属性。

但是 WYSIWYG 工具也是合理的。WYSIWYG 工具应该使用它们认为合适的元素, 不应该使用它们不确定是否合适的元素。这可能在特定极端情况下意味着对能够使用的流式元素做出限制, 比如 divbi,以及 span,以及使用大量的 style 属性。

不论是不是 WYSIWYG,所有编写工具都应该尽量让用户创建良构的、语义丰富的、媒体无关的内容。

为了防范诸如 DoS 攻击、内存耗尽,或解决平台相关的限制, 用户代理可能会对本来不受约束的输入强加实现相关的限制。

为了兼容既有内容与标准,本标准描述了两种写作格式: 一种基于 XML, 另一种基于 SGML 启发的 自定义格式 (称为 HTML 语法)。 本标准鼓励实现同时支持以上两种格式,但至少支持其中一种。

一些符合性要求称为元素、属性、方法或对象的要求。 这些要求分为两类:描述内容模型限制的,和描述实现行为的。   前者是对文档和编写工具的要求,后者是对用户代理的要求。   类似地,另一些符合性要求称为对作者的要求;这些要求应解释为对作者产出的文档的符合性要求。 (换句话说,本标准不区分对作者和对文档的符合性要求)

2.1.9 Dependencies

This specification relies on several other underlying specifications.

Infra

The following terms are defined in Infra: [INFRA]

Unicode and Encoding

The Unicode character set is used to represent textual data, and Encoding defines requirements around character encodings. [UNICODE]

This specification introduces terminology based on the terms defined in those specifications, as described earlier.

The following terms are used as defined in Encoding: [ENCODING]

  • Getting an encoding
  • Get an output encoding
  • The generic decode algorithm which takes a byte stream and an encoding and returns a character stream
  • The UTF-8 decode algorithm which takes a byte stream and returns a character stream, additionally stripping one leading UTF-8 Byte Order Mark (BOM), if any
  • The UTF-8 decode without BOM algorithm which is identical to UTF-8 decode except that it does not strip one leading UTF-8 Byte Order Mark (BOM)
  • The encode algorithm which takes a character stream and an encoding and returns a byte stream
  • The UTF-8 encode algorithm which takes a character stream and returns a byte stream
  • The BOM sniff algorithm which takes a byte stream and returns an encoding or null.
XML and related specifications

Implementations that support the XML syntax for HTML must support some version of XML, as well as its corresponding namespaces specification, because that syntax uses an XML serialization with namespaces. [XML] [XMLNS]

Data mining tools and other user agents that perform operations on content without running scripts, evaluating CSS or XPath expressions, or otherwise exposing the resulting DOM to arbitrary content, may "support namespaces" by just asserting that their DOM node analogues are in certain namespaces, without actually exposing the namespace strings.

In the HTML syntax, namespace prefixes and namespace declarations do not have the same effect as in XML. For instance, the colon has no special meaning in HTML element names.


The attribute with the name space in the XML namespace is defined by Extensible Markup Language (XML). [XML]

The Name production is defined in XML. [XML]

This specification also references the <?xml-stylesheet?> processing instruction, defined in Associating Style Sheets with XML documents. [XMLSSPI]

This specification also non-normatively mentions the XSLTProcessor interface and its transformToFragment() and transformToDocument() methods. [XSLTP]

URLs

The following terms are defined in URL: [URL]

A number of schemes and protocols are referenced by this specification also:

Media fragment syntax is defined in Media Fragments URI. [MEDIAFRAG]

HTTP and related specifications

The following terms are defined in the HTTP specifications: [HTTP]

The following terms are defined in HTTP State Management Mechanism: [COOKIES]

  • cookie-string
  • receives a set-cookie-string
  • `Cookie` header

The following term is defined in Web Linking: [WEBLINK]

The following terms are defined in Structured Field Values for HTTP: [STRUCTURED-FIELDS]

The following terms are defined in MIME Sniffing: [MIMESNIFF]

Fetch

The following terms are defined in Fetch: [FETCH]

The following terms are defined in Referrer Policy: [REFERRERPOLICY]

The following terms are defined in Mixed Content: [MIX]

Paint Timing

The following terms are defined in Paint Timing: [PAINTTIMING]

Long Tasks

The following terms are defined in Long Tasks: [LONGTASKS]

Web IDL

The IDL fragments in this specification must be interpreted as required for conforming IDL fragments, as described in Web IDL. [WEBIDL]

The following terms are defined in Web IDL:

The Web IDL also defines the following types that are used in Web IDL fragments in this specification:

The term throw in this specification is used as defined in Web IDL. The DOMException type and the following exception names are defined by Web IDL and used by this specification:

When this specification requires a user agent to create a Date object representing a particular time (which could be the special value Not-a-Number), the milliseconds component of that time, if any, must be truncated to an integer, and the time value of the newly created Date object must represent the resulting truncated time.

For instance, given the time 23045 millionths of a second after 01:00 UTC on January 1st 2000, i.e. the time 2000-01-01T00:00:00.023045Z, then the Date object created representing that time would represent the same time as that created representing the time 2000-01-01T00:00:00.023Z, 45 millionths earlier. If the given time is NaN, then the result is a Date object that represents a time value NaN (indicating that the object does not represent a specific instant of time).

JavaScript

Some parts of the language described by this specification only support JavaScript as the underlying scripting language. [JAVASCRIPT]

The term "JavaScript" is used to refer to ECMA-262, rather than the official term ECMAScript, since the term JavaScript is more widely known. Similarly, the MIME type used to refer to JavaScript in this specification is text/javascript, since that is the most commonly used type, despite it being an officially obsoleted type according to RFC 4329. [RFC4329]

The following terms are defined in the JavaScript specification and used in this specification:

Users agents that support JavaScript must also implement ECMAScript Internationalization API. [JSINTL]

WebAssembly

The following term is defined in WebAssembly JavaScript Interface: [WASMJS]

DOM

The Document Object Model (DOM) is a representation — a model — of a document and its content. The DOM is not just an API; the conformance criteria of HTML implementations are defined, in this specification, in terms of operations on the DOM. [DOM]

Implementations must support DOM and the events defined in UI Events, because this specification is defined in terms of the DOM, and some of the features are defined as extensions to the DOM interfaces. [DOM] [UIEVENTS]

In particular, the following features are defined in DOM: [DOM]

The following features are defined in UI Events: [UIEVENTS]

The following features are defined in Touch Events: [TOUCH]

The following features are defined in Pointer Events: [POINTEREVENTS]

This specification sometimes uses the term name to refer to the event's type; as in, "an event named click" or "if the event name is keypress". The terms "name" and "type" for events are synonymous.

The following features are defined in DOM Parsing and Serialization: [DOMPARSING]

The following features are defined in Selection API: [SELECTION]

User agents are encouraged to implement the features described in execCommand. [EXECCOMMAND]

The following parts of Fullscreen API are referenced from this specification, in part to define the rendering of dialog elements, and also to define how the Fullscreen API interacts with HTML: [FULLSCREEN]

High Resolution Time provides the current high resolution time and the DOMHighResTimeStamp typedef. [HRT]

File API

This specification uses the following features defined in File API: [FILEAPI]

Indexed Database API

This specification uses cleanup Indexed Database transactions defined by Indexed Database API. [INDEXEDDB]

Media Source Extensions

The following terms are defined in Media Source Extensions: [MEDIASOURCE]

Media Capture and Streams

The following terms are defined in Media Capture and Streams: [MEDIASTREAM]

Reporting

The following terms are defined in Reporting: [REPORTING]

XMLHttpRequest

The following features and terms are defined in XMLHttpRequest: [XHR]

Battery Status

The following features are defined in Battery Status API: [BATTERY]

Media Queries

Implementations must support Media Queries. The <media-condition> feature is defined therein. [MQ]

CSS modules

While support for CSS as a whole is not required of implementations of this specification (though it is encouraged, at least for web browsers), some features are defined in terms of specific CSS requirements.

When this specification requires that something be parsed according to a particular CSS grammar, the relevant algorithm in CSS Syntax must be followed, including error handling rules. [CSSSYNTAX]

For example, user agents are required to close all open constructs upon finding the end of a style sheet unexpectedly. Thus, when parsing the string "rgb(0,0,0" (with a missing close-parenthesis) for a color value, the close parenthesis is implied by this error handling rule, and a value is obtained (the color 'black'). However, the similar construct "rgb(0,0," (with both a missing parenthesis and a missing "blue" value) cannot be parsed, as closing the open construct does not result in a viable value.

To parse a CSS <color> value, given a string input with an optional element element, run these steps:

  1. Let color be the result of parsing input as a CSS <color>. [CSSCOLOR]

  2. If color is failure, then return failure.

  3. If color is 'currentcolor', then:

    1. If element is not given, then set color to opaque black.

    2. Otherwise, set color to the computed value of the 'color' property of element.

  4. Return color.

The following terms and features are defined in Cascading Style Sheets (CSS): [CSS]

CSS also defines the following border properties: [CSS]

Border properties
Top Bottom Left Right
Width 'border-top-width' 'border-bottom-width' 'border-left-width' 'border-right-width'
Style 'border-top-style' 'border-bottom-style' 'border-left-style' 'border-right-style'
Color 'border-top-color' 'border-bottom-color' 'border-left-color' 'border-right-color'

The basic version of the 'display' property is defined in CSS, and the property is extended by other CSS modules. [CSS] [CSSRUBY] [CSSTABLE]

The following terms and features are defined in CSS Logical Properties: [CSSLOGICAL]

The following terms and features are defined in CSS Color: [CSSCOLOR]

The following terms are defined in CSS Images: [CSSIMAGES]

The term paint source is used as defined in CSS Images Level 4 to define the interaction of certain HTML elements with the CSS 'element()' function. [CSSIMAGES4]

The following features are defined in CSS Backgrounds and Borders: [CSSBG]

The following features are defined in CSS Box Alignment: [CSSALIGN]

The following terms and features are defined in CSS Display: [CSSDISPLAY]

The following features are defined in CSS Flexible Box Layout: [CSSFLEXBOX]

The following terms and features are defined in CSS Fonts: [CSSFONTS]

The following features are defined in CSS Grid Layout: [CSSGRID]

The following terms are defined in CSS Inline Layout: [CSSINLINE]

The following terms and features are defined in CSS Intrinsic & Extrinsic Sizing: [CSSSIZING]

The 'list-style-type' property is defined in CSS Lists and Counters. [CSSLISTS]

The following features are defined in CSS Overflow. [CSSOVERFLOW]

The following features are defined in CSS Positioned Layout: [CSSPOSITION]

The following features are defined in CSS Multi-column Layout. [CSSMULTICOL]

The 'ruby-base' value of the 'display' property is defined in CSS Ruby Layout. [CSSRUBY]

The following features are defined in CSS Table: [CSSTABLE]

The following features are defined in CSS Text: [CSSTEXT]

The following features are defined in CSS Writing Modes: [CSSWM]

The following features are defined in CSS Basic User Interface: [CSSUI]

The algorithm to update animations and send events is defined in Web Animations. [WEBANIMATIONS].

Implementations that support scripting must support the CSS Object Model. The following features and terms are defined in the CSSOM specifications: [CSSOM] [CSSOMVIEW]

The following features and terms are defined in CSS Syntax: [CSSSYNTAX]

The following terms are defined in Selectors: [SELECTORS]

The following features are defined in CSS Values and Units: [CSSVALUES]

The term style attribute is defined in CSS Style Attributes. [CSSATTR]

The following terms are defined in the CSS Cascading and Inheritance: [CSSCASCADE]

The CanvasRenderingContext2D object's use of fonts depends on the features described in the CSS Fonts and Font Loading specifications, including in particular FontFace objects and the font source concept. [CSSFONTS] [CSSFONTLOAD]

The following interfaces and terms are defined in Geometry Interfaces: [GEOMETRY]

The following terms are defined in the CSS Scoping: [CSSSCOPING]

The following terms and features are defined in CSS Color Adjustment: [CSSCOLORADJUST]

Intersection Observer

The following term is defined in Intersection Observer: [INTERSECTIONOBSERVER]

WebGL

The following interfaces are defined in the WebGL specifications: [WEBGL]

WebVTT

Implementations may support WebVTT as a text track format for subtitles, captions, metadata, etc., for media resources. [WEBVTT]

The following terms, used in this specification, are defined in WebVTT:

The WebSocket protocol

The following terms are defined in Fetch: [FETCH]

The following terms are defined in The WebSocket protocol: [WSP]

  • the WebSocket connection is established
  • extensions in use
  • subprotocol in use
  • a WebSocket message has been received
  • send a WebSocket Message
  • fail the WebSocket connection
  • close the WebSocket connection
  • start the WebSocket closing handshake
  • the WebSocket closing handshake is started
  • the WebSocket connection is closed (possibly cleanly)
  • the WebSocket connection close code
  • the WebSocket connection close reason
  • Sec-WebSocket-Protocol field
ARIA

The role attribute is defined in Accessible Rich Internet Applications (ARIA), as are the following roles: [ARIA]

In addition, the following aria-* content attributes are defined in ARIA: [ARIA]

Finally, the following terms are defined ARIA: [ARIA]

Content Security Policy

The following terms are defined in Content Security Policy: [CSP]

Service Workers

The following terms are defined in Service Workers: [SW]

Secure Contexts

The following algorithms are defined in Secure Contexts: [SECURE-CONTEXTS]

Permissions Policy

The following terms are defined in Permissions Policy: [PERMISSIONSPOLICY]

Payment Request API

The following feature is defined in Payment Request API: [PAYMENTREQUEST]

MathML

While support for MathML as a whole is not required by this specification (though it is encouraged, at least for web browsers), certain features depend upon small parts of MathML being implemented. [MATHML]

The following features are defined in Mathematical Markup Language (MathML):

SVG

While support for SVG as a whole is not required by this specification (though it is encouraged, at least for web browsers), certain features depend upon parts of SVG being implemented.

User agents that implement SVG must implement the SVG 2 specification, and not any earlier revisions.

The following features are defined in the SVG 2 specification: [SVG]

Filter Effects

The following feature is defined in Filter Effects: [FILTERS]

Cooperative Scheduling of Background Tasks

The following features are defined in Cooperative Scheduling of Background Tasks: [REQUESTIDLECALLBACK]

Storage

The following terms are defined in Storage: [STORAGE]

Web App Manifest

The following features are defined in Web App Manifest: [MANIFEST]


This specification does not require support of any particular network protocol, style sheet language, scripting language, or any of the DOM specifications beyond those required in the list above. However, the language described by this specification is biased towards CSS as the styling language, JavaScript as the scripting language, and HTTP as the network protocol, and several features assume that those languages and protocols are in use.

A user agent that implements the HTTP protocol must implement HTTP State Management Mechanism (Cookies) as well. [HTTP] [COOKIES]

This specification might have certain additional requirements on character encodings, image formats, audio formats, and video formats in the respective sections.

2.1.10 可扩展性

强烈不鼓励本规范的厂商专有的用户代理扩展。 文档不能使用这样的扩展,因为这样做减少了互操作性并且分割了用户群,只允许特定用户代理的用户访问相关内容。

所有扩展的定义必须使得,扩展的使用既不会违反本标准,也不会导致本标准定义的功能的不一致。

例如(强烈不鼓励这样做)实现上可以为控件添加一个新的 IDL 属性 "typeTime" 返回(比如)用户选择控件的当前值所花费的时间。 另一方面,在表单的 elements 数组中定义一个新的控件也会违反上述要求, 因为它将违反本标准给出的 elements 定义。


当本标准需要厂商中立的扩展时,或者相应地更新本标准,或者编写一个扩展标准并重写本标准中的要求。 如果有人在他的活动中使用了本标准,并决定识别该扩展标准的要求,这一标准就变成了本标准中符合性要求的 适用规范

有人可能会编写一个规范来定义任意的字节流为合规的,然后声明他的随机产生的垃圾为符合规范的。 但是这并不意味着他的随机垃圾符合所有人的目的:如果有人认为该标准不适用于他的工作, 他就可以很合理地说上述随机垃圾就是垃圾,根本不符合规范。 就符合性而言,(某一特定)社区内 同意 适用才是最重要的。


用户代理必须将它们不理解的原始和属性当作语义中立的来处理; (DOM 处理器)把它们留在 DOM 中,(CSS 处理器)根据 CSS 设置它们的样式, 但不要推测它们的语义。

当功能的支持被禁用时(例如作为减轻安全问题的紧急措施或协助开发或出于性能原因), 用户代理的表现必须像不支持该功能一样,像本标准没提到该功能一样。 例如,如果某个特性是通过 Web IDL 接口的属性来访问的,实现该接口的对象将会忽略掉这个属性 — 把属性留在对象上,让它返回 null 或抛出异常是不够的。

2.1.11 与 XPath 和 XSLT 交互

操作以本标准的方式解析或创建的 HTML 文档 (例如作为 document.evaluate() API 的一部分) 的 XPath 1.0 的实现必须在 XPath 1.0 标准的基础上遵循以下改动。

首先,移除这一段话:

节点测试中的 QName 使用表达式上下文的命名空间声明展开为 expanded-name, 展开的方式与开始和结束标签的元素类型名称一样,但是不使用以 xmlns 声明的默认命名空间:如果 QName 没有前缀,那么命名空间 URI 就是 null (这与属性名的展开方式相同)。 如果 QName 的命名空间前缀 在表达式上下文中没有声明将会引发错误。

然后,在同样的位置插入下面一段:

节点测试中的 QName 使用表达式上下文的命名空间声明展开为 expanded-name。 如果 QName 有前缀,则该前缀必须在表达式上下文中有一个 URI 与之关联的命名空间声明, 且相应的。 如果 QName 的命名空间前缀 在表达式上下文中没有声明将会引发错误。

如果 QName 没有前缀且轴的主节点类型为元素,那么使用默认的元素命名空间。 否则,如果 QName 没有前缀,命名空间 URI 就是 null。 默认的元素命名空间是 XPath 表达式的上下文中的成员。 按照 DOM3 XPath API 执行 XPath 表达式时,默认的元素命名空间的值由以下方式决定:

  1. 如果上下文节点来自 HTML DOM,默认元素命名空间是 "http://www.w3.org/1999/xhtml"。
  2. 否则,默认元素命名空间 URI is null。

这相当于将 XPath 2.0 的默认元素命名空间特性添加到 XPath 1.0, 并将 HTML 命名空间用作 HTML 文档的默认元素命名空间。这样做是希望实现兼容于遗留的 HTML 内容的同时, 支持本标准在 HTML 元素命名空间方面引入的变更,以及希望使用 XPath 1.0 而不是 XPath 2.0。

这一变更的 有意的违反 XPath 1.0 标准, 这样做是希望实现兼容于遗留内容的同时支持本标准在 HTML 元素命名空间方面引入的变更。 [XPATH10]


当输出方法为 "html" 时(显式地设置或采用了 XSLT 1.0 的默认规则), XSLT 1.0 处理器的 DOM 输出受一下规则的影响:

如果转换程序输出没有命名空间的元素, 处理器必须在构造相应的 DOM 元素节点之前将元素的命名空间更改为 HTML 命名空间, 将局部名称 改为 ASCII 小写, 并且把元素上无命名空间的属性名 改为 ASCII 小写

本要求是 XSLT 1.0 标准的 故意违反, 本标准为了兼容基于 DOM 的 XSLT 转换,而改变了 HTML 的命名空间和大小写敏感性规则。 (不影响序列化该输出的处理器) [XSLT10]


本标准不指定 XSLT 处理具体如何与 HTML 解析器 基础设施交互 (例如,XSLT 处理器是否将所有元素放到 打开元素栈 中)。 但是当成功地完成后,XSLT 处理器必须 停止解析, 也必须首先将 当前文档就绪状态 设置为 "interactive",在退出后再设置为 "complete"。


本标准不指定 XSLT 如何与 导航 算法进行交互, 如何与 事件循环 相匹配, 也不指定错误页面如何处理(例如 XSLT 错误是替代 XSLT 增量输出,还是内联呈现等等)。

script 元素部分,有一些关于 XSLT 与 HTML 之间交互的非规范性注释, template 元素部分 有一些关于 XSLT,XPath,和 HTML 之间交互的非规范性注释。

2.2 String comparison

A string pattern is a prefix match for a string s when pattern is not longer than s and truncating s to pattern's length leaves the two strings as matches of each other.

2.3 Policy-controlled features

This document defines the following policy-controlled features:

Headers/Feature-Policy/autoplay

Firefox🔰 65+SafariNoChrome64+
Opera51+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android🔰 65+Safari iOSNoChrome Android64+WebView Android64+Samsung Internet9.0+Opera Android47+

Headers/Feature-Policy/document-domain

Firefox🔰 65+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android🔰 65+Safari iOSNoChrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo

2.4 公共微语法

HTML 中有很多地方接受特定的数据类型,比如日期和数字。 这一部分描述了那些类型的内容应符合的标准,以及如何解析它们。

强烈要求实现者仔细地检查考虑用来实现如下语法解析的第三方库。 例如,日期库实现的错误处理行为可能与本标准所要求的不同。 因为在描述类似本标准使用的日期语法的其他标准中,通常没有给出错误处理行为, 所以实现的错误处理可能很不一样。

2.4.1 常见的解析器风格

空格字符 是 在 Unicode PropList.txt 数据文件中 Unicode 属性为 "White_Space" 的字符。[UNICODE]

不要与 Unicode.txt 数据文件中 "Bidi_Class" 属性的 "White_Space" 值(缩写为 "WS")相混淆。

有些下面描述的微解析器遵循这样的模式:维护一个 input 变量保存待解析字符串,以及一个 position 变量指向 input 中下一个要解析的字符。

2.4.2 布尔属性

有些属性是 布尔属性。 布尔属性出现在元素上表示值为 true,不出现表示表示值为 false。

如果该属性出现,它的值必须为空字符串或者匹配属性的标准名称的 ASCII 大小写不敏感 字符串, 并且前后没有空格。

布尔属性上不允许 "true" 和 "false" 值。 为了表示 false 值,应该一并忽略该属性。

这里有一个例子,表示复选框被选中和禁用。 checkeddisabled 属性就是布尔属性。

<label><input type=checkbox checked name=cheese disabled> Cheese</label>

这可以等价地写成:

<label><input type=checkbox checked=checked name=cheese disabled=disabled> Cheese</label>

你也可以混合两种风格;下面的写法仍然是等价的:

<label><input type='checkbox' checked name=cheese disabled=""> Cheese</label>

2.4.3 关键字和枚举属性

有些属性定义为取值只能是有限的关键字集合中的一个。 这样的属性称为 枚举属性。 这些关键字都定义为映射到特定的状态 state (可能多个关键字映射到同一个状态, 此时这些关键字互为同义词;此外有些关键字其实是不合规范的,它们在还在这里完全是历史原因)。 除此之外可以给出两个默认状态:第一个是 非法值的默认状态, 第二个是 缺失值的默认状态

如果指定了枚举属性,属性值必须是一个匹配其中一个关键字(不包括不合规范)的 ASCII 大小写不敏感 字符串,并且前后没有空格。

指定属性时,如果它的值是匹配其中一个关键字的 ASCII 大小写不敏感 字符串 那么该属性表示的状态就是该关键字的状态。如果属性值不匹配任何给定的关键字,但该属性有一个 非法值的默认状态,那么该属性表示那个状态。 否则如果该属性的值不匹配任何关键字但定义有一个 缺失值的默认状态, 那么该属性表示的状态就是 那个状态。否则,没有默认状态的情况, 非法值不表示任何状态。

没有 指定属性时,如果定义有 缺失值的默认状态, 那么这个(缺失)属性表示的状态就是这个状态。否则, 缺失的属性不表示任何状态。

空字符串可以是一个合法的关键字。

2.4.4 数字

2.4.4.1 有符号整数

由一个或更多 ASCII 数字 组成的字符串就是 合法的整数。 可以有一个 U+002D HYPHEN-MINUS 字符 (-) 作为前缀。

没有 U+002D HYPHEN-MINUS 字符 (-) 作为前缀的 合法整数 表示 该数字字符串以 10 为基所表示的数字。 有着 U+002D HYPHEN-MINUS 字符 (-) 作为前缀的 合法的整数 表示零减去该字符串以 10 为基所表示的数字。

解析整数的规则 由下列算法给出。 被调用时,必须以给定的步骤执行,在第一个有返回值的步骤中止。该算法会返回一个整数或者一个错误。

  1. input 为被解析的字符串。

  2. positioninput 里面的指针,初始指向字符串的开始。

  3. sign 拥有值 "positive"。

  4. 跳过 input 中的 ASCII 空格,得到 position

  5. 如果 position 越过了 input 的末尾,返回一个错误。

  6. 如果 position 处的(第一个)字符是一个 U+002D HYPHEN-MINUS 字符 (-):

    1. sign 为 "negative"。
    2. position 前进到下一个字符。
    3. 如果 position 越过了 input 的末尾,返回一个错误。

    否则,如果 position 处的(第一个)字符是一个 U+002B PLUS SIGN 字符 (+):

    1. position 前进到下一个字符。 (虽然 "+" 会被忽略但并不符合规范。)
    2. 如果 position 越过了 input 的末尾,返回一个错误。
  7. 如果 position 处的字符不是 ASCII 数字,则返回一个错误。

  8. input 的给定 position 收集ASCII 数字 的代码点序列,将得到的序列解释为以10为基的整数。 令 value 为该整数。

  9. 如果 sign 为 "positive",返回 value,否则返回0减去 value 的结果。

2.4.4.2 非负整数

由一个或更多 ASCII 数字 组成的字符串就是 合法的非负整数

合法的非负整数 表示该数字字符串以10为基所表示的数字。

解析非负整数的规则 由以下算法给出,被调用时该算法必须按顺序执行以下步骤,在第一个有返回值的步骤中止。 该算法将返回 0,正整数或者错误。

  1. input 为被解析的字符串。

  2. value 为使用 解析整数的规则 解析 input 的结果。

  3. 如果 value 是一个错误, 返回一个错误。

  4. 如果 value 小于零, 返回一个错误。

  5. 返回 value

2.4.4.3 浮点数

合法的浮点数 这样构成:

  1. 一个可选的 U+002D HYPHEN-MINUS 字符(-)。
  2. 下面的其中一个或者依次的两个:
    1. 一个或更多 ASCII 数字 组成的序列。
    2. 依次出现:
      1. 单个 U+002E FULL STOP 字符(.)。
      2. 一个或更多 ASCII 数字 组成的序列。
  3. 可选地:
    1. 一个 U+0065 LATIN SMALL LETTER E 字符(e)或 U+0045 LATIN CAPITAL LETTER E 字符(E)。
    2. 可选地,一个 U+002D HYPHEN-MINUS 字符(-) 或 U+002B PLUS SIGN 字符 (+)。
    3. 一个或更多 ASCII 数字 组成的序列。

合法的浮点数 表示将有效数乘以10的指数。 其中有效数是第一个数字,按十进制解析(包括小数点和小数点后的数字,如果后面有的话) 如果整个字符串以 U+002D HYPHEN-MINUS character (-)字符开始且该数字不为零的话, 将有效数解析为负数。 其中指数是 E 后面的数字(如果有的话),如果在 E 和该数字之间有一个 U+002D HYPHEN-MINUS 字符(-) 且该数字不为零的话,解析为负数,如果在 E 和该数字之间有一个 U+002B PLUS SIGN 字符(+)的话忽略该字符。 如果没有 E,指数当做零来处理。

Infinity 和 Not-a-Number (NaN)值不是 合法的浮点数

典型地, 合法的浮点数 的概念只用于限制作者,对用户代理的要求采用下面的 解析浮点数值的规则 (例如,progress 元素的 max 属性)。 然而,在某些情况下要求用户代理检查字符串是否是 合法的浮点数(例如, Number 状态的 input 元素的 值清理算法,或者 解析 srcset 属性 算法)。

浮点数的最佳表示 n 是 运行 ToStringn)得到的字符串。 ToString 抽象方法不是唯一确定的。如果在特定的值上运行 ToString 可能得到多个字符串,用户代理必须对那个值总是返回同样的字符串 (虽然它可能和其他用户代理使用的值不同)。

解析浮点数值的规则 由以下算法给出。 该算法必须在第一个有返回值的步骤中止。 该算法将会返回一个数字或者错误。

  1. input 为被解析的字符串。

  2. positioninput 内的指针,初始指向字符串的开始。

  3. value 的值为 1。

  4. divisor 的值为 1。

  5. exponent 的值为 1。

  6. 跳过 input 中的 ASCII 空格,得到 position

  7. 如果 position 越过了 input 的末尾,返回一个错误。

  8. 如果 position 处的(第一个)字符是一个 U+002D HYPHEN-MINUS 字符 (-):

    1. valuedivisor 改为 −1。
    2. position 前进到下一个字符。
    3. 如果 position 越过了 input 的末尾,返回一个错误。

    否则,如果 position 处的(第一个)字符是一个 U+002B PLUS SIGN 字符 (+):

    1. position 前进到下一个字符。 (虽然 "+" 会被忽略但并不符合规范。)
    2. 如果 position 越过了 input 的末尾,返回一个错误。
  9. 如果 position 处的字符是 U+002E FULL STOP (.),且不是 input 的最后一个字符, 而且 position 表示的字符的后一个字符是 ASCII 数字, 则将 value 设置为零并跳到 fraction 标记的步骤。

  10. 如果 position 处的数字不是 ASCII 数字, 则返回一个错误。

  11. input 的给定 position 收集ASCII 数字 的代码点序列,将得到的序列解释为以10为基的整数。 将 value 乘以该整数。

  12. 如果 position 越过了 input 的末尾,跳到标记为 conversion 的步骤。
  13. Fraction:如果 position 处的数字是 U+002E FULL STOP (.),运行以下子步骤:

    1. position 前进到下一个字符。

    2. 如果 position 越过了 input 的末尾或者不是 ASCII 数字、 U+0065 LATIN SMALL LETTER E (e),或 U+0045 LATIN CAPITAL LETTER E (E), 跳到 conversion 标记的步骤。

    3. 如果 position 处的字符是 U+0065 LATIN SMALL LETTER E character (e)或 U+0045 LATIN CAPITAL LETTER E 字符(E),跳过下面的子步骤。

    4. Fraction loop: 将 divisor 乘以 10。

    5. 按照十进制(0..9)解释 position 处的字符,除以 divisor, 加到 value 上。
    6. position 前进到下一个字符。

    7. 如果 position 越过了 input 的末尾, 跳到 conversion 标记的步骤。

    8. 如果 position 处的字符是 ASCII 数字, 跳回到 fraction loop 标记的子步骤。

  14. 如果 position 处的字符是 U+0065 (e)或 U+0045 (E),则:

    1. position 前进到下一个字符。

    2. 如果 position 越过了 input 的末尾,跳到标记为 conversion 的步骤。

    3. 如果 position 处的字符是 U+002D HYPHEN-MINUS 字符(-):

      1. exponent 设置为 −1。
      2. position 前进到下一个字符。
      3. 如果 position 越过了 input 的末尾,跳到标记为 conversion 的步骤。

      否则,如果 position 处的字符是 U+002B PLUS SIGN 字符(+):

      1. position 前进到下一个字符。
      2. 如果 position 越过了 input 的末尾,跳到标记为 conversion 的步骤。

    4. 如果 position 处的字符不是 ASCII 数字,则跳到标记为 conversion 的步骤。

    5. input 的给定 position 收集ASCII 数字 的代码点序列,将得到的序列解释为以 10 为基的整数。 将 exponent 乘以该整数。

    6. value 乘以 10 的 exponent 指数。

  15. Conversion: 令S 为 IEEE 754 双精度浮点数值的有限集, −0 除外,但新增 21024 和 −21024 两个值。

  16. rounded-valueS 最接近 value 的数字, 如果有两个同样接近的数值,则选择有效数为奇数的数字。 (在这个处理中,21024 和 −21024 这两个特殊值应视为有奇数的有效数。)

  17. 如果 rounded-value 是 21024 或 −21024,返回错误。

  18. 返回 rounded-value

2.4.4.4 百分数和长度

解析维度值的规则 由下面算法给出。被调用时必须按给定顺序执行这些步骤,并在第一个有返回值的步骤中止。 本算法将会返回一个大于等于 0.0 的数字,或者一个错误;如果返回了数字, 那么它可能是百分数或者长度。

  1. input 为被解析的字符串。

  2. positioninput 中的指针,初始指向字符串的开始。

  3. 跳过 input 中的 ASCII 空格,得到 position

  4. 如果 position 越过了 input 的末尾,返回一个错误。

  5. 如果 position 处的字符是一个 U+002B PLUS SIGN 字符 (+), 将 position 前进到下一个字符

  6. 如果 position 越过了 input 的末尾,返回一个错误。

  7. 如果 position 处的字符不是 ASCII 数字,则返回一个错误。

  8. input 的给定 position 收集ASCII 数字 的代码点序列,将得到的序列解释为以 10 为基的整数。 令 value 为该整数。

  9. 如果 position 越过了 input 的末尾,将 value 作为长度返回。

  10. 如果 position 处的字符是 U+002E FULL STOP character (.):

    1. position 前进到下一个字符。

    2. 如果 position 越过了 input 的末尾,或者 position 处的字符不是 ASCII 数字,则将 value 作为长度返回。

    3. divisor 值为 1。

    4. Fraction loop:将 divisor 乘以 10。

    5. 按照十进制(0..9)解释 position 处的字符,除以 divisor, 加到 value 上。
    6. position 前进到下一个字符。

    7. 如果 position 越过了 input 的末尾,则将 value 作为长度返回。

    8. 如果 position 处的字符是一个 ASCII 数字, 返回到标记为 fraction loop 的子步骤。

  11. 如果 position 越过了 input 的末尾,则将 value 作为长度返回。

  12. 如果 position 处的字符是 U+0025 PERCENT SIGN character(%), 将 value 作为百分数返回。

  13. value 作为长度返回。

2.4.4.5 非零百分数和长度

解析非零维度值的规则 由下列算法给出。被调用时必须按给定顺序执行这些步骤,并在第一个有返回值的步骤中止。 本算法将会返回一个大于 0.0 的数字或者一个错误;如果返回了数字, 那么它可能是百分数或者长度。

  1. input 为被解析的字符串。

  2. value 为使用 解析维度值的规则 解析 input 的结果。

  3. 如果 value 是一个错误,返回一个错误。

  4. 如果 value 为 0,返回一个错误。

  5. 如果 value 为百分数,将 value 作为百分数返回。

  6. value 作为长度返回。

2.4.4.6 浮点数列表

合法的浮点数列表 是以 U+002C COMMA 字符分隔的 合法浮点数 , 且没有其他字符(比如 ASCII 空格)。 此外,可能会有浮点数个数限制,或者取值范围限制。

解析浮点数列表的规则 如下:

  1. input 为被解析的字符串。

  2. positioninput 中的指针,初始指向字符串的开始。

  3. numbers 为空的浮点数列表。该列表将会是本算法的结果。

  4. input 的给定 position 收集ASCII 空格, U+002C COMMA,或者 U+003B SEMICOLON 字符的代码点序列。 本步骤跳过了所有前导分隔符。

  5. position 没有越过 input 的末尾时:

    1. input 的给定 position 收集 不是 ASCII 空格, U+002C COMMA,U+003B SEMICOLON, ASCII 数字, U+002E FULL STOP, 或 U+002D HYPHEN-MINUS 字符的代码点序列。 本步骤跳过了前导的无用字符。

    2. input 的给定 position 收集 不是 ASCII 空格, U+002C COMMA,或者 U+003B SEMICOLON 字符的代码点序列,令 unparsed number 为收集的结果。

    3. number 为使用 解析浮点数值的规则 解析 unparsed number 的结果。

    4. 如果 number 是一个错误,将 number 设置为 0。

    5. number 添加到 numbers

    6. input 的给定 position 收集ASCII 空格, U+002C COMMA,或者 U+003B SEMICOLON 字符的代码点序列。 本步骤跳过了分隔符。

  6. 返回 numbers

2.4.4.7 维度值列表

解析维度值列表的规则 如下。 这些规则返回一个由数字或单位组成的偶对列表,包含0个或更多偶对。 其中的单位是 percentage, relative,和 absolute 之一。

  1. raw input 为被解析的字符串。

  2. 如果 raw input 的最后一个字符是 U+002C COMMA character(,), 则从 raw input 中移除该字符。

  3. 用逗号分割 raw input 字符串。 令raw tokens 为得到的标记列表。

  4. result 为 number/unit 偶对的空列表。

  5. raw tokens 中的每一个标记,运行以下子步骤:

    1. input 为该标记。

    2. positioninput 中的指针,初始指向字符串的开始。

    3. value 为数字 0。

    4. unitabsolute

    5. 如果 position 越过了 input 的末尾,将 unit 设为 relative 并跳到最后一个子步骤。

    6. 如果 position 处的字符是 ASCII 数字, 从 input 的给定 position 收集ASCII 数字 的代码点序列,将得到的序列解释为以10为基的整数, 将 value 递增这个整数。

    7. 如果在 position 处的字符是 U+002E(.),则:

      1. input 的给定 position 收集ASCII 空格ASCII 数字 的代码点序列, 令 s 为得到的结果序列。

      2. 移除 s 中所有的 ASCII 空格

      3. 如果 s 不是空字符串,则:

        1. lengths 中(移除空格后的)字符数。

        2. fraction 为将 s 解释为以10为基的整数后的结果, 将这个数字除以 10length

        3. value 递增 fraction

    8. 从给定的 position 跳过 input 中的 ASCII 空白字符

    9. 如果 position 处的字符是 U+0025 PERCENT SIGN 字符(%), 将 unit 设为 percentage

      否则,如果 position 处的字符是 U+002A ASTERISK 字符(*), 则将 unit 设为 relative

    10. result 中增加一项,包含由 value 给定的数字, 以及由 unit 给定的单位。

  6. 返回 result 列表。

2.4.5 日期和时间

在下面的算法中, yearmonth 月的天数 是: 这考虑了格里历(现行公历)的闰年。[GREGORIAN]

当本部分定义的日期与时间语法中使用了 ASCII 数字 时, 这些数字表示10进制数。

虽然这里描述的格式旨在成为相应的 ISO8601 格式的子集,但是本规范比 ISO8601 更详细地定义了解析规则。因此,在使用实现者之前,请仔细检查任何日期解析库,然后再使用它们来实现下面描述的解析规则; ISO8601 库可能不会以完全相同的方式解析日期和时间。[ISO8601]

本标准中的 外推格里历 是指现代格里历向前外推到第 1 年。 外推格里历 中的日期 (有时直接称 外推格里历日期), 的指用外推格里历描述的日期,即使当时还没有颁布格里历。 [GREGORIAN]

格里历在本标准中作为连线协议使用并非出于决策者的文化偏好。参考: 对表单中的 date,time,和 number 格式 的讨论 (对作者而言), 关于表单控件本地化的实现说明,, 以及 time 元素。

2.4.5.1 月份

月份 由特定的 外推格里历日期 组成, 不包含时区信息,也不包含年和月以上的日的信息。[GREGORIAN]

表示 yearmonth 月的 合法的月字符串 包含下列部分(有序):

  1. 表示 year 年的 4 个或更多 ASCII 数字, 其中 year > 0
  2. 一个 U+002D HYPHEN-MINUS 字符(-)
  3. 表示 month 月的两个 ASCII 数字,在范围 1 ≤ month ≤ 12 之内

解析月字符串 的规则如下。将返回年和月,或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. input 为待解析字符串。

  2. positioninput 内的指针初始指向字符串开始。

  3. 解析月的部分 来获得 yearmonth。 如果它没有返回,则失败。

  4. 如果 position 没有 超出 input 的结尾,则失败。

  5. 返回 yearmonth

给定 input 字符串和位置 position解析月的部分 的规则如下。 将返回年和月,或者什么都不返回。 如果算法的任何一个步说它 "失败了",这意味着它在那一步退出并什么都不返回。

  1. input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。 如果收集到的序列不够 4 个字符则失败。 否则将结果序列解释为 10 进制整数。令那个数为 year

  2. 如果 year 不是大于0的数字则失败。。

  3. 如果 position 超出了 input 的末尾或者 position 处的字符不是 U+002D HYPHEN-MINUS 字符,则失败。 否则将 position 前进一个字符。

  4. input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。 如果收集到的序列不是恰好 2 个字符则失败。 否则将结果序列解释为 10 进制整数。令那个数为 month

  5. 如果 month 不是 1 ≤ month ≤ 12 范围内的数字就失败。

  6. 返回 yearmonth

2.4.5.2 日期

日期 由特定的 外推格里历日期 组成, 不包含时区信息,由年、月、日组成。[GREGORIAN]

表示 year 年,month 月,day 日的 合法的日期字符串 由下列几个有序的组成部分:

  1. 表示 yearmonth合法的月字符串
  2. 一个 U+002D HYPHEN-MINUS 字符(-)
  3. 表示 day 的两个 ASCII 数字, 处于范围 1 ≤ day ≤ maxday 内,其中 maxdayyearmonth 月的天数

解析日期字符串 的规则如下。将会返回一个日期或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. input 为待解析字符串。

  2. positioninput 内的指针初始指向字符串开始。

  3. 解析日期部分 来获得 yearmonthday。 如果它没有返回,则失败。

  4. 如果 position 没有 超出 input 的结尾,则失败。

  5. date 的年月日分别为 yearmonthday

  6. 返回 date

给定 input 字符串和位置 position解析日期部分 的规则如下。 将返回年、月、日,或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. 解析月的部分 来获得 yearmonth 如果它没有返回,则失败。

  2. maxdayyearmonth 月的天数

  3. 如果 position 超出了 input 的末尾或者 position 处的字符不是 U+002D HYPHEN-MINUS 字符,则失败。 否则将 position 前进一个字符。

  4. input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。 如果收集到的序列不是恰好 2 个字符则失败。 否则将结果序列解释为 10 进制整数。令那个数为 day

  5. 如果 day 不是 1 ≤ day ≤ maxday 范围内的数字就失败。

  6. 返回 yearmonthday

2.4.5.3 无年的日期

一个 无年的日期 由一个格里历月和该月内的一天组成,但没有关联的年份。[GREGORIAN]

表示 monthday 日的 合法的无年日期 包含如下有序的部分:

  1. 可选地,两个 U+002D HYPHEN-MINUS 字符 (-)
  2. 表示 month 月的两个 ASCII 数字,在范围 1 ≤ month ≤ 12 之内
  3. 一个 U+002D HYPHEN-MINUS 字符 (-)
  4. 表示 day 的两个 ASCII 数字, 处于范围 1 ≤ day ≤ maxday 内,其中 maxday 任意闰年(例如 4 或 2000)的 month 月的天数

换句话说,如果 month 为 "02"(二月), 那么可以是 29 日,把这一年当做闰年。

解析无年的日期字符串 的规则如下。 将会返回月和日,或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. input 为待解析字符串。

  2. positioninput 内的指针初始指向字符串开始。

  3. 解析无年的日期部分 来获得 monthday。 如果它没有返回,则失败。

  4. 如果 position 没有 超出 input 的结尾,则失败。

  5. 返回 monthday

给定 input 字符串和位置 position解析无年的日期部分 的规则如下。 将返回月和日,或者什么都不返回。 如果算法的任何一个步说它 "失败了",这意味着它在那一步退出并什么都不返回。

  1. input 中给定的位置 position 收集 U+002D HYPHEN-MINUS 字符 (-)组成的代码点序列。 如果收集到的序列长度不是 0 或 2,就失败。

  2. input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。 如果收集到的序列长度不是 2 就失败。 否则将结果序列解释为 10 进制整数。令那个数为 month

  3. 如果 month 不是 1 ≤ month ≤ 12 范围内的数字就失败。

  4. maxday 任意闰年(例如 4 或 2000)的 month 月的天数

  5. 如果 position 超出了 input 的末尾或者 position 处的字符不是 U+002D HYPHEN-MINUS 字符,则失败。 否则将 position 前进一个字符。

  6. input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。 如果收集到的序列不是恰好 2 个字符则失败。 否则将结果序列解释为 10 进制整数。令那个数为 day

  7. 如果 day 不是 1 ≤ day ≤ maxday 范围内的数字就失败。

  8. 返回 monthday

2.4.5.4 时间

时间 由一个没有时区信息的特定时间组成。 包含小时、分钟、秒,以及秒的小数。

hourminutesecond 秒的 合法的时间字符串 由以下有序的几部分组成:

  1. 表示 hour 的两个 ASCII 数字, 在 0 ≤ hour ≤ 23 范围内
  2. 一个 U+003A COLON 字符 (:)
  3. 表示 minute 的两个 ASCII 数字, 在 0 ≤ minute ≤ 59 范围内
  4. 如果 second 不是零(是零也合法):
    1. 一个 U+003A COLON 字符(:)
    2. 表示 second 的两个 ASCII 数字, 在 0 ≤ second ≤ 59 范围内
    3. 如果 second 不是整数(是整数也合法):
      1. 一个 U+002E FULL STOP 字符(.)
      2. 表示 second 的一到三个 ASCII 数字

second 部分不可以是 60 或 61;闰秒无法表示。

解析时间字符串 的规则如下。将会返回一个时间或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. input 为待解析字符串。

  2. positioninput 内的指针初始指向字符串开始。

  3. 解析时间部分 来获得 hourminutesecond。 如果它没有返回,则失败。

  4. 如果 position 没有 超出 input 的结尾,则失败。

  5. time 的时分秒分别为 hourminutesecond

  6. 返回 time

给定 input 字符串和位置 position解析时间部分 的规则如下。 将返回时、分、秒,或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。 如果收集到的序列不是恰好 2 个字符则失败。 否则将结果序列解释为 10 进制整数。令那个数为 hour

  2. 如果 hour 不是 0 ≤ hour ≤ 23 范围内的数字就失败。

  3. 如果 position 超出了 input 的末尾或者 position 处的字符不是 U+003A COLON 字符,则失败。 否则将 position 前进一个字符。

  4. input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。 如果收集到的序列不是恰好 2 个字符则失败。 否则将结果序列解释为 10 进制整数。令那个数为 minute

  5. 如果 minute 不是 0 ≤ minute ≤ 59 范围内的数字就失败。

  6. second 为 0。

  7. 如果 position 没有超出 input 的末尾并且 position 处的字符是 U+003A(:),则:

    1. position 前进一个字符。

    2. 如果 position 恰好位于或者超出了 input 的末尾, 或者 input 中从 position 开始的 两个 字符不都是 ASCII 数字,则失败。

    3. input 中给定的位置 position 收集 ASCII 数字 或 U+002E FULL STOP 字符 组成的代码点序列。 如果收集到的序列长度为 3, 或者长度大于 3 且第 3 个字符不是 U+002E FULL STOP 字符, 或者有多于一个的 U+002E FULL STOP 字符,则失败。 否则将结果序列解释为 10 进制数(可能有小数部分)。 将 second 设置为那个数字。

    4. 如果 second 不是 0 ≤ second < 60 范围内的数字就失败。

  8. 返回 hourminutesecond

2.4.5.5 本地日期和时间

本地日期和时间 由一个特定的 外推格里历日期(包含年、月、日) 和时间(包含时、分、秒,以及秒的小数),但没有时区。[GREGORIAN]

表示日期和时间的 合法的本地日期和时间字符串 由以下有序的部分组成:

  1. 表示日期的 合法的日期字符串
  2. 一个 U+0054 LATIN CAPITAL LETTER T 字符(T)或者 U+0020 SPACE 字符
  3. 表示时间的 合法的时间字符串

表示日期和时间的 合法的正则化的本地日期和时间字符串 由以下有序的几部分组成:

  1. 表示日期的 合法的日期字符串
  2. 一个 U+0054 LATIN CAPITAL LETTER T 字符 (T)
  3. 表示时间的 合法的时间字符串, 按给定时间的最短可能的字符串表示。(例如如果秒是 0 的话忽略秒的部分)

解析本地日期和时间字符串 的规则如下。 将会返回一个日期或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. input 为待解析字符串。

  2. positioninput 内的指针初始指向字符串开始。

  3. 解析日期部分 来获得 yearmonthday。 如果它没有返回,则失败。

  4. 如果 position 超出了 input 的末尾或者 position 处的字符是 U+0054 LATIN CAPITAL LETTER T 字符(T) 或 U+0020 SPACE 字符,则失败。否则将 position 前进一个字符。

  5. 解析时间部分 来获得 hourminutesecond。 如果它没有返回,则失败。

  6. 如果 position 没有 超出 input 的结尾,则失败。

  7. date 的年月日分别为 yearmonthday

  8. time 的时分秒分别为 hourminutesecond

  9. 返回 datetime

2.4.5.6 时区

时区 由一个小时和分钟的有符号数字组成。

表示时区的 合法的时区字符串 包含下列之一:

此格式允许从-23:59到+23:59的时区偏移。 现在,实际时区的偏移范围是-12:00到+14:00,分钟分量始终是 00,30 或 45。 但不能保证情况永远是这样的,因为时区被用作政治足球,受到异想天开的政策的支配。

另请参阅下面的 全球日期和时间 部分的使用说明和示例,具体了解如何在正式的时区形成之前的历史时间上使用时区偏移。

解析时区偏移字符串 的规则如下。 将会返回一个时区偏移或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. input 为待解析字符串。

  2. positioninput 内的指针初始指向字符串开始。

  3. 解析时区偏移部分 来获得 timezonehourstimezoneminutes。 如果它没有返回,则失败。

  4. 如果 position 没有 超出 input 的结尾,则失败。

  5. 返回距离 UTC timezonehours 小时 timezoneminutes 分钟的时区偏移。

给定 input 字符串和位置 position解析时区偏移部分 的规则如下。 将会返回一个时区偏移的小时和分钟,或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. 如果 position 处的字符是一个 U+005A LATIN CAPITAL LETTER Z 字符(Z),则:

    1. timezonehours 为 0。

    2. timezoneminutes 为 0。

    3. position 前进到 input 的下一个字符。

    否则,如果 position 是 U+002B PLUS SIGN (+)或 U+002D HYPHEN-MINUS (-),则:

    1. 如果 position 处的字符是一个 U+002B PLUS SIGN (+),令 sign 为 "正"。 如果它是一个 U+002D HYPHEN-MINUS (-),则令 sign 为 "负"。

    2. position 前进到 input 的下一个字符。

    3. input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。令 s 为收集到的序列。

    4. 如果 s 恰好是两个字符长度,则:

      1. s 解释为10进制整数,并赋值给 timezonehours

      2. 如果 position 超出了 input 的末尾或者 position 处的字符不是 U+003A COLON 则失败。 否则将 position 前进一个字符。

      3. input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。 如果收集到的序列不是恰好 2 个字符则失败。 否则将结果序列解释为 10 进制整数。令那个数为 timezoneminutes

      如果 s 恰好是 4 个字符长度,则:

      1. s 的前两个字解释为 10 进制整数,并赋值给 timezonehours

      2. s 的后两个字解释为 10 进制整数,并赋值给 timezoneminutes

      其他情况失败。

    5. 如果 timezonehours 不在 0 ≤ timezonehours ≤ 23 范围内则失败。
    6. 如果 sign 为 "负",则对 timezonehours 求反。
    7. 如果 timezoneminutes 不在 0 ≤ timezoneminutes ≤ 59 范围内则失败。
    8. 如果 sign 为 "负",则对 timezoneminutes 求反。

    其他情况失败。

  2. 返回 timezonehourstimezoneminutes

2.4.5.7 全球日期和时间

全球日期和时间 由一个特定的 外推格里历日期(包含年、月、日) 和时间(包含时、分、秒,以及秒的小数),以及附加的时区信息,一个包括小时和分钟的有符号数。[GREGORIAN]

表示日期、时间和时区的的 合法的全球日期和时间字符串 由以下有序的部分组成:

  1. 表示日期的 合法的日期字符串
  2. 一个 U+0054 LATIN CAPITAL LETTER T 字符(T)或者 U+0020 SPACE 字符
  3. 表示时间的 合法的时间字符串
  4. 表示时区的 合法的时区偏移字符串

在 20 世纪中叶 UTC 形成之前的时间必须按照 UT1(0° 经度处的太阳时)而不是 UTC( UT1 的近似,按照 SI 制秒增长)表示和解析。时区形成前的时间必须按照 UT1 时间表示和解析, 且带有明确的时区信息,以此来近似适当的本地时间和伦敦格林尼治观测到的时间差。

下面是按照 合法的全球日期和时间字符串 编写的日期示例。

"0037-12-13 00:00Z"
使用伦敦时间的地区的午夜,罗马皇帝 Nero 的生日。关于实际对应的日期见下文的进一步讨论。
"1979-10-14T12:00:00.001-04:00"
美国东海岸夏令时的 1979 年 10 月 14 日正午之后的一毫秒。
"8592-01-01T02:09+02:09"
UTC 时间 8592 年 1 月 1 日午夜。其时区是快于 UTC 的 2 小时 9 分钟, 目前还没有这个时区,尽管如此,它是允许的。

关于这些日期,值得一提的是:

解析全球日期和时间字符串 的规则如下。 将会返回一个带有时区信息(为了能够往返转换或显示等用途)的 UTC 时间,或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. input 为待解析字符串。

  2. positioninput 内的指针初始指向字符串开始。

  3. 解析日期部分 来获得 yearmonthday。 如果它没有返回,则失败。

  4. 如果 position 超出了 input 的末尾或者 position 处的字符是 U+0054 LATIN CAPITAL LETTER T 字符(T) 或 U+0020 SPACE 字符,则失败。否则将 position 前进一个字符。

  5. 解析时间部分 来获得 hourminutesecond。 如果它没有返回,则失败。

  6. 如果 position 超出了 input 的结尾,则失败。

  7. 解析时区偏移部分 来获得 timezonehourstimezoneminutes。 如果它没有返回,则失败。

  8. 如果 position 没有 越过 input 的结尾,则失败。

  9. 令时刻 time 的年月日时分秒分别为 yearmonthdayhourminutesecond,减去 timezonehours 小时 timezoneminutes 分钟。 该时刻的时区为 UTC 时区。

  10. timezone 为距 UTC timezonehours 小时 timezoneminutes 分钟的时区偏移。

  11. 返回 timetimezone

2.4.5.8 星期

星期 由一个表示年的数字(星期年)和一个表示星期的数字(周号)组成,表示从周一开始的 7 天时间段。 在这个日历系统中,每个星期年有 52 或 53 个这样的 7 天,定义如下。这样的 7 天周期从格里历 1969 年 12 月 29 日(1969-12-29)开始, 这一周被定义为 1970 年的第 1 周。后续的星期都依次进行编号。一个星期年的第一周之前是上一个星期年的最后一周,反之亦反。 [GREGORIAN]

如果编号为 year 的星期年对应的 外推格里历year 第一天(1月1日)是周二,或者这一天是周三且 year 可被 400 整除或可被 4 整除但不可被 100 整除, 那么这一星期年有 53 周。其他所有星期年都有 52 周。

有 53 周的星期年的 最后一天的周号 是 53; 有 52 周的星期年的最后一天的周号是 52。

特定日期的星期年的编号可能与包含这一天的 外推格里历 年不同。 星期年 y 的第一周为包含第一个周二的格里历年 y

为了现代目的,这里定义的 星期 等价于定义在 ISO 8601 中的 ISO 星期。 [ISO8601]

表示星期年 year 和周号 week合法的星期字符串 有下列几个有序的组成部分:

  1. 表示 year 的 4 个或更多 ASCII 数字,其中 year > 0
  2. 一个 U+002D HYPHEN-MINUS 字符 (-)
  3. 一个 U+0057 LATIN CAPITAL LETTER W 字符 (W)
  4. 表示周号 week 的两个 ASCII 数字,其中 1 ≤ week ≤ maxweekmaxweek 为星期年 year 最后一天的周号

解析星期字符串 的规则如下。将会返回星期年和周号两个数字,或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. input 为待解析字符串。

  2. positioninput 内的指针初始指向字符串开始。

  3. input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。 如果收集到的序列长度小于 4 个字符长度则失败。 否则将结果序列解释为 10 进制整数。令那个数为 year

  4. 如果 year 小于等于零则失败。

  5. 如果 position 超出了 input 的末尾或者 position 处的字符不是 U+002D HYPHEN-MINUS 字符则失败。 否则将 position 前进一个字符。

  6. 如果 position 超出了 input 的末尾或者 position 处的字符不是 U+0057 LATIN CAPITAL LETTER W 字符(W)则失败。 否则将 position 前进一个字符。

  7. input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。 如果收集到的序列不是恰好 2 个字符长度则失败。 否则将结果序列解释为 10 进制整数。令那个数为 week

  8. maxweekyear最后一天的周号

  9. 如果 week 不是在 1 ≤ week ≤ maxweek 范围内的数字就失败。

  10. 如果 position 没有 超出 input 末尾,则失败。

  11. 返回星期年 year 和周号 week

2.4.5.9 时间间隔

时间间隔 由 秒数构成。

由于月和秒是不可比较的(一月没有精确的秒数, 它的长度取决于究竟从哪天算起),本标准中定义的 时间间隔 不允许包含 月(或者年,它等于12个月)。 时间间隔只能描述秒数。

表示 时间间隔 t合法的时间间隔字符串 的组成方式可以是下列任何一种:

解析时间间隔字符串 的规则如下。将会返回一个 时间间隔 或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. input 为待解析字符串。

  2. positioninput 内的指针初始指向字符串开始。

  3. monthsseconds,和 component count 均为零。

  4. M-disambiguatorminutes

    该标志的另一个值是 months。它用来消除 ISO8601 时间间隔中 "M" 单位的歧义, 在 ISO8601 中月和分钟都使用这个单位。虽然月是不允许的,但为了向前兼容, 以及避免误解 ISO8601 时间间隔(在其他上下文中仍然是合法的), 仍然对月进行了解析。

  5. position 开始 跳过 input 中的 ASCII 空格。

  6. 如果 position 越过了 input 的结尾,则失败。

  7. 如果 position 处的字符是一个 U+0050 LATIN CAPITAL LETTER P 字符, 则将 position 前进一个字符。将 M-disambiguator 设置为 months, 并从 position 开始 跳过 input 中的 ASCII 空格。

  8. while true:

    1. units 为 undefined。它的值可能是: yearsmonthsweeksdayshoursminutes,或 seconds

    2. next character 为 undefined。用来从 input 中处理字符。

    3. 如果 position 越过了 input 的结尾,则 break。

    4. 如果 position 处的字符是一个 U+0050 LATIN CAPITAL LETTER T 字符, 则将 position 前进一个字符。将 M-disambiguator 设置为 minutes, 并从 position 开始 跳过 input 中的 ASCII 空格。

    5. next character 设置为 inputposition 处的字符。

    6. 如果 next character 为一个 U+002E FULL STOP 字符 (.),则令 N 等于 0。 (不要前进 position。下面会处理它。)

      否则,如果 next character 是一个 ASCII 数字,则从 input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。将结果序列解释为 10 进制整数。令 N 为那个数字。

      否则如果 next character 不是数字,则失败。

    7. 如果 position 越过了 input 的结尾,则 break。

    8. next character 设置为 inputposition 处的字符, 这次将 position 前进到下一字符。 (如果 next character 刚才是一个 U+002E FULL STOP 字符(.),它将仍然是那个字符。)

    9. 如果 next character 是 U+002E (.),则:

      1. input 中给定的位置 position 收集 ASCII 数字 组成的代码点序列。令 day 为结果序列。

      2. 如果 s 是空字符串则失败。

      3. lengths 中的字符数。

      4. fraction 为将 s 解释为10进制数的结果, 把这个数除以 10length

      5. N 增加 fraction

      6. position 开始 跳过 input 中的 ASCII 空格。

      7. 如果 position 越过了 input 的结尾,则失败。

      8. next character 设为 inputposition 指向的字符, 并将 position 前进到下一字符。

      9. 如果 next character 既不是 U+0053 LATIN CAPITAL LETTER S 字符也不是 U+0073 LATIN SMALL LETTER S 字符,则失败。

      10. units 设为 seconds

      否则:

      1. 如果 next characterASCII 空格, 那么从 position 开始 跳过 input 中的 ASCII 空格。 将 next character 设为 inputposition 指向的字符, 并将 position 前进到下一字符。

      2. 如果 next character 是一个 U+0059 LATIN CAPITAL LETTER Y 字符或 U+0079 LATIN SMALL LETTER Y 字符,将 units 设置为 years 并将 M-disambiguator 设置为 months

        如果 next character 是一个 U+004D LATIN CAPITAL LETTER M 字符或 U+006D LATIN SMALL LETTER M 字符,且 M-disambiguatormonths,则将 units 设置为 months

        如果 next character 是一个 U+0057 LATIN CAPITAL LETTER W 或 U+0077 LATIN SMALL LETTER W 字符,将 units 设置为 weeks 并将 M-disambiguator 设置为 minutes

        如果 next character 是一个 U+0044 LATIN CAPITAL LETTER D 或 U+0064 LATIN SMALL LETTER D 字符,将 units 设置为 days 并将 M-disambiguator 设置为 minutes

        如果 next character 是一个 U+0048 LATIN CAPITAL LETTER H 或 U+0068 LATIN SMALL LETTER H 字符,将 units 设置为 hours 并将 M-disambiguator 设置为 minutes

        如果 next character 是一个 U+004D LATIN CAPITAL LETTER M 字符或 U+006D LATIN SMALL LETTER M 字符,且 M-disambiguatorminutes,则将 units 设置为 minutes

        如果 next character 是一个 U+0053 LATIN CAPITAL LETTER S 或 U+0073 LATIN SMALL LETTER S 字符,将 units 设置为 seconds 并将 M-disambiguator 设置为 minutes

        否则如果 next character 不是上述任何字符,则失败。

    10. 递增 component count

    11. multiplier 为 1。

    12. 如果 unitsyears,将 multiplier 乘以 12 并设置 unitsmonths

    13. 如果 unitsmonths,把 Nmultiplier 的乘积加到 months 上。

      否则:

      1. 如果 unitsweeks,将 multiplier 乘以 7 并设置 unitsdays

      2. 如果 unitsdays,将 multiplier 乘以 24 并设置 unitshours

      3. 如果 unitshours,将 multiplier 乘以 60 并设置 unitsminutes

      4. 如果 unitsminutes,将 multiplier 乘以 60 并设置 unitsseconds

      5. 否则 units 只能是 seconds 了。 将 Nmultiplier 的乘积加到 seconds 上。

    14. position 开始 跳过 input 中的 ASCII 空格。

  9. 如果 component count 为零,则失败。

  10. 如果 months 不为零,则失败。

  11. 返回包含 seconds 秒的 时间间隔

2.4.5.10 模糊的时间

合法的可选时间的日期字符串 是下列中的一种:


解析日期或时间字符串 的规则如下。 该算法将会返回一个 datetime,或 全球日期和时间 或者什么都不返回。 如果算法的任何一个点说它 "失败了",这意味着它在那一点退出并什么都不返回。

  1. input 为待解析字符串。

  2. positioninput 内的指针初始指向字符串开始。

  3. start position 设置为 position

  4. date presenttime present 标志设置为 true。

  5. 解析日期部分 来获得 yearmonthday。 如果它没有返回,设置 date present 为 false。

  6. 如果 date present 为 true,且 position 没有越过 input 的末尾, 且 position 处的字符是 U+0054 LATIN CAPITAL LETTER T 字符 (T)或 U+0020 SPACE 字符, 将 position 前进到 input 的下一个字符。

    否则,如果 date present 为 true,并且 position 越过了 input 的末尾或 position 处的字符既不是 U+0054 LATIN CAPITAL LETTER T 字符 (T)也不是 U+0020 SPACE 字符, 则设置 time present 为 false。

    否则,如果 date present 为 false,将 position 设置回 start position

  7. 如果 time present 为 true,则 解析时间部分 来获得 hourminutesecond。 如果它没有返回,则失败。

  8. 如果 date presenttime present 标志都是 true, 但 position 越过了 input 的末尾,则失败。

  9. 如果 date presenttime present 标志都是 true, 解析时区偏移部分 来获得 timezonehourstimezoneminutes。如果它没有返回则失败。

  10. 如果 position 没有 越过 input 的结尾,则失败。

  11. 如果 date present 标志为 true 且 time present 标志为 false, 则令 date 为年与日分别为 yearmonthday 的日期并返回 date

    否则,如果 time present 标志为 true 且 date present 标志为 false, 则令 time 为时分秒分别为 hourminutesecond 的时间并返回 time

    否则,令 timeyearmonthdayhour 时mminutesecond 秒, 减去 timezonehours 小时 timezoneminutes分钟,这一时刻是 UTC 时区的时间; 令 timezone 距离 UTC timezonehours 小时 timezoneminutes 分钟; 返回 timetimezone

2.4.6 颜色

简单颜色 由三个在 0..255 范围的 8 位数字组成。 分别表示 sRGB 色彩空间的颜色的红、绿、蓝分量。 [SRGB]

合法的简单颜色 字符串应恰好包含 7 个字符长度, 第一个字符是 U+0023 NUMBER SIGN 字符(#),剩下的 6 个都是 ASCII 十六进制数, 其中前两个表示红色分量,中间两个表示绿色分量,最后两个表示蓝色分量,均为 16 进制。

合法的小写简单颜色 字符串是 不使用任何 U+0041 LATIN CAPITAL LETTER A 到 U+0046 LATIN CAPITAL LETTER F 字符的 合法的简单颜色

解析简单色值的规则 由下列算法给出。 被调用时必须依次执行这些步骤,在第一个有返回值的步骤中止。该算法将会返回一个 简单颜色 或者错误。

  1. input 为待解析字符串。

  2. 如果 input 不是恰好 7 个字符则返回一个错误。

  3. 如果 input 的首字符不是 U+0023 NUMBER SIGN 字符(#),则返回一个错误。

  4. 如果 input 的后面 6 个字符不都是 ASCII 十六进制数字,则返回一个错误。

  5. result 为一个 简单颜色

  6. 将第2、3个字符解释为 16 进制数,令该结果为 result 的红色分量。

  7. 将第4、5个字符解释为 16 进制数,令该结果为 result 的绿色分量。

  8. 将第6、7个字符解释为 16 进制数,令该结果为 result 的蓝色分量。

  9. 返回 result

给定 简单颜色 序列化简单色值的规则 在下列算法中给出:

  1. result 为包含一个 U+0023 NUMBER SIGN 字符(#)的字符串。

  2. 将红、绿、蓝分量依次转换为两位 16 进制数字,并使用 ASCII 小写十六进制数字, 需要的话填充零。将这些数字按照红绿蓝的顺序追加到 result

  3. 返回 result,它将是一个 合法的小写简单颜色


有些废弃的遗留属性以更复杂的方式解析颜色,它们使用 解析遗留色值的规则,由以下算法给出。 被调用时必须依次执行这些步骤,在第一个有返回值的步骤中止。该算法将会返回一个 简单颜色 或者错误。

  1. input 为待解析字符串。

  2. 如果 input 位空字符串则返回一个错误。

  3. input移除前后的 ASCII 空白

  4. 如果 input ASCII 大小写不敏感地 匹配 字符串 "transparent",则返回一个错误。

  5. 如果 input ASCII 大小写不敏感地 匹配 命名颜色,则返回该关键字对应的 简单颜色[CSSCOLOR]

    没有识别 CSS2 System Colors

  6. 如果 input 是 4 个字符长度,且 input 的第一个字符是 U+0023(#), 且 input 后面的 3 个字符都是 ASCII 十六进制数字,则:

    1. result 为一个 简单颜色

    2. input 第二个字符解释为十六进制数字;令 result 的红色分量为得到的数字乘以 17。

    3. input 第三个字符解释为十六进制数字;令 result 的绿色分量为得到的数字乘以 17。

    4. input 第四个字符解释为十六进制数字;令 result 的蓝色分量为得到的数字乘以 17。

    5. 返回 result

  7. input 中任何代码点大于 U+FFFF 的字符(即任何不在基本多文种平面的字符)替换为两个字符的字符串 "00"。

  8. 如果 input 字符长度大于 128,把 input 截断到只有 128 个字符。

  9. 如果 input 中第一个字符是 U+0023 NUMBER SIGN 字符(#),移除它。

  10. input 中任何非 ASCII 十六进制数字 的字符替换为 U+0030 DIGIT ZERO(0)。

  11. While input 长度为零或者不是 3 的倍数,添加一个 U+0030 DIGIT ZERO (0)字符到 input

  12. input 分割成三个等长字符来获得三个分量。 令length 为这三个分量的长度(input 长度的三分之一)。

  13. 如果 length 大于 8,移除每个分量中前面的 length-8 个字符,并且令 length 为 8。

  14. While length 大于 2 并且每个分量的第一个字符是 U+0030 DIGIT ZERO (0)字符,移除该字符并将 length 减一。

  15. 如果 length 仍然 大于 2,截断每个分量,分别只保留前两个字符。

  16. result 为一个 简单颜色

  17. 将第一个分量解释为十六进制数字;令 result 的红色分量为得到的数字。

  18. 将第二个分量解释为十六进制数字;令 result 的绿色分量为得到的数字。

  19. 将第三个分量解释为十六进制数字;令 result 的蓝色分量为得到的数字。

  20. 返回 result


2D 图形上下文 有单独的颜色语法,还处理了不透明度。

2.4.7 空格分隔的令牌

空格分隔的令牌集合 是包含零个或更多词(称为令牌)的字符串,它们以一个或更多 ASCII 空白 分隔, 其中的词是由一个或更多的除 ASCII 空白 之外的字符组成的任何字符串。

包含 空格分隔的令牌集合 的字符串前后都可能有 ASCII 空白

空格分隔的无序不重复令牌集合 是一个没有令牌重复的 空格分隔的令牌集合

空格分隔的有序不重复令牌集合 是一个没有令牌重复但令牌顺序有意义的 空格分隔的令牌集合

空格分隔的令牌集合 有时定义有允许值的集合。 当定义了允许值的集合时,集合中的令牌必须都从那个允许的列表中来;其他值是不合规范的。 如果没有提供允许值的集合,那么所有值都是符合规范的。

set of space-separated tokens 中的令牌如何进行比较 (例如是否大小写敏感) 由各自集合定义。

2.4.8 逗号分隔的字符集

逗号分隔的字符集 is a string containing zero or more tokens each separated from the next by a single U+002C COMMA character (,), where tokens consist of any string of zero or more characters, neither beginning nor ending with ASCII whitespace, nor containing any U+002C COMMA characters (,), and optionally surrounded by ASCII whitespace.

是包含零个或多个字符的字符串,它们以一个 U+002C COMMA 字符(,)分隔,其中的字符是由一个或更多的字符组成的任意字符串,首尾不包括 ASCII 空白也不能包含 U+002C COMMA 字符(,),但前后可以有 ASCII 空白

例如字符串" a ,b,,d d "由四个字符组成:"a", "b", 空字符串和 "d d"。每个字符的前后空白不计入字符,空字符串可以是一个字符。

有时逗号分隔的字符集对合法字符的构成还有额外限制。如果定义了那些限制,字符就必须完全遵守;其他值都是不符合规范的。如果没定义其他限制,所有值都是符合规范的。

2.4.9 引用

type 类型的元素的 合法的哈希名引用 字符串由一个 U+0023 NUMBER SIGN 字符(#)和完全匹配 同一个 中的 type 元素的 name 属性的字符串构成。

给定上下文节点 scope解析对 type 类型的元素的哈希名引用的规则 如下:

  1. 如果被解析字符串不包含 U+0023 NUMBER SIGN 字符,或者第一个这样的字符是字符串的最后一个字符, 则返回 null 并中止这些步骤。

  2. s 为从紧接着第一个 U+0023 NUMBER SIGN 字符之后的字符开始,直到待解析字符串结尾的字符串。

  3. 返回 scope 中,按照 树序 的第一个 idname 属性的值是 s 的类型为 type 的元素。如果没有这样的元素就返回 null。

    虽然解析时用到了 id 属性, 但它不用于决定一个值是否是 合法的 哈希名引用。 也就是说,一个基于 id 引用元素的哈希名引用是符合性错误。 (除非那个元素也有一个具有相同值的 name 属性)。

2.4.10 媒体查询

合法的媒体查询列表 是一个匹配 Media Queries 标准中的 <media-query-list> 生成式的字符串。[MQ]

匹配用户环境 的字符串可以是空字符串、只包含 ASCII 空白 的字符串, 或者根据 Media Queries 标准给出的定义匹配用户环境的媒体查询列表。[MQ]

2.5 URL

2.5.1 术语

一个字符串如果是合法 URL 字符串,同时是非空字符串, 那么它就是 合法的非空 URL

如果 去掉前后 ASCII 空白 后是一个 合法 URL 字符串, 那么它就是一个 可能由空格包裹的合法 URL

如果 去掉前后 ASCII 空白 后是一个 合法的非空 URL, 那么它就是一个 可能由空格包裹的合法的非空 URL

本标准将 about:legacy-compat 定义为保留 URL。 因为 about: URL 不可解析,当需要兼容 XML 工具时, 用在 HTML 文档DOCTYPE 中。[ABOUT]

本标准将 about:html-kind 定义为保留 URL。 因为 about: URL 不可解析,可用于媒体轨道的类型标识。[ABOUT]

本标准将 about:srcdoc 定义为保留 URL。 因为 about: URL 不可解析, 被用于 iframe srcdoc 文档URL [ABOUT]

Document 对象 document后备基 URL 是通过执行这些步骤获得的 URL 记录

  1. 如果 document iframe srcdoc 文档, 则返回 document浏览环境容器文档文档基 URL

  2. 如果 documentURLabout:blank, 且 document浏览环境创建者的 base URL 是非空,那么返回该 创建者的 base URL

  3. 返回 documentURL

Document 对象的 文档基 URL 是通过执行这些步骤获得的 绝对 URL

  1. 如果 Document 中不存在拥有 href 属性的 base 元素,那么 文档基 URLDocument后备基 URL;中止这些步骤。

  2. 否则,文档基 URLDocument 中按照 树序 的 第一个有 href 属性的 base 元素的 冻结的基 URL

2.5.2 解析 URL

解析 URL 是从字符串中获取它表示的 URL 记录 的过程。 虽然这一过程定义在 WHATWG URL 标准中,但方便起见 HTML 标准也定义了一个包装过的版本。 [URL]

这一包装只用于出于历史原因当 URL 解析器的字符编码必须匹配文档或环境设置对象时。 除此之外可以直接使用 URL 解析器

相对于一个 documentenvironment settings object 解析 URL url, 用户代理必须使用下列步骤。 解析 URL 的结果可能是失败,也可能是 结果 URL 字符串结果 URL 记录

  1. 如果指定了 document, 令 encodingdocument字符编码, 否则令它为 environment settings objectAPI URL 字符编码

  2. 如果指定了 document, 令 baseURLdocument基 URL, 否则令它为 environment settings objectAPI 基 URL

  3. urlRecord 为 使用 baseURLencoding,在 url 上应用 URL 解析器 的结果。

  4. 如果 urlRecord 解析失败,中止这些步骤并产生一个错误。

  5. urlString 为在 urlRecord 上应用 URL 序列化 的结果。

  6. urlString 作为 结果 URL 字符串urlRecord 作为 结果 URL 记录 返回。

2.5.3 基 URL 的动态变化

当一个文档的 文档基 URL 变化时,该文档中所有元素多 受基 URL 变化的影响

当一个元素 受基 URL 变化影响 时执行下面的 基 URL 变化步骤(定义在 DOM 标准中):

如果该元素创建了 超链接

如果该超链接标识的 URL 正在展现给用户, 或任何从该 URL 来的数据正在影响显示,那么应该相对于该元素的 节点文档 重新解析 href 属性并适当地更新 UI。

例如 CSS :link/:visited 伪类 可能不受影响。

如果该超链接有 ping 属性 且它的 URL 正在展现给用户,那么应该相对于该元素的 节点文档 重新解析 ping 属性的令牌并适当地更新 UI。

如果该属性是有 cite 属性的 qblockquoteins,或 del 元素

如果 cite 属性标识的 URL 正在展现给用户, 或任何从该 URL 来的数据正在影响显示,那么应该相对于该元素的 节点文档 重新解析 href 属性并适当地更新 UI。

否则

该元素不直接受影响。

例如更改基 URL 不影响 img 元素显示的图片, 尽管脚本中后续对 src IDL 属性的访问将返回新的 绝对 URL,可能不再对应于正在显示的图片。

2.6 获取资源

2.6.1 术语

类型 为 "basic", "cors",或 "default" 的 响应 称为 CORS-same-origin[FETCH]

类型 为 "opaque" 或 "opaqueredirect" 的 响应 称为 CORS-cross-origin

响应不安全响应 是它的 内部响应(如果有的话),否则就是 响应 自己。

给定 urldestinationcorsAttributeState,以及可能有的 same-origin fallback 标志创建一个可能 CORS 的请求 应该执行以下步骤:

  1. 如果 corsAttributeStateNo CORS, 令 mode 为 "no-cors" ,否则令 mode 为 "cors"。

  2. 如果设置了 same-origin fallback 标志mode 为 "no-cors",则将 mode 设置为 "same-origin"。

  3. credentialsMode 为 "include"。

  4. 如果 corsAttributeStateAnonymous, 将 credentialsMode 设为 "same-origin"。

  5. request 为一个新的 request, 其 urlurl目标地址destination模式modecredentials 模式credentialsMode, 且设置了 use-URL-credentials 标志

2.6.2 确定响应类型

必须获取响应的 Content-Type 元数据 并按照 WHATWG MIME Sniffing 标准的要求解释。[MIMESNIFF]

必须按照 WHATWG MIME Sniffing 标准的要求找到资源的 计算后的 MIME 类型[MIMESNIFF]

嗅探图片 Content-Type 的规则 区分资源是文本还是二进制的规则,以及 嗅探音频和视频的规则 也定义在 WHATWG MIME Sniffing 标准中。 这些规则返回的结果是一个 MIME 类型[MIMESNIFF]

WHATWG MIME Sniffing 标准中的规则必须严格遵守。 当用户代理使用与服务器所期望的内容类型检测不同的启发式方法时,可能会发生安全问题。 有关更多详细信息,请参阅 WHATWG MIME Sniffing 标准。 [MIMESNIFF]

2.6.3meta 元素提取字符编码

给定字符串 s 从一个 meta 元素提起字符编码的算法 如下。 它或者返回一个字符编码,或者什么都不返回。

  1. positions 中的指针初始指向字符串开始。

  2. Loop:在 s 中找到 position 后面 ASCII 大小写不敏感地 匹配 "charset" 的前 7 个字符。 如果没有找到这样的匹配,什么都不返回并中止这些步骤。

  3. 跳过所有紧接着 "charset" 后面的 ASCII 空白(也可能没有)。

  4. 如果下一个字符不是 U+003D EQUALS SIGN (=),让 position 指向下一个字符之前, 跳回到标记为 loop 的步骤。

  5. 跳过所有紧接着等号后面的 ASCII 空白(也可能没有)。

  6. 处理下一个字符:

    如果它是一个 U+0022 QUOTATION MARK 字符(")且 s 中后面还有一个 U+0022 QUOTATION MARK 字符 (")
    如果它是一个 U+0027 APOSTROPHE 字符 (')且 s 中后面还有一个 U+0027 APOSTROPHE 字符 (')
    返回从当前字符到当前字符的下一次出现的子字符串 获取编码 的结果。
    如果它是一个没有闭合的 U+0022 QUOTATION MARK 字符 (")
    如果它是一个没有闭合的 U+0027 APOSTROPHE 字符 (')
    如果没有下一个字符
    什么都不返回。
    否则
    返回从当前字符到(不包含)第一个 ASCII 空白 或 U+003B SEMICOLON 字符(;) 或 s 的末尾(取决于哪一个先出现) 构成的子字符串中 获取编码 的结果。

该算法与 HTTP 规范中的算法不同 (例如,HTTP 不允许使用单引号,并且需要支持该算法不支持的反斜线转义机制)。 虽然在历史上本算法用于 HTTP 相关的上下文,但不同的实现支持的语法前段时间就不一样了。[HTTP]

2.6.4 CORS 设置属性

CORS 设置属性 是一个 枚举属性。下表列出了关键字以及属性状态 — 每行中第一列给出了那一行的关键字映射到的状态。

状态 关键字 简要介绍
Anonymous anonymous Requests for the element will have their mode set to "cors" and their credentials mode set to "same-origin"。
(the empty string)
使用 Credentials use-credentials 该元素的 请求 会把 模式 设置为 "cors" 把 credentials 模式 设置为 "include"。

属性的 非法值默认Anonymous 状态,它的 缺失值默认No CORS 状态。 用于 反射 时, Anonymous 状态的 标准关键字anonymous

CORS 设置属性 控制的多数请求都是通过 创建一个可能 CORS 的请求 算法来完成的。

对于更先进的特行,比如请求的 mode 总是 "cors", 某些 CORS 设置属性 用于其他语义, 不过还是只对 请求credentials 模式 起作用。 为了执行这个转换,定义了 CORS 设置属性 credentials 模式 来通过属性状态确定 CORS 设置属性

No CORS
Anonymous
"same-origin"
Use Credentials
"include"

2.6.5 引荐来源策略属性

引荐来源策略属性 是一个 枚举属性。 每个 引荐来源策略包括空字符串都是该属性的关键字, 都映射到一个同名的状态。

该属性的 非法值的默认缺失值的默认 都是空字符串状态。

这些状态对各种 获取 处理模型的影响详细地定义在 本标准中,WHATWG Fetch 标准中,以及 Referrer Policy 中。 [FETCH] [REFERRERPOLICY]

对给定的 获取 使用哪个处理模型取决于多个信号; 引荐来源策略属性只是其中之一。一般来说,这些信号的处理顺序是:

  1. 首先,是否出现一个 noreferrer 超链接类型;

  2. 然后,引荐来源策略属性 的值;

  3. 然后,是否出现任何 name 属性设为 referrermeta 元素。

  4. 最后,`Referrer-Policy` HTTP 头。

2.6.6 Nonce attributes

Global_attributes/nonce

Support in all current engines.

Firefox31+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)YesInternet ExplorerNo
Firefox Android31+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

A nonce content attribute represents a cryptographic nonce ("number used once") which can be used by Content Security Policy to determine whether or not a given fetch will be allowed to proceed. The value is text. [CSP]

Elements that have a nonce content attribute ensure that the crytographic nonce is only exposed to script (and not to side-channels like CSS attribute selectors) by taking the value from the content attribute, moving it into an internal slot named [[CryptographicNonce]], exposing it to script via the HTMLOrSVGElement interface mixin, and setting the content attribute to the empty string. Unless otherwise specified, the slot's value is the empty string.

element . nonce

Returns the value of the element's [[CryptographicNonce]] internal slot.

Can be set, to update that slot's value.

HTMLElement/nonce

Firefox75+Safari🔰 10+Chrome61+
Opera48+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS🔰 10+Chrome Android61+WebView Android61+Samsung Internet8.0+Opera Android45+

The nonce IDL attribute must, on getting, return the value of this element's [[CryptographicNonce]]; and on setting, set this element's [[CryptographicNonce]] to the given value.

Note how the setter for the nonce IDL attribute does not update the corresponding content attribute. This, as well as the below setting of the nonce content attribute to the empty string when an element becomes browsing-context connected, is meant to prevent exfiltration of the nonce value through mechanisms that can easily read content attributes, such as selectors. Learn more in issue #2369, where this behavior was introduced.

The following attribute change steps are used for the nonce content attribute:

  1. If element does not include HTMLOrSVGElement, then return.

  2. If localName is not nonce or namespace is not null, then return.

  3. If value is null, then set element's [[CryptographicNonce]] to the empty string.

  4. Otherwise, set element's [[CryptographicNonce]] to value.

Whenever an element including HTMLOrSVGElement becomes browsing-context connected, the user agent must execute the following steps on the element:

  1. Let CSP list be element's shadow-including root's CSP list.

  2. If CSP list contains a header-delivered Content Security Policy, and element has a nonce content attribute attr whose value is not the empty string, then:

    1. Let nonce be element's [[CryptographicNonce]].

    2. Set an attribute value for element using "nonce" and the empty string.

    3. Set element's [[CryptographicNonce]] to nonce.

    If element's [[CryptographicNonce]] were not restored it would be the empty string at this point.

As each Document's CSP list is append-only, user agents can optimize away the contains a header-delivered Content Security Policy check by, for example, holding a flag on the Document, set during Document creation and initialization.

The cloning steps for elements that include HTMLOrSVGElement must set the [[CryptographicNonce]] slot on the copy to the value of the slot on the element being cloned.

2.6.7 Lazy loading attributes

Lazy_loading

Support in all current engines.

Firefox75+Safari15.4+Chrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS15.4+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

A lazy loading attribute is an enumerated attribute. The following table lists the keywords and states for the attribute — the keywords in the left column map to the states in the cell in the second column on the same row as the keyword.

The attribute directs the user agent to fetch a resource immediately or to defer fetching until some conditions associated with the element are met, according to the attribute's current state.

Keyword State Description
lazy Lazy Used to defer fetching a resource until some conditions are met.
eager Eager Used to fetch a resource immediately; the default state.

The attribute's missing value default and invalid value default are both the Eager state.


The will lazy load element steps, given an element element, are as follows:

  1. If scripting is disabled for element, then return false.

    This is an anti-tracking measure, because if a user agent supported lazy loading when scripting is disabled, it would still be possible for a site to track a user's approximate scroll position throughout a session, by strategically placing images in a page's markup such that a server can track how many images are requested and when.

  2. If element's lazy loading attribute is in the Lazy state, then return true.

  3. Return false.

Each img and iframe element has associated lazy load resumption steps, initially null.

For img and iframe elements that will lazy load, these steps are run from the lazy load intersection observer's callback or when their lazy loading attribute is set to the Eager state. This causes the element to continue loading.

Each Document has a lazy load intersection observer, initially set to null but can be set to an IntersectionObserver instance.

To start intersection-observing a lazy loading element element, run these steps:

  1. Let doc be element's node document.

  2. If doc's lazy load intersection observer is null, set it to a new IntersectionObserver instance, initialized as follows:

    The intention is to use the original value of the IntersectionObserver constructor. However, we're forced to use the JavaScript-exposed constructor in this specification, until Intersection Observer exposes low-level hooks for use in specifications. See bug w3c/IntersectionObserver#427 which tracks this. [INTERSECTIONOBSERVER]

  3. Call doc's lazy load intersection observer's observe method with element as the argument.

    The intention is to use the original value of the observe method. See w3c/IntersectionObserver#427. [INTERSECTIONOBSERVER]

To stop intersection-observing a lazy loading element element, run these steps:

  1. Let doc be element's node document.

  2. Assert: doc's lazy load intersection observer is not null.

  3. Call doc's lazy load intersection observer unobserve method with element as the argument.

    The intention is to use the original value of the unobserve method. See w3c/IntersectionObserver#427. [INTERSECTIONOBSERVER]

(This is a tracking vector.) The lazy load root margin is an implementation-defined value, but with the following suggestions to consider:

It is important for privacy that the lazy load root margin not leak additional information. For example, the typical scrolling speed on the current device could be imprecise so as to not introduce a new fingerprinting vector.

2.7 通用 DOM 接口

2.7.1 在 IDL 属性中反映内容属性

定义有些 IDL 属性是为了 反映 特定的内容属性。 这意味着在获取 IDL 属性时返回的是内容属性的当前值, 在设置 IDL 属性时将内容属性更改为给定的值。

通常,当获取 IDL 属性时如果内容属性不存在,IDL 属性必须表现为该内容属性的值为空字符串; 当设置时,如果内容属性的值不存在,则必须首先添加它。

如果反映内容属性的 IDL 属性是USVString属性, 且它的内容属性定义为包含一个 URL。那么在获取时如果内容属性不存在,那么 IDL 属性必须返回空字符串。 否则,IDL 属性必须相对于元素的节点文档 解析内容属性的值,如果解析成功则返回 结果 URL 字符串。 如果解析失败,则必须将内容属性的值转换USVString 并返回。 在设置时,必须设置内容属性的值为新值。

如果反映内容属性的 IDL 属性是 DOMString属性, 且它的内容属性是 枚举属性, 且该 IDL 属性 只限于已知的一些值, 那么当获取时必须返回与属性所处状态关联的关键字值(如果有的话),或者空字符串 (如果没有关联的关键字值,或属性不在任何已定义的状态。比如属性缺失且没有 缺失默认值)。 该状态有如果有多个关键字值,则返回匹配的那个。 如果有多个匹配的关键字值,则指定一个作为 标准关键字 并选择它。 在设置时,内容属性必须设置为指定的新值。

如果反映内容属性的 IDL 属性是可为空的 DOMString 属性, 且它的内容属性是一个 枚举属性,那么当获取时, 如果对应的内容属性在 缺失默认值 状态,则 IDL 属性必须返回 null; 否则 IDL 属性必须返回属性所属状态对应的关键字值。如果有多个关键字值,返回匹配的那个。 如果有多个匹配的 If there are multiple conforming keyword values, then one will be 如果有多个匹配的关键字值,则指定一个作为 标准关键字 并选择它。 在设置时,如果新值为 null 则内容属性必须被移除;否则内容属性必须设置为指定的新值。

如果反映内容属性的 IDL 属性是 DOMStringUSVString 属性但不归于上述类别中, 那么获取和设置必须透明地,保持大小写地进行。

如果反映内容属性的 IDL 属性是 布尔 属性, 当获取该 IDL 属性时,如果设置了该内容属性则必须返回 true, 如果不存在则返回 false。当设置时,如果该 IDL 属性被设为 false 则必须移除该内容属性。 如果该 IDL 属性被设为 true 则必须将内容属性设为空字符串。 (这与布尔内容属性的规则对应。)

如果反映内容属性的 IDL 属性是有符号整数类型 (long), 那么当获取时,必须根据解析有符号整数的规则 解析内容属性,如果解析成功且值在该 IDL 属性的类型的取值范围内,则必须返回结果值。 如果解析失败或返回了范围外的值,或者该属性不存在,则必须返回默认值,如果没有默认值则返回0。 当设置时,必须将给定的值转换为可以将该数字表示为合法整数 的可能的最短字符串,然后该字符串必须被用作新的内容属性值。

如果反映内容属性的 IDL 属性是有符号整数类型 (long) 且 仅限为非负数字,那么当获取时, 该内容属性必须根据解析非负整数的规则 解析,如果解析成功且值在该 IDL 属性类型的取值范围内,必须返回结果值。 如果解析失败或返回了范围外的值,或者该属性不存在,则必须返回默认值, 如果没有默认值则返回 −1。 当设置时,如果值为负用户代理必须抛出 "IndexSizeError" DOMException。 否则必须将给定的值转换为可以将该数字表示为 合法非负整数 的可能的最短字符串, 然后该字符串必须被用作新的内容属性值。

如果反映内容属性的 IDL 属性是 无符号 整数类型 (unsigned long) ,那么当获取时,必须根据 解析非负整数的规则 解析内容属性,如果解析成功且值在 0 到 2147483647 范围内(含), 必须返回结果值。 如果解析失败或返回了范围外的值,或者该属性不存在,必须返回默认值, 如果没有默认值则返回 0。当设置时,如果新值处于 0 到 2147483647 范围内, 则令 n 为这个新值,否则令n 为默认值(如果没有默认值则为0); 然后必须将 n 转换为可将该数字表示为 合法非负整数 的可能的最短字符串,然后该字符串必须被用作新的内容属性值。

如果反映内容属性的 IDL 属性是无符号整数类型(unsigned long) 且 仅限于大于零的非负整数 ,那么行为与上一种情形类似,但零是不允许的。 当获取时,首先必须根据 解析非负整数的规则 解析内容属性, 如果解析成功且值在 1 到 2147483647 范围内(含),则必须返回结果值。 如果解析失败或返回了范围外的值,或者该属性不存在, 则必须返回默认值(没有默认值则为1)。 当设置时,如果值为0,用户代理必须抛出 "IndexSizeError" DOMException。否则, 如果新值在 1 到 2147483647 范围内,那么令 n 为这个新值。 否则令 n 为默认值( 如果没有默认值则为 1); 然后必须将n 转换为可将该数字表示为 合法非负整数 的可能的最短字符串,然后该字符串必须被用作新的内容属性值。

如果反映内容属性的 IDL 属性是无符号整数类型(unsigned long) 且 仅限于有fallback 的大于0的非负整数,则行为与前一种情形类似,但不允许的值将被转换为默认值。 当获取时, 首先必须根据解析非负整数的规则 解析内容属性,如果解析成功且值在 1 到 2147483647 范围内(含),则必须返回结果值。 如果解析失败或返回了范围外的值,或者该属性不存在,则必须返回默认值。 当设置时,如果新值在 1 到 2147483647 范围内,则令 n 为这个新值, 否则令 n 为默认值;然后必须将 n 转换为可将该数字表示为 合法非负整数 的可能的最短字符串,然后该字符串必须被用作新的内容属性值。

如果反映内容属性的 IDL 属性是固定范围 到 [min, max] 的无符号整数类型(unsigned long), 当获取时,必须先根据 解析非负整数的规则 解析内容属性,如果解析成功且值在 minmax 之间(包含), 必须返回该结果值。如果失败,必须返回默认值。如果解析成功但值小于 min,必须返回 min。 如果解析成功但值大于 max,必须返回 max。当设置时,其行为与设置普通无符号整数一样。

如果反映内容属性的 IDL 属性是浮点数类型(doubleunrestricted double),那么当获取时, 必须根据 解析浮点数值的规则 解析内容属性,如果解析成功则必须返回结果值。 如果解析失败或该属性不存在,则必须返回默认值(如果没有默认值则为0)。 当设置时, 必须将给定的值转换为 浮点数的最佳表示,然后该字符串必须被用作新的内容属性值。

如果反映内容属性的 IDL 属性是浮点数类型(doubleunrestricted double)且 仅限于大于零的数字,那么行为与上一种情形类似但不允许零和负值。当获取时,必须根据 解析浮点数值的规则解析内容属性,如果解析成功且值大于 0.0,则必须返回结果值。 否则如果解析失败或返回了范围外的值,或者该属性不存在,则必须返回默认值(如果没有默认值则为0)。 当设置时,如果新值小于等于0,那么必须忽略该值。 否则,必须将给定的值转换为 浮点数的最佳表示,然后该字符串必须被用作新的内容属性值。

当设置 Infinity 和 Not-a-Number (NaN)这些值时会抛出异常。 定义在 Web IDL 中。 [WEBIDL]

如果反映内容属性的 IDL 属性的类型为 DOMTokenList,那么当获取时, 必须返回 DOMTokenList 对象,与它关联的元素为被查询的元素, 与它关联的属性的本地名称为被查询的属性名。

如果反映内容属性的 IDL 属性为 HTMLElement 类型, 或者依赖于 HTMLElement 的接口,那么当获取时, 它必须运行下列算法(在第一个返回值的地方停机):

  1. 如果对应的内容属性不存在,那么 IDL 属性必须返回 null。
  2. candidate 为:以对应的内容属性的当前值为参数, 在内容属性的元素的 节点文档 上调用 document.getElementById() 方法将会找到的元素。
  3. 如果 candidate 是 null,或者它与 IDL 属性类型不兼容, 那么该 IDL 属性必须返回 null。
  4. 否则,它必须返回 candidate

当设置时,如果给定的元素有 id 属性, 且与被设置属性的元素有同样的 , 且给定的元素是该 ID 为该 id 属性值的第一个元素,则必须将内容属性设置为 该 id 属性的值。否则,必须设置该内容属性为空字符串。

2.7.2 集合

HTMLFormControlsCollectionHTMLOptionsCollection 接口是 从 HTMLCollection 接口派生出来的 集合HTMLAllCollection 接口是 集合, 但它不派生自 HTMLCollection

2.7.2.1 The HTMLAllCollection interface

The HTMLAllCollection interface is used for the legacy document.all attribute. It operates similarly to HTMLCollection; the main differences are that it allows a staggering variety of different (ab)uses of its methods to all end up returning something, and that it can be called as a function as an alternative to property access.

All HTMLAllCollection objects are rooted at a Document and have a filter that matches all elements, so the elements represented by the collection of an HTMLAllCollection object consist of all the descendant elements of the root Document.

Objects that implement the HTMLAllCollection interface are legacy platform objects with an additonal [[Call]] internal method described in the section below. They also have an [[IsHTMLDDA]] internal slot.

Objects that implement the HTMLAllCollection interface have several unusual behaviors, due of the fact that they have an [[IsHTMLDDA]] internal slot:

These special behaviors are motivated by a desire for compatibility with two classes of legacy content: one that uses the presence of document.all as a way to detect legacy user agents, and one that only supports those legacy user agents and uses the document.all object without testing for its presence first. [JAVASCRIPT]

[Exposed=Window,
 LegacyUnenumerableNamedProperties]
interface HTMLAllCollection {
  readonly attribute unsigned long length;
  getter Element (unsigned long index);
  getter (HTMLCollection or Element)? namedItem(DOMString name);
  (HTMLCollection or Element)? item(optional DOMString nameOrIndex);

  // Note: HTMLAllCollection objects have a custom [[Call]] internal method and an [[IsHTMLDDA]] internal slot.
};
collection . length

Returns the number of elements in the collection.

element = collection . item(index)
element = collection(index)
element = collection[index]

Returns the item with index index from the collection (determined by tree order).

element = collection . item(name)
collection = collection . item(name)
element = collection . namedItem(name)
collection = collection . namedItem(name)
element = collection(name)
collection = collection(name)
element = collection[name]
collection = collection[name]

Returns the item with ID or name name from the collection.

If there are multiple matching items, then an HTMLCollection object containing all those elements is returned.

Only button, form, iframe, input, map, meta, object, select, and textarea elements can have a name for the purpose of this method; their name is given by the value of their name attribute.

The object's supported property indices are as defined for HTMLCollection objects.

The supported property names consist of the non-empty values of all the id attributes of all the elements represented by the collection, and the non-empty values of all the name attributes of all the "all"-named elements represented by the collection, in tree order, ignoring later duplicates, with the id of an element preceding its name if it contributes both, they differ from each other, and neither is the duplicate of an earlier entry.

On getting, the length attribute must return the number of nodes represented by the collection.

The indexed property getter must return the result of getting the "all"-indexed element from this HTMLAllCollection given the passed index.

The namedItem(name) method must return the result of getting the "all"-named element(s) from this HTMLAllCollection given name.

The item(nameOrIndex) method must perform the following steps:

  1. If nameOrIndex was not provided, return null.

  2. Return the result of getting the "all"-indexed or named element(s) from this HTMLAllCollection, given nameOrIndex.


The following elements are "all"-named elements: a, button, embed, form, frame, frameset, iframe, img, input, map, meta, object, select, and textarea

To get the "all"-indexed element from an HTMLAllCollection collection given an index index, return the indexth element in collection, or null if there is no such indexth element.

To get the "all"-named element(s) from an HTMLAllCollection collection given a name name, perform the following steps:

  1. If name is the empty string, return null.

  2. Let subCollection be an HTMLCollection object rooted at the same Document as collection, whose filter matches only elements that are either:

  3. If there is exactly one element in subCollection, then return that element.

  4. Otherwise, if subCollection is empty, return null.

  5. Otherwise, return subCollection.

To get the "all"-indexed or named element(s) from an HTMLAllCollection collection given nameOrIndex:

  1. If nameOrIndex, converted to a JavaScript String value, is an array index property name, return the result of getting the "all"-indexed element from this HTMLAllCollection given the number represented by nameOrIndex.

  2. Return the result of getting the "all"-named element(s) from this HTMLAllCollection given nameOrIndex.

2.7.2.1.1 [[Call]] ( thisArgument, argumentsList )
  1. If argumentsList's size is zero, or if argumentsList[0] is undefined, return null.

  2. Let nameOrIndex be the result of converting argumentsList[0] to a DOMString.

  3. Let result be the result of getting the "all"-indexed or named element(s) from this HTMLAllCollection given nameOrIndex.

  4. Return the result of converting result to an ECMAScript value.

The thisArgument is ignored, and thus code such as Function.prototype.call.call(document.all, null, "x") will still search for elements. (document.all.call does not exist, since document.all does not inherit from Function.prototype.)

2.7.2.2 HTMLFormControlsCollection 接口

HTMLFormControlsCollection 接口用于 form 元素中 列出的元素集合

HTMLFormControlsCollection

Support in all current engines.

Firefox1+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

RadioNodeList

Support in all current engines.

Firefox33+Safari7+Chrome21+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android33+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android14+
interface HTMLFormControlsCollection : HTMLCollection {
  // inherits length and item()
  getter (RadioNodeList or Element)? namedItem(DOMString name); // shadows inherited namedItem()
};

interface RadioNodeList : NodeList {
  attribute DOMString value;
};
collection . length

返回集合中元素的数目。

element = collection . item(index)
element = collection[index]

从集合中返回下标为 index 的项目。 这些项目以 树序 排序。

element = collection . namedItem(name)

HTMLFormControlsCollection/namedItem

Support in all current engines.

Firefox33+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android33+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
radioNodeList = collection . namedItem(name)
element = collection[name]
radioNodeList = collection[name]

从集合中返回 IDnamename 的项目。

如果有多个匹配的项目,则返回一个包含所有那些元素的 RadioNodeList 对象。

radioNodeList . value [ = value ]

返回该对象表示的首个选中的单选按钮的值。

可以被设置,此时选中第一个值为该对象表示的值的单选按钮。

该对象 支持的属性下标HTMLCollection 中定义的相同。

支持的属性名该集合表示的 所有元素的所有 idname 属性的非空值组成。 这些值以 树序 排列, 忽略后面的重复项,元素的 idname 之前 (如果都存在的话),它们是互不相同的也互不为重复项。

namedItem(name) 方法必须根据下列算法操作:

  1. 如果 name 为空字符串,返回 null 并停止算法。
  2. 该方法被调用时,如果该集合中只有一个节点的 id 属性或 name 属性等于 name,则返回该节点并停止算法。
  3. 否则,如果集合中没有一个节点的 id 属性或 name 属性等于 name,则返回 null 并停止该算法。
  4. 否则,创建一个新的 RadioNodeList 对象, 表示该 HTMLFormControlsCollection 对象的一个 实时 视图, 且 RadioNodeList 对象中只包含 id 属性或 name 属性等于 name 的节点。RadioNodeList 对象中的节点必须以 树序 排序。
  5. 返回该 RadioNodeList 对象。

继承自 NodeList 接口的 RadioNodeList 接口的成员 必须与 NodeList 对象上的表现一致。

RadioNodeList/value

Support in all current engines.

Firefox33+Safari7+Chrome21+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android33+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android14+

在获取RadioNodeList 对象上的 value IDL 属性时, 必须返回运行下列步骤的返回值:

  1. elementRadioNodeList 对象表示的第一个 (树序type 属性处于 单选按钮 状态且 选中状态 为真的 input 元素。 如果这样的元素不存在,令它为 null。

  2. 如果 element 为 null,返回空字符串。

  3. 如果 element 为没有 value 属性的元素, 返回“on” 字符串。

  4. 否则返回该 元素value 属性的值。

当设置时,value IDL 属性必须执行下列步骤:

  1. 如果新的值是字符串“on”:令 elementRadioNodeList 对象表示的第一个(树序type 属性处于 单选按钮 状态且 value 内容属性缺失, 或存在且等于新的值(如果有新值的话)的 input 元素。 如果这样的元素不存在,令 element 为 null。

    除此之外:令 elementRadioNodeList 对象表示的第一个(树序type 属性处于 单选按钮 状态且 value 内容属性存在且等于新值(如果有的话) 的 input 元素。 如果这样的元素不存在,令 element 为 null。

  2. 如果 element 不是 null, 则设置它的 选中状态 为真。

2.7.2.3 HTMLOptionsCollection 接口

HTMLOptionsCollection 接口用于 option 元素的 集合。它经常以 select 元素为根, 且拥有操作其后代属性和方法。

interface HTMLOptionsCollection : HTMLCollection {
  // inherits item(), namedItem()
  [CEReactions] attribute unsigned long length; // shadows inherited length
  [CEReactions] setter void (unsigned long index, HTMLOptionElement? option);
  [CEReactions] void add((HTMLOptionElement or HTMLOptGroupElement) element, optional (HTMLElement or long)? before = null);
  [CEReactions] void remove(long index);
  attribute long selectedIndex;
};
collection . length [ = value ]

返回集合中元素的数目。

当设置为较小的数字时,截断相应容器中 option 元素的数目。

当设置为较大的数字时,在容器中新增空白的 option 元素。

element = collection . item(index)
element = collection[index]

返回集合中下标为 index 的项目。项目以 树序 排序。

collection[index] = element

index 比集合中项目的数目大时,在相应容器中新增空白 option 元素。

当设为 null 时,从集合中移除在下标 index 处的项目。

当设为一个 option 元素时,在下标 index 处新增或替换为该元素。

element = collection . namedItem(name)
element = collection[name]

从集合中返回 IDnamename 的元素。

如果有多个匹配项则返回第一个。

collection . add(element [, before ] )

before 节点前插入 element

before 参数是数字时,在该数字处的项前插入 element; 是集合中的元素时,在该元素前插入 element

如果 before 被省略或者为 null, 或者是一个溢出的数字, 就在列表尾部插入 element

如果 element 是被插入元素的祖先, 该方法将会抛出 "HierarchyRequestError" DOMException

collection . remove(index)

从集合中移除下标为 index 的元素。

collection . selectedIndex [ = value ]

返回第一个项的下标(如果有的话),否则,如果没有选中项则返回 −1。

可以被设置,来改变选中项。

该对象 支持的属性下标HTMLCollection 对象中定义的相同。

当获取时,length 属性必须返回 集合表示的 节点的数目。

当设置时,其行为取决于新的值等于、大于或小于 当时 集合表示的 节点的数目。 如果等于,则设置该属性不应做任何事情。如果大于,则必须将 n 个新的、 没有属性和子节点的 option 元素追加到 HTMLOptionsCollection 的根 select 元素上。其中 n 为这两个数字之差(新的值减去旧的值)。 同时必须触发 Mutation 事件,如同插入了包含这些 option 元素的 DocumentFragment 一样。如果新的值更小,则必须从父节点中移除集合中最后的 n 个节点,其中 n 为这两个数之差(旧的值减去新的值)。

设置 length 不会移除或增加任何 optgroup 元素,也不会给既有的 optgroup 元素增加子节点。 (虽然可以从中移除子节点)。

支持的属性名 由 所有 集合表示的 元素的 所有idname属性的非空值构成。 这些值以 树序 排列, 忽略后面的重复项,元素的 idname 之前(如果都存在的话),它们互不相同也互不为重复项。

当用户代理 设置一个新的索引属性的值设置已存在的索引属性的值 时, 设属性下标为 index,新的值为 value,它必须运行下列算法:

  1. 如果 value 为 null,以 index 为参数运行 remove 方法的步骤,并终止本步骤。

  2. length集合表示的 节点的数目。

  3. nindexlength

  4. 如果 n 大于0,则 追加 一个由 n-1 个新的、 没有属性和子元素的 option 元素组成的 DocumentFragmentHTMLOptionsCollection 所在的根 select 元素。

  5. 如果 n 大于等于0,追加 valueselect 元素。否则,以 value 替换 集合中第 index 个元素。

add(element, before) 方法必须按照下列算法执行:

  1. 如果 elementHTMLOptionsCollection 所在的根 select 元素的祖先节点,则抛出一个 "HierarchyRequestError" DOMException 并终止这些步骤。

  2. 如果 before 为一个元素,但它并非 HTMLOptionsCollection 所在的根 select 元素的后代,则抛出一个 "NotFoundError" DOMException 并终止这些步骤。

  3. 如果 elementbefore 为同一元素,则返回并终止这些步骤。

  4. 如果 before 为一个节点,那么令 reference 为该节点。 否则如果 before 为整数且集合中存在第 before 个节点,令 reference 为该节点。否则令 reference 为 null。

  5. 如果 reference 不为 null,令 parentreference 的父节点。否则令 parentHTMLOptionsCollection 所在的根 select 元素。

  6. reference之前插入 elementparent 节点中。

remove(index) 方法 必须按照下列算法执行:

  1. 如果 集合表示的 元素数目为0, 终止这些步骤。

  2. 如果 index 小于零,或小于 集合表示的 节点数目,终止这些步骤。

  3. element 为集合中第 index 个元素。

  4. element 从它的父节点移除。

selectedIndex IDL 属性必须像 HTMLOptionsCollection 所在的根 select 元素上的同名属性一样操作。

2.7.3 DOMStringList 接口

DOMStringList 接口是表示字符串列表的一种毫不时髦的复古的方式。

[Exposed=(Window,Worker)]
interface DOMStringList {
  readonly attribute unsigned long length;
  getter DOMString? item(unsigned long index);
  boolean contains(DOMString string);
};

新 API 必须使用 sequence<DOMString> 或 其他等价的接口,而不是 DOMStringList

strings . length

返回 strings 中字符串的个数。

strings[index]
strings . item(index)

返回 strings 中下标为 index 的字符串。

strings . contains(string)

如果 strings 包含 string 则返回 true,否则返回 false。

每个 DOMStringList 对象有一个与之关联的 列表

DOMStringList 对象 支持的属性下标 为 0 到关联列表的 大小 减 1。如果与它关联的列表 为空,它就没有 支持的属性下标

length 属性的读取方法必须返回 与该 DOMStringList 对象关联的列表的 大小

item(index) 方法被调用时, 必须返回该 DOMStringList 对象的关联列表中第 index 个项目, 如果 index 加一大于该 DOMStringList 对象的关联列表的 大小

contains(string) 方法被调用时,如果该 DOMStringList 对象的关联列表 包含 string,则必须返回 true, 否则必须返回 false。

2.8 安全地传递结构化数据

本节使用 JavaScript 标准的术语和排版惯例。 [JAVASCRIPT]

2.8.1 可序列化对象

可序列化对象 支持被序列化以及之后反序列化, 且这一过程与给定的 JavaScript 领域 无关。 这允许它们存储在磁盘中用于后续恢复,或者在文档和 worker 的边界上克隆 (包括不同 的文档之间, 或者不同的 事件循环 之间)。

并非所有对象都是 可序列化对象,也并不是 可克隆的对象 的所有方面都需要在序列化时保留。

平台对象 可以是 可序列化对象 只要它们实现了用 [Serializable] IDL 扩展属性 标注的接口。 这样的接口必须定义下面的算法:

序列化步骤, 接受一个 平台对象 value, 一个 记录 serialized, 和一个布尔值 forStorage

value 中的数据序列化为 serialized 字段的一系列步骤。 序列化到 serialized 中的结果数据必须独立于任何 JavaScript 领域

如果不可能序列化,这些步骤会抛出异常。

这些步骤可能会执行一个 子序列化 来序列化嵌套的数据结构。 它们不应直接调用 StructuredSerialize,因为这样做会忽略 一个重要的 memory 参数。

引入这些步骤,如果与该算法无关,则不应该提及 forStorage 参数。

反序列化步骤, 接受一个 记录 serialized 和一个 平台对象 value

serialized 中的数据反序列化的一系列步骤,用它适当地建立 valuevalue 将会是一个新创建的相应 平台对象 类型的实例, 它的内部数据还未建立;这一工作交给这些步骤:

如果不可能反序列化这些步骤会抛出一个异常。

这些步骤可能会执行一个 子反序列化 来反序列化嵌套的数据结构。 它们不能直接调用 StructuredDeserialize,一文这样做会忽略 重要的 targetRealmmemory 参数。

由平台对象的定义决定哪些数据被这些步骤序列化和反序列化。通常这些步骤是非常对称的。

[Serializable] 扩展属性不允许有任何参数, 并且不能出现任何不是接口的地方。在一个接口上它必须只出现一次。它不能用在回调接口上。 如果它出现在部分接口(partial interface)上,或者一个混入接口(mixin)上, 那么它必须也出现在原始(original)或被混入(mixed-in-to)接口上, 并且部分接口或混入提供任何的 序列化步骤反序列化步骤 应该理解为 增加到原始或被混入接口的对应步骤上。

加入我们在定义一个平台对象 Person,它与两部分数据相关联:

接着,我们使用 [Serializable] 扩展属性 标注 Person 接口,可以把 Person 实例定义为 可序列化对象,同时定义下列算法:

序列化步骤
  1. 设置 serialized.[[Name]] 为 value 关联的名字值。

  2. serializedBestFriendvalue 关联的最好朋友的值的 子序列化

  3. 设置 serialized.[[BestFriend]] 为 serializedBestFriend

反序列化步骤
  1. 设置 value 关联的名字值为 serialized.[[Name]]。

  2. deserializedBestFriendserialized.[[BestFriend]] 的 子反序列化

  3. 设置 value 关联的最好朋友值为 deserializedBestFriend

在 JavaScript 规范中定义的对象直接由 StructuredSerialize 抽象操作处理。

最初,本规范定义了“克隆对象”的概念, 可以从一个 JavaScript 领域 克隆到另一个。 但为了更好地指定某些更复杂的情况的行为,更新了模型来显示地进行序列化和反序列化。

2.8.2 可传输对象

可传输对象 支持在 事件循环 之间传输。传输其实就是有效地重新创建对象并共享对底层数据的引用,然后将被传输的对象分离。 在转让昂贵资源的所有权时很有用。并非所有对象都是 可传输对象, 也并非 可传输对象 的所有方面都会在传输时被保留。

传输是不可逆转的、不幂等的操作。对象一旦被传输就不可再次传输或使用。

平台对象 可以是 可传输对象, 只要它们实现了以 [Transferable] IDL 扩展属性 注解的接口。 这样的接口必须定义下列算法:

传输步骤, 接受一个 平台对象 value 和一个 记录 dataHolder

value 中的数据传输到 dataHolder 字段的一系列步骤。 dataHolder 中的结果数据必须独立于任何 JavaScript 领域

如果不可能传输,这些步骤会抛出异常。

接收步骤, 接收一个 记录 dataHolder 和一个 平台对象 value

接收 dataHolder 中的数据并用它适当地建立 value 的一系列步骤。 value 将会是一个新创建的相应 平台对象 类型的实例, 它的内部数据还未建立;这一工作交给这些步骤:

如果不可能接收这次传输,这些步骤会抛出异常。

由平台对象的定义决定哪些数据被这些步骤传输。通常这些步骤是非常对称的。

[Transferable] 扩展属性不允许有任何参数, 并且不能出现任何不是接口的地方。在一个接口上它必须只出现一次。它不能用在回调接口上。 如果它出现在部分接口(partial interface)上,或者一个混入接口(mixin)上, 那么它必须也出现在原始(original)或被混入(mixed-in-to)接口上, 并且部分接口或混入提供任何的 传输步骤接收步骤 应该理解为 增加到原始或被混入接口的对应步骤上。

可传输对象平台对象 有一个 [[Detached]] 内部槽。 用于确保一旦平台对象已经被传输,它不能被再次传输。

JavaScript 标准中定义的对象直接交由 StructuredSerializeWithTransfer 抽象操作处理。

2.8.3 StructuredSerializeInternal ( value, forStorage [ , memory ] )

StructuredSerializeInternal 抽象操作接受一个 JavaScript 值 value 作为输入, 把它序列化为一个 领域 无关的形式,在这里表示为一个 记录。这一序列化的形式有着后续反序列化到不同领域的新 JavaScript 值需要的所有必要信息。

这一过程可能会抛出一个异常,例如当尝试序列化不可序列化对象时。

  1. 如果没有提供 memory,令 memory 为一个空的 映射

    memory 映射是为了避免把对象序列化两次。 最终会用于保持环状结构以及标识图中的重复对象。

  2. 如果 memory[value] 存在,则 返回 memory[value]。

  3. deep 为 false。

  4. 如果 Type(value) 为 Undefined,Null,Boolean, Number,BigInt 或 String,则返回 { [[Type]]: "primitive",[[Value]]: value }。

  5. 如果 Type(value) 为 Symbol,则抛出一个 "DataCloneError" DOMException

  6. serialized 为一个未初始化的值。

  7. 如果 value 有一个 [[BooleanData]] 内部槽,则把 serialized 设置为 { [[Type]]: "Boolean",[[BooleanData]]: value.[[BooleanData]] }。

  8. 否则,如果 value 有一个 [[NumberData]] 内部槽,则把 serialized 设置为 { [[Type]]: "Number",[[NumberData]]: value.[[NumberData]] }。

  9. 否则,如果 value 有一个 [[BigIntData]] 内部槽,则把 serialized 设置为 { [[Type]]: "BigInt", [[BigIntData]]: value.[[BigIntData]] }。

  10. 否则,如果 value 有一个 [[StringData]] 内部槽,则把 serialized 设置为 { [[Type]]: "String",[[StringData]]: value.[[StringData]] }。

  11. 否则,如果 value 有一个 [[DateValue]] 内部槽,则把 serialized 设置为 { [[Type]]: "Date",[[DateValue]]: value.[[DateValue]] }。

  12. 否则,如果 value 有一个 [[RegExpMatcher]] 内部槽,则把 serialized 设置为 { [[Type]]: "RegExp",[[RegExpMatcher]]: value.[[RegExpMatcher]],[[OriginalSource]]: value.[[OriginalSource]], [[OriginalFlags]]: value.[[OriginalFlags]] }。

  13. 否则,如果 value 有一个 [[ArrayBufferData]] 内部槽,则:

    1. sizevalue.[[ArrayBufferByteLength]]。

    2. 如果 ! IsSharedArrayBuffer(value) 为 true,则:

      1. agentClustersurrounding agentagent cluster

      2. 如果 agentCluster跨域隔离 为 false,则抛出一个 "DataCloneError" DOMException

        该检查只在序列化时需要(反序列化时不需要)。因为 跨域隔离 不会随着时间改变,而且 SharedArrayBuffer 不能离开 agent cluster

      3. 如果 forStorage 为 true,则抛出一个 "DataCloneError" DOMException

      4. serialized 设置为 { [[Type]]: "SharedArrayBuffer",[[ArrayBufferData]]: value.[[ArrayBufferData]],[[ArrayBufferByteLength]]: size, [[AgentCluster]]: agentCluster }。

    3. 否则:

      1. 如果 ! IsDetachedBuffer(value) 为 true,则抛出一个 "DataCloneError" DOMException

      2. dataCopy 为 ? CreateByteDataBlock(size)。

        在分配地址失败时可能会抛出一个 RangeError 异常。

      3. 执行 ! CopyDataBlockBytes(dataCopy,0,value.[[ArrayBufferData]],0,size)。

      4. serialized 设置为 { [[Type]]: "ArrayBuffer",[[ArrayBufferData]]: dataCopy,[[ArrayBufferByteLength]]: size }。

  14. 否则,如果 value 有一个 [[ViewedArrayBuffer]] 内部槽,则:

    1. buffervalue 的 [[ViewedArrayBuffer]] 内部槽的值。

    2. bufferSerialized 为 ? StructuredSerializeInternal(buffer,forStorage, memory)。

    3. 断言: bufferSerialized.[[Type]] 是 "ArrayBuffer"。

    4. 如果 value 有一个 [[DataView]] 内部槽,则把 serialized 设置为 { [[Type]]: "ArrayBufferView",[[Constructor]]: "DataView",[[ArrayBufferSerialized]]: bufferSerialized,[[ByteLength]]: value.[[ByteLength]],[[ByteOffset]]: value.[[ByteOffset]] }。

    5. 否则:

      1. 断言: value 有一个 [[TypedArrayName]] 内部槽。

      2. serialized 设置为 { [[Type]]: "ArrayBufferView",[[Constructor]]: value.[[TypedArrayName]],[[ArrayBufferSerialized]]: bufferSerialized, [[ByteLength]]: value.[[ByteLength]],[[ByteOffset]]: value.[[ByteOffset]],[[ArrayLength]]: value.[[ArrayLength]] }。

  15. 否则,如果 value 有 [[MapData]] 内部槽,则:

    1. 设置serialized 为 { [[Type]]: "Map",[[MapData]]: 一个新的空 列表 }。

    2. 设置deep 为 true。

  16. 否则,if value 有 [[SetData]] 内部槽,则:

    1. 设置 serialized 为 { [[Type]]: "Set",[[SetData]]: 一个新的空 列表 }。

    2. 设置 deep 为 true。

  17. 否则,如果 value 有 [[ErrorData]] 内部槽且 value 不是 平台对象,那么:

    1. name 为 ? Get(value, "name")。

    2. 如果 name 不是 "Error", "EvalError", "RangeError", "ReferenceError", "SyntaxError", "TypeError" 或 "URIError",则设置 name 为 "Error"。

    3. valueMessageDesc 为 ? value.[[GetOwnProperty]]("message")。

    4. 如果 IsDataDescriptor(valueMessageDesc) 为 false, 令 message 为 undefined,否则为 ? ToString(valueMessageDesc.[[Value]])。

    5. 设置 serialized 为 { [[Type]]: "Error", [[Name]]: name, [[Message]]: message }。

    6. 用户代理应该把任何有用的还没标准化的附加数据都加到序列化表示 serialized 里,尤其是 stack 属性。

      该数据正在标准化,见 Error Stacks 提案。[JSERRORSTACKS]

  18. 否则,如果 value 是一个外来 Array 对象,那么:

    1. valueLenDescriptor 为 ? OrdinaryGetOwnProperty(value,"length")。

    2. valueLenvalueLenDescriptor.[[Value]]。

    3. 设置serialized 为 { [[Type]]: "Array",[[Length]]: valueLen, [[Properties]]: 一个新的空 列表 }。

    4. 设置deep 为 true。

  19. 否则,如果 value 是一个 可序列化的 平台对象

    1. 如果 value 有一个 [[Detached]] 内部槽且值为 true, 则抛出一个 "DataCloneError" DOMException

    2. typeStringvalue主接口 标识。

    3. 设置serialized 为 { [[Type]]: typeString }。

    4. 设置deep 为 true。

  20. 否则,如果 value 是一个 平台对象,则抛出一个 "DataCloneError" DOMException

  21. 否则,如果 IsCallable(value) 为 true,则抛出一个 "DataCloneError" DOMException

  22. 否则,如果 value 有除了 [[Prototype]] 和 [[Extensible]] 之外的任何内部槽, 则抛出一个 "DataCloneError" DOMException

    例如 [[PromiseState]] 或 [[WeakMapData]] 内部槽。

  23. 否则,如果 value 是一个外来对象且 value 不是 关联到任何 JavaScript realm%Object.prototype% intrinsic 对象, 则抛出一个 "DataCloneError" DOMException

    例如代理对象。

  24. 否则:

    1. 设置serialized 为 { [[Type]]: "Object",[[Properties]]: 一个新的空 列表 }。

    2. 设置deep 为 true。

    %Object.prototype% 最终会被本步骤或后续步骤处理。 最终结果是它的外来属性被忽略,反序列化后结果将是一个空对象(而不是 prototype 外部对象不变量)。

  25. 设置 memory[value] 为 serialized

  26. 如果 deep 为 true,则:

    1. 如果 value 有一个 [[MapData]] 内部槽,则:

      1. copiedList 为一个新的空 列表

      2. value.[[MapData]] 中的 每一个 记录 { [[Key]],[[Value]] } entry

        1. copiedEntry 为一个新的 记录 { [[Key]]: entry.[[Key]],[[Value]]: entry.[[Value]] }。

        2. 如果 copiedEntry.[[Key]] 不是特殊值 empty追加 copiedEntrycopiedList

      3. copiedList 中的 每一个 记录 { [[Key]],[[Value]] } entry

        1. serializedKey 为 ? StructuredSerializeInternal(entry.[[Key]],forStorage, memory)。

        2. serializedValue 为 ? StructuredSerializeInternal(entry.[[Value]],forStorage, memory)。

        3. 追加 { [[Key]]: serializedKey, [[Value]]: serializedValue } 到 serialized.[[MapData]]。

    2. 否则,如果 value 有一个 [[SetData]] 内部槽,则:

      1. copiedList 为一个新的空 列表

      2. value.[[SetData]] 中 每一个 entry

        1. 如果 entry 不是特殊值 empty追加 entrycopiedList

      3. copiedList每一个 entry

        1. serializedEntry 为 ? StructuredSerializeInternal(entry,forStorage, memory)。

        2. 追加 serializedEntryserialized.[[SetData]]。

    3. 否则,如果 value 是一个 可序列化的 平台对象,则给定 valueserialized,和 forStorage, 为 valueprimary interface 执行 序列化步骤

      序列化步骤 可能需要执行一个 字序列化。 该操作接受 subValue 值作为输入,返回 StructuredSerializeInternal (subValue, forStorage,memory)。 (换句话说,子序列化StructuredSerializeInternal 的与该调用一致的特化。)

    4. 否则,对 ! EnumerableOwnPropertyNames(value, key) 里的每个 key

      1. 如果 ! HasOwnProperty(value, key) 为 true,则:

        1. inputValue 为 ? value.[[Get]](key, value)。

        2. outputValue 为 ? StructuredSerializeInternal(inputValue, forStorage, memory)。

        3. 把 { [[Key]]: key, [[Value]]: outputValue } 加到 serialized.[[Properties]]。

  27. 返回 serialized

注意 StructuredSerializeInternal 产生的 记录 可能包含其他记录的 "指针",这产生了环装引用。例如当我们传递下面的 JavaScript 对象到 StructuredSerializeInternal 中时:

const o = {};
o.myself = o;

它产生了下面的结果:

{
  [[Type]]: "Object",
  [[Properties]]: «
    {
      [[Key]]: "myself",
      [[Value]]: <a pointer to this whole structure>
    }
  »
}

2.8.4 StructuredSerialize ( value )

  1. 返回 ? StructuredSerializeInternal(value, false).

2.8.5 StructuredSerializeForStorage ( value )

  1. 返回 ? StructuredSerializeInternal(value, true).

2.8.6 StructuredDeserialize ( serialized, targetRealm [ , memory ] )

StructuredDeserialize 抽象操作接受一个 记录 serialized 作为输入,它由之前的 StructuredSerializeStructuredSerializeForStorage 产生,把它反序列化到一个新的 targetRealm 中创建的 JavaScript 值。

该过程可能抛出一个异常,例如为新的对象尝试分配内存时(尤其是 ArrayBuffer 对象)。

  1. 如果没有提供 memory,令 memory 为一个空的 映射

    memory 映射是为了避免把对象反序列化两次。 最终会用于保持环状结构以及标识图中的重复对象。

  2. 如果 memory[sirialized] 存在,则 返回 memory[serialized]。

  3. deep 为 false。

  4. value 为一个未初始化的值。

  5. 否则,如果 serialized.[[Type]] 是 "primitive",则设置 valueserialized.[[Value]]。

  6. 否则,如果 serialized.[[Type]] 是 "Boolean",则设置 value 为一个 targetRealm 中的新的 Boolean 对象,其 [[BooleanData]] 内部槽值为 serialized.[[BooleanData]]。

  7. 否则,如果 serialized.[[Type]] 是 "Number",则设置 value 为一个 targetRealm 中的新的 Number 对象,其 [[NumberData]] 内部槽值为 serialized.[[NumberData]]。

  8. 否则,如果 serialized.[[Type]] 是 "BigInt",则设置 value 为一个 targetRealm 中的新的 BigInt 对象,其 [[BigIntData]] 内部槽的值为 serialized.[[BigIntData]]。

  9. 否则,如果 serialized.[[Type]] 是 "String",则设置 value 为一个 targetRealm 中的新的 String 对象,其 [[StringData]] 内部槽值为 serialized.[[StringData]]。

  10. 否则,如果 serialized.[[Type]] 是 "Date",则设置 value 为一个 targetRealm 中的新的 Date 对象,其 [[DateValue]] 内部槽值为 serialized.[[DateValue]]。

  11. 否则,如果 serialized.[[Type]] 是 "RegExp",则设置 value 为一个 targetRealm 中的新的 RegExp 对象,其 [[RegExpMatcher]] 内部槽值为 serialized.[[RegExpMatcher]],其 [[OriginalSource]] 内部槽值为 serialized.[[OriginalSource]],其 [[OriginalFlags]] 内部槽值为 serialized.[[OriginalFlags]]。

  12. 否则,如果 serialized.[[Type]] 是 "SharedArrayBuffer",则:

    1. 如果 targetRealm 对应的 agent cluster 不是 serialized.[[AgentCluster]],则抛出一个 "DataCloneError" DOMException

    2. 否则,设置 value 到一个 targetRealm 中的新的 SharedArrayBuffer 对象, 其 [[ArrayBufferData]] 内部槽值为 serialized.[[ArrayBufferData]], 其 [[ArrayBufferByteLength]] 内部槽值是 serialized.[[ArrayBufferByteLength]]。

  13. 否则,如果 serialized.[[Type]] 是 "ArrayBuffer",则设置 value 为一个 targetRealm 中新的 ArrayBuffer 对象,其 [[ArrayBufferData]] 内部槽值为 serialized.[[ArrayBufferData]],其 [[ArrayBufferByteLength]] 内部槽值为 serialized.[[ArrayBufferByteLength]]。

    如果这抛出了一个异常,则抛出一个 "DataCloneError" DOMException

    如果没有足够的内存来创建这样一个 ArrayBuffer 对象,该步骤可能会抛出异常。

  14. 否则,如果 serialized.[[Type]] 是 "ArrayBufferView",则:

    1. deserializedArrayBuffer 为 ? StructuredDeserialize(serialized.[[ArrayBufferSerialized]], targetRealm,memory)。

    2. 如果 serialized.[[Constructor]] 是 "DataView",则设置 valuetargetRealm 中的一个新的 DataView 对象,其 [[ViewedArrayBuffer]] 内部槽值为 deserializedArrayBuffer,其 [[ByteLength]] 内部槽值为 serialized.[[ByteLength]],其 [[ByteOffset]] 内部槽值为 serialized.[[ByteOffset]]。

    3. 否则,设置 value 为一个 targetRealm 中新的有类型数组对象, 使用 serialized.[[Constructor]] 给出的构造器,其 [[ViewedArrayBuffer]] 内部槽值为 deserializedArrayBuffer,其 [[TypedArrayName]] 内部槽值为 serialized.[[Constructor]],其 [[ByteLength]] 内部槽值为 serialized.[[ByteLength]],其 [[ByteOffset]] 内部槽值为 serialized.[[ByteOffset]],其 [[ArrayLength]] 内部槽值为 serialized.[[ArrayLength]]。

  15. 否则,如果 serialized.[[Type]] 是 "Map",则:

    1. 设置valuetargetRealm 中一个新的 Map 对象,其 [[MapData]] 内部槽值为一个新的空 列表

    2. 设置deep to true。

  16. 否则,如果 serialized.[[Type]] 是 "Set",则:

    1. 设置value 为一个 targetRealm 中新的设置对象,其 [[SetData]] 内部槽值为一个新的空 列表

    2. 设置deep 为 true。

  17. 否则,如果 serialized.[[Type]] 是 "Array",则:

    1. outputPrototargetRealm.[[Intrinsics]].[[%Array.prototype%]]。

    2. 设置 value 为 ! ArrayCreate(serialized.[[Length]], outputProto)。

    3. 设置deep 为 true。

  18. 否则,如果 serialized.[[Type]] 是 "Object",则:

    1. 设置valuetargetRealm 中一个新的 Object。

    2. 设置deep 为 true。

  19. 否则,如果 serialized.[[Type]] 是 "Error",则:

    1. prototype%Error.prototype%

    2. 如果 serialized.[[Name]] 是 "EvalError",则设置 prototype%EvalError.prototype%

    3. 如果 serialized.[[Name]] 是 "RangeError",则设置 prototype%RangeError.prototype%

    4. 如果 serialized.[[Name]] 是 "ReferenceError",则设置 prototype%ReferenceError.prototype%

    5. 如果 serialized.[[Name]] 是 "SyntaxError",则设置 prototype%SyntaxError.prototype%

    6. 如果 serialized.[[Name]] 是 "TypeError",则设置 prototype%TypeError.prototype%

    7. 如果 serialized.[[Name]] 是 "URIError",则设置 prototype%URIError.prototype%

    8. messageserialized.[[Message]]。

    9. 设置 value 为 ! ObjectCreate(prototype, « [[ErrorData]] »)。

    10. messageDescPropertyDescriptor{ [[Value]]: message, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }。

    11. 如果 message 不是 undefined,则执行 ! OrdinaryDefineOwnProperty(value, "message", messageDesc)。

    12. serialized 上面任何有用的附加数据都应该反序列化后再附加到value 上。

  20. 否则:

    1. interfaceNameserialized.[[Type]]。

    2. 如果 interfaceName 标识的接口没有 暴露targetRealm 中,则抛出一个 "DataCloneError" DOMException

    3. 设置value 为在 targetRealm 中创建的、 以 interfaceName 标识的接口的一个新的实例。

    4. 设置deep 为 true。

  21. 设置 memory[serialized] 为 value

  22. 如果 deep 为 true,则:

    1. 如果 serialized.[[Type]] 是 "Map",则:

      1. serialized.[[MapData]] 中的 每一个 记录 { [[Key]],[[Value]] } entry

        1. deserializedKey 为 ? StructuredDeserialize(entry.[[Key]],targetRealm, memory)。

        2. deserializedValue 为 ? StructuredDeserialize(entry.[[Value]],targetRealm, memory)。

        3. 追加 { [[Key]]: deserializedKey, [[Value]]: deserializedValue } 到 value.[[MapData]]。

    2. 否则,如果 serialized.[[Type]] 是 "Set",则:

      1. serialized.[[SetData]] 中 每一个 entry

        1. deserializedEntry 为 ? StructuredDeserialize(entry,targetRealm, memory)。

        2. 追加 deserializedEntryvalue.[[SetData]]。

    3. 否则,如果 serialized.[[Type]] 是 "Array" 或 "Object",则:

      1. serialized.[[Properties]] 中的 每一个 记录 { [[Key]],[[Value]] } entry

        1. deserializedValue 为 ? StructuredDeserialize(entry.[[Value]],targetRealm, memory)。

        2. result 为 ! CreateDataProperty(value, entry.[[Key]],deserializedValue)。

        3. 断言: result 为 true。

    4. 否则:

      1. 给定 serializedvalue,为 serialized.[[Type]] 标识的接口 执行适当的 反序列化步骤

        反序列化步骤 可能会执行一个 子反序列化。该操作接受 先前序列化后的 Record subSerialized 作为输入,返回 StructuredDeserialize(subSerialized,targetRealm, memory)。(换句话说,子反序列化 是 是 StructuredDeserialize 的与该调用一致的特化。)

  23. 返回 value

2.8.7 StructuredSerializeWithTransfer ( value, transferList )

  1. memory 为一个空的 映射

    除了它在 StructuredSerializeInternal 中的正常使用外, 在本算法中 memory 还用来确保 StructuredSerializeInternal 忽略了 transferList 中的项目,来让我们做自己的处理。

  2. transferList 中的 每一个 transferable

    1. 如果 transferable 既没有 [[ArrayBufferData]] 内部槽 又没有 [[Detached]] 内部槽,则抛出一个 "DataCloneError" DOMException

    2. 如果 transferable 有一个 [[ArrayBufferData]] 内部槽且 ! IsSharedArrayBuffer(transferable) 为 true 或 ! IsDetachedBuffer(transferable) 为 true,则抛出一个 "DataCloneError" DOMException

    3. 如果 transferable 有一个 [[Detached]] 内部槽且 transferable.[[Detached]] 为 true,则抛出一个 "DataCloneError" DOMException

    4. placeholder 为一个用户代理定义的占位对象。

    5. 设置 memory[transferable] 为 placeholder

  3. serialized 为 ? StructuredSerializeInternal(value, false,memory)。

  4. transferDataHolders 为一个新的空 列表

  5. transferList 中的 每一个 transferable

    1. placeholdermemory[transferable]。

    2. dataHolder 为一个未初始化的值。

    3. 如果 transferable 有一个 [[ArrayBufferData]] 内部槽,则:

      1. 设置dataHolder 为 { [[TransferConsumed]]: false,[[Type]]: "ArrayBuffer", [[ArrayBufferData]]: transferable.[[ArrayBufferData]],[[ArrayBufferByteLength]]: transferable.[[ArrayBufferByteLength]] }。

      2. 执行 ! DetachArrayBuffer(transferable)。

    4. 否则:

      1. 断言: transferable 是一个 可传输的 平台对象

      2. interfaceNametransferable主接口 的标识符。

      3. 设置dataHolder 为 { [[TransferConsumed]]: false,[[Type]]: interfaceName }。

      4. 指定 transferabledataHolder, 为 interfaceName 标识的接口执行适当的 传输步骤

      5. 设置transferable.[[Detached]] 为 true。

    5. serialized 中,用 dataHolder 替换所有的 placeholder 实例。

    6. 追加 dataHoldertransferDataHolders

  6. 返回 { [[Serialized]]: serialized,[[TransferDataHolders]]: transferDataHolders }。

2.8.8 StructuredDeserializeWithTransfer ( serializeWithTransferResult, targetRealm )

  1. memory 为一个空的 映射

    除了它在 StructuredDeserialize 中的正常使用外, 在本算法中 memory 还用来帮助我们确定传输值的列表。

  2. deserialized 为 ? StructuredDeserialize(serializeWithTransferResult.[[Serialized]], targetRealm,memory)。

  3. transferredValues 为一个新的空 列表

  4. serializeWithTransferResult.[[TransferDataHolders]] 中的 每一个 transferDataHolder

    1. 追加 memory[transferDataHolder] 到 transferredValues

  5. 返回 { [[Deserialized]]: deserialized,[[TransferredValues]]: transferredValues }。

2.8.9 在其他规范中执行序列化和传输

其他规范可以使用这里定义的抽象操作。下面为每个抽象操作何时比较有用提供了指导以及例子。

StructuredSerializeWithTransfer
StructuredDeserializeWithTransfer

把一个值克隆到另一个 JavaScript Realm, 带着传输列表但提前不知道目标领域。 这一情况下序列化步骤可以立即执行,反序列化步骤延迟到目标 Realm 已知的时候执行。

messagePort.postMessage() 使用这一对抽象操作,因为目标 Realm 直到 MessagePort 发出 时才知道。

StructuredSerialize
StructuredSerializeForStorage
StructuredDeserialize

为给定的值创建一个 JavaScript Realm 无关的可以保存无限时间的快照, 然后(可能很多次)具象化回 JavaScript 值。

StructuredSerializeForStorage 可以在序列化被用于持久保存值的时候 (而不是在 Realm 之间传递)使用。当尝试序列化 SharedArrayBuffer 对象时会抛出异常, 因为保存共享内存没有意义。类似地,当指定有着定制的 序列化步骤平台对象forStorage 参数为 true 时,也可能抛出异常或者有不同的行为。

history.pushState()history.replaceState() 在作者提供的状态对象上使用 StructuredSerializeForStorage,把它们存储为 会话历史入口序列化状态。 然后 history.state 属性用了 StructuredDeserialize 来返回最初提供的状态对象的一份克隆。

broadcastChannel.postMessage() 对它的输入使用了 StructuredSerialize,然后对结果多次使用了 StructuredDeserialize 来对每一个广播目标产生新的拷贝。注意在多目标情况下传输没有意义。

持久化 JavaScript 值到文件系统的 API 可能还会对它的输入使用 StructuredSerializeForStorage 并对它的输出使用 StructuredDeserialize

一般来说,调用点可能会传递 Web IDL 值而不是 JavaScript 值; 这将被理解为在调用这些算法之前执行到 JavaScript 值的隐式 转换

本规范曾经定义了“结构化克隆”算法和一个 StructuredClone 抽象操作。 然而在实践中,它的所有已知用途可以更好地通过单独的序列化和反序列化步骤来实现,所以把它删除了。


如果在任意对象上进行操作,对于非用户代码同步调用到用户代理方法的调用点必须在调用 StructuredSerializeStructuredSerializeForStorage, 或 StructuredSerializeWithTransfer 等抽象操作之前小心地 准备执行脚本 以及 准备运行 fallback。 这是必要的,因为序列化过程可能会调用作者定义的访问器作为最终的深度序列化步骤, 这些访问器调用的操作可能会依赖于 entryincumbent 的概念已经建立好。

window.postMessage() 对它的参数执行 StructuredSerializeWithTransfer 操作,但是在算法中的同步部分立即执行这一操作则需要小心。 因为可能无需 准备执行脚本准备执行 fallback 就能使用该算法。

作为对比,假设有个 API 直接通过 事件循环任务 来定期地使用 StructuredSerialize 序列化一些作者提供的对象, 可能需要事先确保它执行了适当的准备工作。现在我们还没见过平台上有这样的 API; 通常,作为作者代码的同步结果来事先执行序列化更加容易。

3 HTML 文档的语义,结构,与API

3.1 文档

HTML UA 中的每个 XML 和 HTML 文档表示为一个 Document 对象。 [DOM]

Document 对象的 URL 定义在 DOM 标准中。 It is initially set when 当创建 Document 对象时设置,但可以在 Document 的生命期内改变; 例如当用户 导航 到一个页面的一个 片段 并用一个新的 URL 调用 pushState() 方法时就会改变。[DOM]

交互式用户代理通常在其用户界面中显示 Document 对象的 URL。 这是用户用来判断当前网站是否在冒充其他网站的主要机制。

脚本 中使用 createDocument()createHTMLDocument() 创建 Document 时,Document 立即 准备好了执行加载后的任务

文档的 referrer 是一个字符串(表示一个 URL)。 可以在创建 Document 时设置,如果没有明确设置,它的值是空字符串。

3.1.1 Document 对象

DOM 定义了 Document 接口,本规范对它进行了很多扩展:

enum DocumentReadyState { "loading","interactive","complete" };
typedef (HTMLScriptElement or SVGScriptElement) HTMLOrSVGScriptElement;

[LegacyOverrideBuiltIns]
partial interface Document {
  // 资源元数据管理
  [PutForwards=href, LegacyUnforgeable] readonly attribute Location? location;
  attribute USVString domain;
  readonly attribute USVString referrer;
  attribute USVString cookie;
  readonly attribute DOMString lastModified;
  readonly attribute DocumentReadyState readyState;

  // DOM 树访问器
  getter object (DOMString name);
  [CEReactions] attribute DOMString title;
  [CEReactions] attribute DOMString dir;
  [CEReactions] attribute HTMLElement? body;
  readonly attribute HTMLHeadElement? head;
  [SameObject] readonly attribute HTMLCollection images;
  [SameObject] readonly attribute HTMLCollection embeds;
  [SameObject] readonly attribute HTMLCollection plugins;
  [SameObject] readonly attribute HTMLCollection links;
  [SameObject] readonly attribute HTMLCollection forms;
  [SameObject] readonly attribute HTMLCollection scripts;
  NodeList getElementsByName(DOMString elementName);
  readonly attribute HTMLOrSVGScriptElement? currentScript; // classic scripts in a document tree only

  // 动态标记插入
  [CEReactions] Document open(optional DOMString unused1, optional DOMString unused2); // both arguments are ignored
  WindowProxy? open(USVString url,DOMString name,DOMString features);
  [CEReactions] undefined close();
  [CEReactions] undefined write(DOMString..。 text);
  [CEReactions] undefined writeln(DOMString..。 text);

  // 用户交互
  readonly attribute WindowProxy? defaultView;
  boolean hasFocus();
  [CEReactions] attribute DOMString designMode;
  [CEReactions] boolean execCommand(DOMString commandId,optional boolean showUI = false,optional DOMString value = "");
  boolean queryCommandEnabled(DOMString commandId);
  boolean queryCommandIndeterm(DOMString commandId);
  boolean queryCommandState(DOMString commandId);
  boolean queryCommandSupported(DOMString commandId);
  DOMString queryCommandValue(DOMString commandId);

  // 只适用于 Document 对象的特殊 事件处理器 IDL 属性
  [LegacyLenientThis] attribute EventHandler onreadystatechange;

  // also has obsolete members
};
Document 实现了 GlobalEventHandlersDocument 实现了 DocumentAndElementEventHandlers

Document 有一个 引荐来源策略 (一个 引荐来源策略), 初始为空字符串,它表示由 Document 发起的 获取 的默认 引荐来源策略

Document 有一个 嵌入策略 (一个 嵌入策略))。

Document 有一个 CSP 列表,它是一个在该上下文中活动的 内容安全策略 对象的列表。 该列表在没有指定时是空的。

Document 有一个 权限策略,是一个 初始为空的 权限策略

Document 有一个 模块映射, 是一个初始为空的 模块映射

Document 有一个 跨域 opener 策略,是一个 跨域 opener 策略,初始为 "unsafe-none"。

3.1.2 The DocumentOrShadowRoot interface

DOM defines the DocumentOrShadowRoot mixin, which this specification extends.

partial interface mixin DocumentOrShadowRoot {
  readonly attribute Element? activeElement;
};

3.1.3 资源元数据管理

document . referrer

Document/referrer

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

返回用户导航到此文档的那个 DocumentURL, 除非它被阻止或没有这样的文档,这时返回空字符串。

noreferrer 链接类型可用于阻止引荐来源。

referrer 属性必须返回 该文档的引荐来源


document . cookie [ = value ]

返回适用于该 Document 的 HTTP cookie。如果没有 Cookie 或 Cookie 不适用于该资源, 则返回空字符串。

可以被设置,用来给该元素的 HTTP Cookie 集合添加一个新的 Cookie。

如果内容 被沙盒化到一个唯一的 origin 中 (例如有 sandbox 属性的 iframe), 当读取和设置时抛出 "SecurityError" DOMException

Document/cookie

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

cookie 属性表示由文档的 URL 标识的资源的 Cookie。

满足下列条件的 Document 对象为 cookie-averse 文档 对象

当读取时,如果文档是一个 cookie-averse Document 对象, 那么用户代理必须返回空字符串。否则,如果 Documentorigin 是一个 不透明 origin,用户代理必须抛出 "SecurityError" DOMException。否则,用户代理必须作为 "非HTTP" API 返回 使用 无 BOM 的 UTF-8 解码算法 解码后的, 文档 URLCookie 字符串[COOKIES]

当设置时,如果文档是一个 cookie-averse Document 对象, 则用户代理必须什么都不做。否则,如果 Documentorigin 是一个 不透明 origin,用户代理必须抛出一个 "SecurityError" DOMException。 否则用户代理的行为必须像是通过 "非HTTP" API 为文档的 URL 接收 set-cookie-string 时一样。 其中,set-cookie-string 由一个新的 UTF-8 编码的 值组成。[COOKIES] [ENCODING]

因为在 frame 之间可以访问 cookie 属性, Cookie 的路径限制只是用来帮助管理对站点的哪一部分发送哪些 Cookie 的工具,并不是任何形式的安全特性。

cookie 属性的读取方法和设定方法同步地访问共享状态。 由于没有加锁机制,在多进程用户代理中其他浏览环境可能会在脚本执行中修改 Cookie。 比如一个站点试着读取 Cookie,增加它的值然后写回去,用新的值作为会话的唯一标识; 如果该站点在不同的浏览器窗口中同时做这件事情,两个会话使用的唯一标识可能是相同的,这可能引发灾难性后果。


document . lastModified

Document/lastModified

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

根据服务器的报告返回文档的(用户的本地时区的)最后修改时间,按照这样的格式:"MM/DD/YYYY hh:mm:ss"。

如果不知道最后修改时间,返回当前时间。

当读取 lastModified 属性时, 必须返回 Document 的源文件的最后修改(在用户本地时区的)日期和时间,按照下列格式:

  1. 日期的月。
  2. 一个 U+002F SOLIDUS 字符 (/)。
  3. 日期的日。
  4. 一个 U+002F SOLIDUS 字符 (/)。
  5. 日期的年。
  6. 一个 U+0020 SPACE 字符。
  7. 时间的小时部分。
  8. 一个 U+003A COLON 字符 (:)。
  9. 时间的分钟部分。
  10. 一个 U+003A COLON 字符 (:)。
  11. 时间的秒部分。

上述除了年之外的所有数字数字组件必须以两位 ASCII 数字 的形式给出, 表示十进制数,必要时需要补零。年必须按照最短可能的字符串给出,可能是 4 个或更多的 ASCII 数字,表示十进制数,必要时需要补零。

Document 的源文件的最后修改日期和时间必须从使用的网络协议的相关特性中获取。 比如文档的 HTTP Last-Modified 头部,或者(对于本地文件)文件系统中的元数据。 如果不知道最后修改日期和时间,该属性必须按照上述格式返回当前日期和时间。


document . readyState

Document 正在加载时返回 "loading", 一旦结束解析但仍在加载子资源时返回 "interactive", 一旦加载完成返回 "complete"。

当这个值变化时触发 Document 对象上的 readystatechange 事件。

Document/readyState

Support in all current engines.

Firefox3.6+Safari1+Chrome1+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android11+

每个文档有一个 当前文档就绪状态。 创建 Document 对象时, 如果文档有关联的 HTML 解析器XML 解析器,或 XSLT 处理器, 必须将 当前文档就绪状态 设置为字符串 "loading"; 否则必须将 当前文档就绪状态 设置为字符串 "complete"。 在页面加载过程中很多算法都会影响这个值。当这个值被设置时用户代理必须 在 Document 对象上 触发 一个名为 readystatechange 的事件。

如果文档有关联的 HTML 解析器XML 解析器, 且该解析器还没有 停止中止, 那么就称该 Document 有一个 活动的解析器

当读取时,readyState IDL 属性必须返回 当前文档就绪状态

3.1.4 DOM 树访问器

如果文档是一个 html 元素, 它的 html 元素 就是它的 文档元素, 否则就是 null。


document . head

Document/head

Support in all current engines.

Firefox4+Safari5+Chrome4+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

返回 head 元素

文档的 head 元素 是它的 html 元素 的第一个 head 子元素。 如果没有这样的元素,则为 null。

当读取 head 属性时,必须返回 文档的 head 元素(一个 head 元素或 null)。


document . title [ = value ]

返回文档的标题,对于 HTML 由 title 元素 给出, 对于 SVG 由 SVG title 元素给出。

可以被设置来更新文档的标题。如果没有合适的元素来更新,新的值将被忽略。

文档的 title 元素 是文档中的第一个 title 元素(按 树序), 如果没有则为 null。

Document/title

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

当读取时,title 属性必须执行以下算法:

  1. 如果 文档元素 是一个 SVG svg 元素, 那么令 value文档元素 的第一个子 SVG title 元素的 子文本内容

  2. 否则,令 valuetitle 元素子文本内容, 如果 title 元素 是 null 则令 value 为空字符串。

  3. 移除 value 前后和多余的 ASCII 空白

  4. 返回 value

当设置时,必须执行匹配下列第一个条件的对应步骤:

如果 文档元素 是一个 SVG svg 元素
  1. 如果 文档元素 有一个 SVG title 子元素, 令 element 为第一个该元素。

  2. 否则:

    1. element 为给定 文档元素节点文档titleSVG 命名空间 创建一个元素 的结果。

    2. element 作为 第一个子元素 插入到 文档元素 中。

  3. 如同 elementtextContent IDL 属性设置为正在分配的新值一样表现。

如果 文档元素HTML 命名空间
  1. 如果 title 元素 为 null 且 the head 元素 为 null,则中止这些步骤。

  2. 如果 title 元素 不是 null,令 element 为该 title 元素

  3. 否则:

    1. element 为给定 文档元素节点文档titleHTML 命名空间 创建一个元素 的结果。

    2. element 追加head 元素 中。

  4. 如同 elementtextContent IDL 属性设置为正在分配的新值一样表现。

否则

什么都不做。


document . body [ = value ]

Document/body

Support in all current engines.

Firefox60+Safari1+Chrome1+
Opera9.6+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android60+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

返回 body 元素

被设置时替换 body 元素

如果新值不是一个 bodyframeset 元素,这将会抛出一个 "HierarchyRequestError" DOMException

文档的 body 元素html 元素 的第一个是 body 元素或 frameset 元素的子节点,没有的话就是 null。

读取 body 属性时,必须返回 文档的 body 元素(是一个 bodyframeset 元素,或者是 null)。 当设置时,必须执行以下算法:

  1. 如果新值不是一个 bodyframeset 元素则抛出一个 "HierarchyRequestError" DOMException 并中止这些步骤。
  2. 否则,如果新值与 body 元素 相同,什么都不做并中止这些步骤。
  3. 否则, 如果 body 元素 不是 null,就在 body 元素 的父元素中,把 body 元素 替换 为新值并中止这些步骤。
  4. 否则, 如果不存在 文档元素,就抛出一个 "HierarchyRequestError" DOMException 并中止这些步骤.
  5. 否则, body 元素 是 null, 但有一个 文档元素,就把新值 追加文档元素 上。

document . images

Document/images

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

返回一个 Document 中的 img 元素的 HTMLCollection

document . embeds

Document/embeds

Support in all current engines.

Firefox1+Safari10.1+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS10.3+Chrome Android64+WebView Android64+Samsung Internet9.0+Opera Android47+
document . plugins

Document/plugins

Support in all current engines.

Firefox1+Safari10.1+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS10.3+Chrome Android64+WebView Android64+Samsung Internet9.0+Opera Android47+

返回一个 Document 中的 embed 元素的 HTMLCollection

document . links

Document/links

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

返回一个 Document 中的有 href 属性的 aarea 元素的 HTMLCollection

document . forms

Document/forms

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

返回一个 Document 中的 form 元素的 HTMLCollection

document . scripts

Document/scripts

Support in all current engines.

Firefox9+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

返回一个 Document 中的 script 元素的 HTMLCollection

images 属性必须返回一个 根为 Document 节点的 HTMLCollection ,其过滤器只匹配 img 元素。

embeds 属性必须返回一个 根为 Document 节点的 HTMLCollection ,其过滤器只匹配 embed 元素。

plugins 属性必须返回 与 embeds 属性返回的相同的对象。

links 属性必须返回一个 根为 Document 节点的 HTMLCollection ,其过滤器只匹配 有 href 属性的 a 元素, 以及有 href 属性的 area 元素。

forms 属性必须返回一个 根为 Document 节点的 HTMLCollection ,其过滤器只匹配 form 元素。

scripts 属性必须返回一个 根为 Document 节点的 HTMLCollection ,其过滤器只匹配 script 元素。


collection = document . getElementsByName(name)

Document/getElementsByName

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera5+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

返回一个 Document 中的 name 属性值为 nameNodeList

getElementsByName(name) 方法接受一个字符串 name,必须返回一个 活的 NodeList, 包含该文档中 name 属性的值(大小写敏感地地)等于 name 参数 的所有 HTML 元素,按照 树序 排列。 在 Document 对象上再次使用同样的参数调用该方法时,用户代理可以返回之前调用时返回的对象。 其他情况必须返回一个新的 NodeList 对象。


document . currentScript

Document/currentScript

Support in all current engines.

Firefox4+Safari8+Chrome29+
Opera16+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android4+Safari iOS8+Chrome Android29+WebView Android4.4+Samsung Internet2.0+Opera Android16+

返回正在执行的 script 元素或 SVG script 元素, 只要该元素表示一个 经典的脚本。 对于再次进入的脚本,返回还没结束执行的脚本中最近开始执行的那个。

如果 Document 当前没有在执行 scriptSVG script (例如,因为运行的脚本是一个事件处理器或定时器),如果当前执行的 scriptSVG script 元素表示一个 module script 则返回 null。

读取 currentScript 属性时,必须返回最近设置的值。 创建 Document 时,currentScript 必须初始化为 null。

实现和标准社区已经不再青睐这一 API 因为它会全局暴露 scriptSVG script 元素。 因此它在新的环境中不再可用,比如执行 module scripts 时, 或者在 shadow tree 执行中执行脚本时。我们正在寻求一种解决方案, 在这些环境中识别正在执行的脚本,同时又不让它全局可用。参见 Issue:#1013


Document 接口 支持命名属性。 任何时候 Document 对象 document 支持的属性名 包括 (根据贡献的元素按照树序 排列,忽略后续重复项, 对同一元素从 id 属性来的值排在从 name 属性来的值前面):

为了 确定 Document 的命名属性 name 的值,用户代理返回必须执行以下算法得到的值:

  1. elements在文档树中 rootdocument, 且名为 name命名元素 列表。

    按照定义,至少会有一个这样的元素。

  2. 如果 elements 只有一个元素且该元素为 iframe 元素, 且该 iframe 元素的 嵌套浏览环境 不是 null, 则返回该元素的 嵌套浏览环境WindowProxy 对象。

  3. 否则,如果 elements 只有一个元素,返回该元素。

  4. 否则返回一个根为 Document 节点的 HTMLCollection, 其过滤器只匹配名为 name命名元素

上述算法中名为 name命名元素 包括:

如果 embedobject 元素没有 暴露的 object 祖先, 而且对于 object 元素没有显示它的 后备内容 或没有 objectembed 后代,就说它是 暴露的


Document 接口上的 dir 属性 与 dir 内容属性定义在一起。

3.2 元素

3.2.1 语义

HTML 中的元素、属性和属性值(由本规范)定义有确定的含义(语义)。 例如,ol 元素表示一个有序列表, lang 属性表示内容的语言。

这些定义允许诸如 Web 浏览器或搜索引擎的 HTML 处理器可能在作者不曾考虑过的 各种上下文中呈现和使用文档或应用。

作为一个简单的例子,考虑一个由只考虑了桌面电脑 Web 浏览器的作者编写的 Web 页面:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>My Page</title>
 </head>
 <body>
  <h1>Welcome to my page</h1>
  <p>I like cars and lorries and have a big Jeep!</p>
  <h2>Where I live</h2>
  <p>I live in a small hut on a mountain!</p>
 </body>
</html>

因为 HTML 表达了 含义,而不是呈现,同样的页面也可以用于移动电话的小浏览器而不需要改动页面。 比如在桌面浏览器中标题使用大号字体,但在移动浏览器中可能整页使用同样大小的字体,但标题使用粗体。

这不仅仅是屏幕尺寸的差异:同一页面可以通过基于语音合成的浏览器同样地被盲人使用, 这时就不是在屏幕上显示页面,而是将页面朗读给用户,比如使用耳机。 标题可能不再是大号的文本,语音浏览器可能会对它使用不同的音量或较慢的声音。

带来的好处不止于此。由于浏览器知道页面的哪些部分是标题,它们可以创建文档大纲来使得用户可以快速浏览文档, 使用“跳转到下一个标题”或“跳转到上一个标题”的快捷键。 这些功能在语音浏览器中尤其常见,不然用户可能很难快速浏览页面。

甚至除浏览器之外的软件也可以利用这些信息。 搜索引擎可以使用标题更有效地对页面进行索引,或者从结果中提供到页面子部分的快速链接。 而工具可以使用标题来创建一个目录(实际上这个规范的目录就是这样生成的)。

这个例子集中在标题上,但是相同的原则也适用于 HTML 中的所有语义。

作者不得将元素,属性或属性值用于适当的语义目的之外的其他意图,因为这样做会使软件无法正确处理页面。

例如,以下代表公司网站标题的代码片段是不合规范的, 因为第二行不是子部分的标题,而是副标题(同一部分的下级标题)。

<body>
 <h1>ACME Corporation</h1>
 <h2>The leaders in arbitrary fast delivery since 1920</h2>
 ...

hgroup 元素适用于这些情况:

<body>
 <hgroup>
  <h1>ACME Corporation</h1>
  <h2>The leaders in arbitrary fast delivery since 1920</h2>
 </hgroup>
 ...

下一个例子中的文档类似,也不合规范。尽管语法是正确的, 因为放在单元格中的数据显然不是表格数据,而且误用了 cite 元素:

<!DOCTYPE HTML>
<html lang="en-GB">
 <head> <title> Demonstration </title> </head>
 <body>
  <table>
   <tr> <td> My favourite animal is the cat. </td> </tr>
   <tr>
    <td>
     —<a href="https://example.org/~ernest/"><cite>Ernest</cite></a>,
     in an essay from 1992
    </td>
   </tr>
  </table>
 </body>
</html>

这将使得依赖于这些语义的软件出错: 例如支持盲人浏览文档中的表格的语音浏览器将把上述引用误报为表格,这会使用户困惑; 同样地,从网页中提取作品标题的工具也会将“Ernest”提取为作品的标题,即使它实际上是一个人名而不是标题。

这个文档的更正版本可能是:

<!DOCTYPE HTML>
<html lang="en-GB">
 <head> <title> Demonstration </title> </head>
 <body>
  <blockquote>
   <p> My favourite animal is the cat. </p>
  </blockquote>
  <p>
   —<a href="https://example.org/~ernest/">Ernest</a>,
   in an essay from 1992
  </p>
 </body>
</html>

作者不得使用本规范或 其他适用规范 不允许的元素,属性或属性值,因为这样做会使以后的语言扩展变得更加困难。

下一个示例中有一个不符合规范的属性值(“carpet”)和不符合规范的属性(“texture”),这是本规范不允许的:

<label>Carpet: <input type="carpet" name="c" texture="deep pile"></label>

以下是标记这一内容的正确的替代方式:

<label>Carpet: <input type="text" class="carpet" name="c" data-texture="deep pile"></label>

节点文档 不具有 浏览环境 的 DOM 节点 不受 HTML 语法 要求和 XML 语法 要求之外的所有文档一致性要求的限制。

特别地,template 元素的 模板内容节点文档 没有浏览上下文。 例如,内容模型 要求 和属性值微语法要求不适用于 template 元素的 模板内容。 在此示例中,img 元素的属性值是占位符,如果在 template 元素外就是无效的。

<template>
 <article>
  <img src="{{src}}" alt="{{alt}}">
  <h1></h1>
 </article>
</template>

但是,如果上述标记省略了 </h1> 结束标记,将会违反 HTML 语法,会被符合性检查器标记为错误。

通过脚本和使用其他机制,在用户代理处理文档时,属性值,文本以及文档的整体结构都可能会动态变化。 某一时刻文档的语义由这一时刻的文档的状态来表示,因此文档的语义会随时间变化。 当这种情况发生时,用户代理 must 更新文档的显示。

HTML 有一个表示进度条的 progress 元素。 如果其 “value” 属性由脚本动态地更新,那么 UA 将更新呈现以显示进度变化。

3.2.2 DOM 中的元素

在 DOM 中表示 HTML 元素 的节点 必须 实现本规范相关章节中的对应接口,并暴露给脚本。这包括 XML 文档 中的 HTML 元素, 即使那些文档在另外的上下文中(比如在一个 XSLT 转换中)。

DOM 中的元素 表示着 事物; 也就是说它们具有内在的 意义,也被称为语义。

例如一个 ol 元素表示一个有序列表。

元素可以被显式地或者隐式地 引用。 一种显式地引用 DOM 中元素的方式是给该元素一个 id 属性, 然后创建一个 超链接, 用那个 id 属性值作为该 超链接href 属性值的 片段。其实引用不需要超链接的存在,任何其他引用元素的方式都是足够的。

考虑下面的 figure 元素,给了它一个 id 属性:

<figure id="module-script-graph">
  <img src="module-script-graph.svg"
       alt="Module A depends on module B, which depends
            on modules C and D.">
  <figcaption>Figure 27: a simple module graph</figcaption>
</figure>

可以用 a 元素创建基于 超链接引用,像这样:

As we can see in <a href="#module-script-graph">figure 27</a>, ...

但是也有很多其他 引用 figure 元素的方式,比如:

所有 HTML 元素 的接口都继承自一个基本接口,没有额外要求的元素必须使用这一接口。这就是 HTMLElement 接口。

HTMLElement

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

HTMLUnknownElement

Support in all current engines.

Firefox1+Safari6+Chrome15+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+
[Exposed=Window,
 HTMLConstructor]
interface HTMLElement : Element {
  // 元数据属性
  [CEReactions] attribute DOMString title;
  [CEReactions] attribute DOMString lang;
  [CEReactions] attribute boolean translate;
  [CEReactions] attribute DOMString dir;
  [SameObject] readonly attribute DOMStringMap dataset;

  // 用户交互
  [CEReactions] attribute boolean hidden;
  void click();
  [CEReactions] attribute long tabIndex;
  void focus(optional FocusOptions options);
  void blur();
  [CEReactions] attribute DOMString accessKey;
  readonly attribute DOMString accessKeyLabel;
  [CEReactions] attribute boolean draggable;
  [CEReactions] attribute boolean spellcheck;
  [CEReactions] attribute DOMString autocapitalize;

  [CEReactions] attribute [TreatNullAs=EmptyString] DOMString innerText;
};

HTMLElement includes GlobalEventHandlers;
HTMLElement includes DocumentAndElementEventHandlers;
HTMLElement includes ElementContentEditable;

// 注意:有意 不是 [HTMLConstructor]
[Exposed=Window]
interface HTMLUnknownElement : HTMLElement { };

HTMLElement 接口保存着很多不同功能的方法和属性,因此该接口的成员在本规范的不同部分中描述。


HTML 命名空间 中名为 name 的元素的 元素接口 这样决定:

  1. 如果 nameappletbgsoundblinkisindexkeygenmulticolnextid, 或 spacer, 则返回 HTMLUnknownElement

  2. 如果 nameacronymbasefontbigcenternobrnoembednoframesplaintextrbrtcstrike,或 tt,则返回 HTMLElement

  3. 如果 namelistingxmp,则返回 HTMLPreElement

  4. 否则,如果本规范定义了一个 local name name 对应的 元素类型 的接口,则返回那个接口。

  5. 如果 其他适用规范name 定义了一个合适的接口, 则返回他们定义的接口。

  6. 如果 name 是一个 合法的 Custom Element 名字, 则返回HTMLElement

  7. 返回 HTMLUnknownElement

合法的 Custom Element 名 时, 使用 HTMLElement 而不是 HTMLUnknownElement 是为了确保任何将来可能的 升级 只造成元素原型链的线性转变, 从 HTMLElement 到一个子类,而不是后者从 HTMLUnknownElement 到一个不相关的子类。

HTML 和 SVG 元素共同的特性使用 HTMLOrSVGElement 接口 mixin: [SVG]

interface mixin HTMLOrSVGElement {
  [SameObject] readonly attribute DOMStringMap dataset;
  attribute DOMString nonce;

  [CEReactions] attribute long tabIndex;
  void focus(optional FocusOptions options);
  void blur();
};
HTMLElement includes HTMLOrSVGElement;
SVGElement includes HTMLOrSVGElement;

3.2.3 HTML 元素构造器

为支持 Custom Element 特性, 所有 HTML 元素都有特定的构造器行为。该行为 [HTMLConstructor] IDL 扩展属性 表示。 它指示着给定接口的接口对象将在调用时具有特定的行为,如下所述:

[HTMLConstructor] 扩展属性必须接受无参数, 不得出现在非接口的对象上。它在接口上必须只出现一次,且该接口不得以 [Constructor][NoInterfaceObject] 扩展属性标注。(但是该接口可以用 [NamedConstructor] 标注,这里没有冲突。)它不得作为回调接口使用。

[HTMLConstructor] 扩展属性标注的接口的 接口对象 必须作为相应 JavaScript 函数对象的 [[Call]] 和 [[Construct]] 调用的函数体行为运行以下步骤。从 [[Call]] 调用时,NewTarget 值未定义,因此下面的算法将立即抛出异常。 从 [[Construct]] 调用时,[[Construct]] 的 newTarget 参数提供了 NewTarget 值。

  1. registry当前全局对象CustomElementRegistry 对象。

  2. 如果 NewTarget 等于 活动的函数对象,则抛出一个 TypeError 并中止这些步骤。

    这在使用 元素接口 作为构造器定义 Custom Element 时可能发生:

    customElements.define("bad-1",HTMLButtonElement);
    new HTMLButtonElement();          // (1)
    document.createElement("bad-1");  // (2)

    在这种情形下,HTMLButtonElement(可能是显式地,比如 1,也可能是隐式地,比如 2)的执行期间, 活动的函数对象 和 NewTarget 都是 HTMLButtonElement。 如果没有这项检查,就可能会创建一个 local name 是 bad-1HTMLButtonElement 实例。

  3. definitionregistryconstructor 等于 NewTarget 的条目。 如果没有这样一个定义,则抛出一个 TypeError 并中止这些步骤。

    由于 registry 中没有 constructor 是 undefined 的条目, 这一步可以防止 HTML 元素构造器作为函数被调用(在该情况下 NewTarget 将是 undefined)。

  4. 如果 definitionlocal name 等于 definitionname (即 definition 是一个 自主的 Custom Element),则:

    1. 如果 活动的函数对象 不是 HTMLElement,则抛出一个 TypeError 并中止这些步骤。

      当 Custom Element 定义时没有扩展任何 local name 但继承了非 HTMLElement 类时就会发生这种情况:

      customElements.define("bad-2",class Bad2 extends HTMLParagraphElement {});

      这种情形下,在(隐含地)在创建 Bad2 实例的 super() 调用期间, 活动的函数对象HTMLParagraphElement 而不是 HTMLElement

  5. 否则(如果 definition 是一个 定制的内建元素):

    1. valid local name 为本规范 或 其他适用规范 中定义的 使用 活动的函数对象 作为 元素接口 的元素的 local name 列表。

    2. 如果 valid local names 不包含 definitionlocal name,则抛出一个 TypeError 并中止这些步骤。

      这在定义扩展了给定 local name 但继承了错误的类的 Custom Element 时会发生:

      customElements.define("bad-3",class Bad3 extends HTMLQuoteElement {},{ extends: "p" });

      这种情形下,在(隐含地)在创建 Bad3 实例的 super() 调用期间, valid local names 列表包含 qblockquote,但 definitionlocal namep,不在这个列表中。

  6. prototypeGet(NewTarget,"prototype")。 重新抛出任何异常。

  7. 如果 Type(prototype) 不是 Object,则:

    1. realmGetFunctionRealm(NewTarget)。

    2. 设置 prototyperealm 中 接口与 活动函数对象 的接口相同的 的 接口原型对象

    活动函数对象 的 realm 可能不是 realm,所以我们用更通用的概念 "Realms 中同样的接口" 而不寻找 相等的 接口对象。设计这个退化行为是为了匹配 JavaScript 内建对象的类似行为, 包括使用 NewTarget 的 Realm 以及在那里查找合适的原型。

  8. 如果 definition构造栈 为空,则:

    1. element 为实现了 活动函数对象 对应接口的新元素, 没有属性,命名空间设为 HTML 命名空间,local name 设为 definitionlocal name节点文档 设为 当前全局对象关联 Document

    2. 执行 element.[[SetPrototypeOf]](prototype)。重新抛出任何异常。

    3. 设置 elementCustom Element 状态 为 "custom"。

    4. 设置 elementCustom Element 定义definition

    5. 返回 element

    当作者脚本直接构建了一个新的 Custom Element 时(例如通过 new MyCustomElement()),就会发生这种情况。

  9. elementdefinition构造栈 中的最后一个条目。

  10. 如果 element 是一个 已经构造 标记, 则抛出一个 "InvalidStateError" DOMException 并中止这些步骤。

    Custom Element 构造器 中的作者代码 在调用 super() 之前 不合规范地 创建了 正在创建的类的另一个实例时,就会发生这种情况:

    let doSillyThing = false;
    
    class DontDoThis extends HTMLElement {
      constructor() {
        if (doSillyThing) {
          doSillyThing = false;
          new DontDoThis();
          // 现在构造栈将会包含一个 已经构造 标记。
        }
    
        // 这将会失败并抛出 "InvalidStateError" DOMException:
        super();
      }
    }

    Custom Element 构造器 中的作者代码 不合规范地 调用两次 super() 时也会发生。 因为根据 JavaScript 规范,这确实会在抛出异常前执行两次父类构造器(即当前这个算法):

    class DontDoThisEither extends HTMLElement {
      constructor() {
        super();
    
        // 这将会抛出异常,但这时已经调用进入了 HTMLElement 构造器
        super();
      }
    }
  11. 执行 element.[[SetPrototypeOf]](prototype)。重新抛出任何异常。

  12. definition构造栈 中的最后一个条目替换为一个 已经构造 标记

  13. 返回 element

    升级 Custom Element 时就会自然地进入这一步, 返回现有元素,以便 Custom Element 构造器 中的 super() 调用将该现有元素赋值给 this


除了 [HTMLConstructor] 隐含的构造器行为之外, 有些元素还有 命名的构造器(其实是改过 prototype 属性的工厂函数)。

当定义 Custom Element 构造器 时, HTML 元素的命名构造器也可以用于 extends 子句中:

class AutoEmbiggenedImage extends Image {
  constructor(width,height) {
    super(width * 10,height * 10);
  }
}

customElements.define("auto-embiggened",AutoEmbiggenedImage,{ extends: "img" });

const image = new AutoEmbiggenedImage(15,20);
console.assert(image.width === 150);
console.assert(image.height === 200);

3.2.4 元素定义

在本规范中的每个元素都有一个定义,包含以下信息:

类别

该元素所属的 类别 列表。 在为每个元素定义 内容模型 时用到。

可以使用该元素的上下文

该元素可以在哪里使用的 非规范化的 描述。 该信息与允许该元素为子元素的元素内容模型之间存在冗余,只是为了方便而提供。

为了简单起见,只列出最具体的元素规则。

例如,所有 短语内容 都是 流内容。 因此 短语内容 元素只会列在 "需要是 短语内容 的地方", 因为这样更具体。任何需要 流式内容 的地方也可以用 短语内容, 因为它也符合规则。

内容模型

必须包含哪些内容作为子元素和后代元素的规范性描述。

text/html 中的标签省略

非规范性的 描述:在 text/html 语法中, 是否可以忽略 开始结束 标签。 该信息与 可选标签 部分给出的规范性要求之间存在冗余, 在元素定义中提供只是为了方便。

内容属性

可以在该元素上指定的(除了不允许的情况)一个规范性的属性列表, 以及对这些属性的非规范性的描述。(破折号左侧是规范性的,右侧是非规范性的。)

可访问性考虑

对于使用方:遵循 ARIA in HTML 定义的 ARIA rolearia-* 属性的要求。 [ARIA] [ARIAHTML]

对于实现方:用户代理实现可访问性 API 语义的要求定义在 HTML Accessibility API Mappings[HTMLAAM]

DOM 接口

一个关于这样的元素必须实现的 DOM 接口的规范性的定义。

之后是更多的描述:元素所 代表 的内容, 以及可能适用于作者 和实现 的任何其他规范性的一致性标准,有时也包括实例。

3.2.4.1 属性

一个属性值是一个字符串。 除非另有说明,HTML 元素 上的属性值可以是任何字符串值, 包括空字符串,而且对这些属性值中可以指定的文本没有任何限制。

3.2.5 内容模型

本标准中定义的每个元素都有内容模型:描述了元素期望的 内容HTML 元素 的内容必须匹配元素内容模型的要求。 元素的 内容 是它在 DOM 中的子节点。

元素之间总是允许 ASCII 空白。用户代理将源码标记中元素之间的字符表示为 DOM 中的 Text 节点。 空的 Text 节点和 只包含那些字符序列的 Text 节点都被认为是 元素间空白

当决定元素内容是否匹配元素内容模型的要求时必须忽略 元素间空白, 注释节点,以及处理指令节点。 在执行定义文档和元素语义的算法时也必须忽略这些节点。

因此,元素 A 与元素 B 相邻 是指 AB 有相同的父节点且它们之间没有元素节点或 Text 节点 (元素间空白 除外)。 类似地,元素的 唯一子节点 是指其父元素只包含 元素箭空白, 注释节点,以及处理指令节点。

作者不得随意使用 HTML 元素,除非明确允许(每个元素都有定义), 或其他规范有明确要求。对于 XML 复合文档,如果这些元素定义为提供相关上下文,那么这些上下文可以位于其他命名空间的元素之内。

例如 Atom 规范定义了一个 content 元素。当它的 type 属性值为 xhtml 时,Atom 规范要求它包含单个 HTML div 元素。因此该上下文中允许出现一个a div 元素,虽然本规范没有明确地声明这一点。[ATOM]

此外,HTML 元素 可能是孤立节点(即没有父节点)。

例如创建一个 td 元素并把它存储为脚本中的全局变量是符合规范的,即使 td 元素只期望用于 tr 元素中。

var data = {
  name: "Banana",
  cell: document.createElement('td'),
};
3.2.5.1 "nothing" 内容模型

当元素的内容模型是 nothing 时, 该元素不得包含 Text 节点(元素间空白 除外) 和元素节点。

方便起见,多数内容模型为 “nothing” 的 HTML 元素同时也是 void 元素HTML 语法 中没有 结束标签 的元素)。 但是,这些是完全独立的概念。

3.2.5.2 内容的种类

HTML 中的每个元素都属于一个或多个 类别 一个类别中的元素有着相似的特点。本规范使用以下几个大类:

有些元素属于其他类别,这些类别定义在本规范的其他部分。

这些类别之间的关系如下:

章节内容,标题内容,短语内容,嵌入内容和交互式内容都是流式内容。元数据有时也是流式内容。 元数据和交互式内容有时是短语内容。嵌入内容也是短语内容,有时也是交互式内容。

有时为了特定意图也会使用其他的类别,比如为了定义通用要求,为表单控件指定了多种类别。 有些元素有独特的要求,不属于任何特定类别。

3.2.5.2.1 元数据内容

元数据内容 是设置其余内容的呈现或行为, 设置文档与其他文档的关系,传达其他“带外”信息的内容。

其语义主要与元数据相关的其他命名空间的元素(比如 RDF) 也是 元数据内容

因此在 XML 序列化中,可以像这样使用 RDF:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:r="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xml:lang="en">
 <head>
  <title>Hedral's Home Page</title>
  <r:RDF>
   <Person xmlns="http://www.w3.org/2000/10/swap/pim/contact#"
           r:about="https://hedral.example.com/#">
    <fullName>Cat Hedral</fullName>
    <mailbox r:resource="mailto:hedral@damowmow.com"/>
    <personalTitle>Sir</personalTitle>
   </Person>
  </r:RDF>
 </head>
 <body>
  <h1>My home page</h1>
  <p>I like playing with string, I guess. Sister says squirrels are fun
  too so sometimes I follow her to play with them.</p>
 </body>
</html>

然而,这在 HTML 序列化中是不可能的。

3.2.5.2.2 流式内容

多数文档和应用的 body 中的元素都归类为 流式内容

3.2.5.2.3 章节内容

章节内容 是定义了 标题页脚 范围的内容。

每个 章节内容 元素可能具有标题和 大纲。 有关详细信息请参阅 标题和章节

有些元素属于 章节根元素。 它们与 章节内容 不同,但也可以有 大纲

3.2.5.2.4 标题内容

标题内容 定义了章节的标题 (可以显式地用 章节内容 元素标记, 也可以隐式地用标题内容自己来标记)。

3.2.5.2.5 短语内容

短语内容 是文档中的文本, 以及标记该文本的段内级别的元素。 多个 短语内容 形成 段落

多数短语内容元素只能包含短语内容元素,而不是任何流式内容元素。

内容模型中的 文本内容 意味着什么都没有, 或者有 Text 节点。有时 文本内容 自身就是 一种内容模型,但它也是 短语内容, 也可以是 元素间空白 (如果 Text 节点为空或者只包含 ASCII 空白)。

Text 节点和属性值必须由 标量值 组成,不包含 非字符, 以及除 ASCII 空白 之外的 控制字符。 本规范对 Text 节点的值和属性的值,基于其确切的上下文会有额外的约束。

3.2.5.2.6 嵌入内容

嵌入内容 是指 引入其他资源的内容,或插入到文档的其他词汇表的内容。

来自除 HTML 命名空间 之外的,表达内容而不是元数据的元素, 是 嵌入内容,用于本规范定义的内容模型 (例如 MathML 或 SVG。)

有些嵌入内容元素可以包含 fallback 内容: 在不能使用外部资源时使用的内容(例如,因为它是不受支持的格式)。 如果有 fallback 内容的话,元素定义会加以说明。

3.2.5.2.7 交互式内容

交互式内容 是专门用于用户交互的内容。

tabindex 属性也可以让任何元素变成 交互式内容

3.2.5.2.8 可感知内容

作为一般规则,其内容模型允许任何 流式内容短语内容 的元素应在其 内容 中至少包含一个 可感知内容 的节点,并且它没有指定 hidden 属性。

可感知内容 通过提供一些非空的后代 文本, 可以听到(audio 元素)或看到(videoimgcanvas 元素), 或可以与之交互的内容(例如可交互的表单控件)来让一个元素变得非空。

但这个要求并不是一个硬性要求,因为有许多情况下空元素是合理的,比如当它被用作一个占位符之后用脚本填充, 或者对于模板元素,大多数页面都会填充,只有某些页面表现为空白,这也无关紧要。

推荐一致性检查工具为作者提供工具,来定位不遵守该要求的元素,帮助作者的代码编写。

下列元素是可感知内容:

3.2.5.2.9 脚本支持元素

脚本支持元素 是指那些本身不 表示 任何东西(即它们不被渲染),但是被用于支持脚本, 为用户提供功能。

下列元素是脚本支持元素:

3.2.5.3 透明内容模型

有些元素被描述为 透明的;它们的内容模型描述中有 "透明" 一词。 透明 元素的内容模型从其父元素的内容模型派生: “透明”的内容模型中某一部分所要求的元素与父元素的内容模型中对应部分所要求的元素相同。

例如,ruby 元素中的 ins 元素不可包含 rt 元素, 因为 ruby 元素的内容模型中允许 ins 元素的部分就是允许 短语内容 的那一部分, rt 元素不是 短语内容

在有些情况下,透明元素互相嵌套时,必须迭代地应用这个过程。

考虑下面的标记片段:

<p><object><param><ins><map><a href="/">Apples</a></map></ins></object></p>

为了检查 a 元素中是否允许 "Apples",要检查内容模型。 a 元素的内容模型是透明的,map 元素也是, ins 元素也是,object 元素中 ins 元素所在的部分也是。 object 元素位于 p 元素中,后者的内容模型是 短语内容。 因此 "Apples" 是允许的,因为文本是短语内容。

当透明元素秘佑父元素时,它的内容模型中透明的那一部分必须被当做可以接受任何 流式内容

3.2.5.4 段落

本小节定义的术语 段落 的用途不止是 p 元素的定义。这里定义的 段落 概念用于描述如何解释文档。 p 元素仅仅是标记 段落 的一种方式。

一个 段落 通常是由一系列 短语内容 形成的一个文本块, 在排版中可能包含一个或多个句子,讨论一个特定的主题(也可以用于更一般的专题分组)。 例如,一个地址也可以是一个段落,可以是表单的一部分,一行署名,或者一首诗中的一节。

下面的例子中,一个章节中有两段话。还有一个标题,它包含的短语内容不构成段落。 注意注释和 元素间空白 也不构成段落。

<section>
  <h1>Example of paragraphs</h1>
  This is the <em>first</em> paragraph in this example.
  <p>This is the second.</p>
  <!-- This is not a paragraph. -->
</section>

流式内容 中的段落相对于文档的样子来定义,与 ainsdel,和 map 元素造成的复杂情况无关。 因为那些元素的混合内容模型使它们可以跨越段落边界,就像下面两个例子那样。

通常来讲,最好避免让元素跨越段落边界。这样的标记很难维护。

下面的例子取自前一个例子中的标记,在某些标记处加入了 insdel 元素, 用来展示文本的变更(尽管这种情况下,这一变更确实没啥意义)。注意这个例子中的段落与上一个例子完全相同, 尽管插入了 insdel 元素 — ins 元素跨越了标题和第一个段落, del 元素跨越了两个段落的边界。

<section>
  <ins><h1>Example of paragraphs</h1>
  This is the <em>first</em> paragraph in</ins> this example<del>.
  <p>This is the second.</p></del>
  <!-- This is not a paragraph. -->
</section>

view 为 DOM 的一个视图,将文档中所有的 a, ins, del, 和 map 元素替换为它们的 内容。然后对 view 中除了接受 短语内容 还接受非 短语内容 的元素中的每一个没有被其他类型内容打断的 短语内容 节点序列, 令 first 为序列中第一个节点,令 last 为序列中最后一个节点。 对每一个上述序列中,包含至少一个非 嵌入内容元素间空白 节点的序列,在原始 DOM 中从 first 前面到 last 后面形成了一个段落。(因此段落可以横跨 a, ins, del, 和 map 元素。)

一致性检查器可以在段落相互重叠时警告作者( 在 object, video, audio, 和 canvas 元素中有可能发生这种情况, 允许再次嵌入 HTML 的其他命名空间的元素也可能间接地发生这种情况,比如 SVG svgMathML math)。

p 元素也显式地生成了 段落

p 元素可以用于包裹普通的短语内容来形成相互独立的段落。

在下面的例子中,链接横跨了半个第一个段落,分离两个段落的标题,以及半个第二个段落。它同时横跨了段落和标题。

<header>
 Welcome!
 <a href="about.html">
  This is home of...
  <h1>The Falcons!</h1>
  The Lockheed Martin multirole jet fighter aircraft!
 </a>
 This page discusses the F-16 Fighting Falcon's innermost secrets.
</header>

这是上述标记的另一种写法,这次显式地声明了段落,将一个链接分割成三部分:

<header>
 <p>Welcome! <a href="about.html">This is home of...</a></p>
 <h1><a href="about.html">The Falcons!</a></h1>
 <p><a href="about.html">The Lockheed Martin multirole jet
 fighter aircraft!</a> This page discusses the F-16 Fighting
 Falcon's innermost secrets.</p>
</header>

当使用某些元素来定义 fallback 内容时,段落可以重叠。例如下面的章节:

<section>
 <h1>My Cats</h1>
 You can play with my cat simulator.
 <object data="cats.sim">
  To see the cat simulator, use one of the following links:
  <ul>
   <li><a href="cats.sim">Download simulator file</a>
   <li><a href="https://sims.example.com/watch?v=LYds5xY4INU">Use online simulator</a>
  </ul>
  Alternatively, upgrade to the Mellblom Browser.
 </object>
 I'm quite proud of it.
</section>

共有5个段落:

  1. 第一段说:"You can play with my cat simulator. object I'm quite proud of it.",其中 objectobject 元素。
  2. 第二段说:"To see the cat simulator, use one of the following links:"。
  3. 第三段说:"Download simulator file"。
  4. 第四段说:"Use online simulator"。
  5. 第五段说:"Alternatively, upgrade to the Mellblom Browser."。

第一个段落与后面4个重叠。支持 "cats.sim" 资源的用户代理只会显示第一个段落,但显示 fallback 的用户代理就会 将第一个段落的第一句话与第二段显示为一个段落,最后一个段落会显示在第一个段落的第二个句子之前。

为避免困惑,可以显式地使用 p 元素。例如:

<section>
 <h1>My Cats</h1>
 <p>You can play with my cat simulator.</p>
 <object data="cats.sim">
  <p>To see the cat simulator, use one of the following links:</p>
  <ul>
   <li><a href="cats.sim">Download simulator file</a>
   <li><a href="https://sims.example.com/watch?v=LYds5xY4INU">Use online simulator</a>
  </ul>
  <p>Alternatively, upgrade to the Mellblom Browser.</p>
 </object>
 <p>I'm quite proud of it.</p>
</section>

3.2.6 全局属性

下列属性是通用的,所有 HTML 元素 都可以指定。 (即使是本规范中没有定义的那些元素):

本规范定义的这些属性只用于 HTML 元素 的属性。 当本规范引用具有这些属性的元素时, 没有定义这些属性的命名空间下的元素不得当作具有这些属性的元素处理。

例如,在下面的 XML 片段中,根据本标准的定义 "bogus" 元素没有 dir 属性,尽管它字面上有一个名为 "dir" 的属性。因此,最里面的 span 元素的 方向 是 'rtl', 通过 "bogus" 元素间接地继承自 div 元素。

<div xmlns="http://www.w3.org/1999/xhtml" dir="rtl">
 <bogus xmlns="https://example.net/ns" dir="ltr">
  <span xmlns="http://www.w3.org/1999/xhtml">
  </span>
 </bogus>
</div>

Global_attributes/slot

Support in all current engines.

Firefox63+Safari10+Chrome53+
Opera40+Edge79+
Edge (Legacy)NoInternet Explorer?
Firefox Android63+Safari iOS10+Chrome Android53+WebView Android53+Samsung Internet6.0+Opera Android41+

WHATWG DOM 标准为任何命名空间下的任何元素的 classid,和 slot 属性定义了用户代理的要求。[DOM]

classid,和 slot 属性可以在任何 HTML 元素 上指定。

HTML 元素 上指定了 class 属性时,该属性的值必须是 一组空格分隔的令牌, 表示该元素所属的各种类。

设置元素的类会影响 CSS 选择符的匹配,DOM 的 getElementsByClassName() 方法, 以及其他这类特性。

作者在 class 属性中可以使用的令牌没有额外的限制, 但鼓励作者使用描述内容本质的取值,而不是描述内容表示的取值。

HTML 元素 上指定了 id 属性时, 该属性的值必须在该元素所在的 的所有 IDs 中是唯一的, 必须至少包含一个字符,且不得包含任何 ASCII 空白

id 属性指定了该元素的 唯一标识符(ID)

对 ID 的形式没有其他限制;ID 甚至可以只包含数字,以数字起始,以下划线起始,或者只包含标点等等。

元素的 唯一标识符 有很多用途, 最值得一提的是通过 URL 片段 链接到文档的特定部分, 在脚本中指向元素的一种方式,以及从 CSS 中指定特定元素的样式。

标识符是不透明的字符串。不得通过 id 属性的值来推断特定的含义。

HTML 元素slot 属性没有符合性要求。

slot 属性用于为元素 设置一个槽:具有 slot 属性的元素会被 指定到 name 属性值匹配该 slot 属性值的 slot 元素创建的 slot 中。 — 但条件是 slot 元素所在的 shadow treeroothost 有相应的 slot 属性值。


为了使辅助技术产品提供相比于 HTML 元素和属性更加细粒度的界面,有一组 用于辅助技术产品的注解 可以指定 (ARIA rolearia-* 属性)。[ARIA]


下面的 事件处理器内容属性 可以在任何 HTML 元素 上指定:

用星号标记的属性在用于 body 元素时有不同的含义, 因为该元素暴露了 Window 对象上同名的 事件处理器

虽然这些属性适用于所有元素,但并不是对所有元素都有用。 例如,只有 媒体元素 才会接收到用户代理触发的 音量变化 事件。


任何 HTML 元素 都可以指定 自定义数据属性 (例如 data-foldernamedata-msgid), 用于存储页面相关的自定义数据,状态,注解这样的东西。


HTML 文档 中,HTML 命名空间 中的元素可以指定一个 xmlns 属性,但它的值只能是 "http://www.w3.org/1999/xhtml" 。这不适用于 XML 文档

在 HTML 中,xmlns 属性完全没有效果,它只是一个标志。 它的存在只是为了方便 XML 与 HTML 之间的迁移。 被 HTML 解析器 解析时,该属性的结果是没有命名空间, 而不是像 XML 中的命名空间声明那样,解析为 "http://www.w3.org/2000/xmlns/" 命名空间。

在 XML 中,xmlns 属性是命名空间机制的一部分, 没有指定命名空间时,元素不能有 xmlns 属性。


XML 文档 中的任何元素上,XML 也遵循 XML 命名空间 中的 xml:space 属性的使用。 该属性在 HTML 元素 上没有作用,因为 HTML 的默认行为就是保留空白。 [XML]

text/html 语法中,无法序列化 HTML 元素xml:space 属性。

3.2.6.1 title 属性

title 属性 表示 元素的建议信息,比如适用于工具提示。 在链接上,这可能是目标资源的标题或描述;在图片上,它可以是图片来源或图片的描述; 在段落上,它可能是文本的脚注或评论;在引用上,可以是来源的进一步信息; 在 交互式内容 上,它可能是元素的标签或使用说明; 等等。值为文本。

目前不鼓励依赖于 title 属性, 因为许多用户代理不按照本规范中要求的可访问的方式来暴露该属性 (例如,要求像鼠标这样的定点设备来触发工具提示,这排除了纯键盘用户和触摸设备用户,比如手机或平板电脑的用户)。

如果从元素中省略此属性,则默认关联到离该元素最近的设置了 title 属性的 祖先 HTML 元素。 设置该属性可以覆盖这一行为,显式地声明了任何祖先的建议信息与此元素无关。 将属性设置为空字符串表示该元素没有建议信息。

如果 title 属性值包含 U+000A LINE FEED (LF)字符, 其内容将被分割为多行。每个 U+000A LINE FEED (LF) 字符表示一个换行。

title 属性中使用换行要多加小心。

比如下面的代码片段其实定义了一个缩写的解释,其中包含一个换行

<p>My logs show that there was some interest in <abbr title="Hypertext
Transport Protocol">HTTP</abbr> today.</p>

有些元素比如 linkabbr,和 inputtitle 属性定义了额外的语义。

元素的 建议信息 是下面算法的返回值, 只要有值返回算法就中止。当该算法返回空字符串时,没有任何建议信息。

  1. 如果该元素是一个 linkstyledfn,或 abbr 元素,那么:如果该元素有 title 属性, 返回该属性的值,否则返回空字符串。

  2. 否则,如果该元素有一个 title 属性则返回它的值。

  3. 否则,如果该属性有父元素,则返回父元素的 建议信息

  4. 否则,返回空字符串。

当元素有 建议信息 时, 用户代理应该通知用户,不然就无法发现该信息。


HTMLElement/title

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

title IDL 属性必须 反映 title 内容属性。

3.2.6.2 langxml:lang 属性

Global_attributes/lang

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

lang 属性(没有命名空间)指定了该元素内容, 以及该元素包含文本的属性的主要语言。它的值必须是一个合法的 BCP 47 语言标签, 或者空字符串。将该属性设置为控制付出表示主要语言是未知的。 [BCP47]

XML 命名空间 中的 lang 属性 定义在 XML 中。 [XML]

如果元素省略了这些属性,该元素的语言就是其父元素的语言(如果有的话)。

没有命名空间的 lang 属性可以用于任何 HTML 元素

XML 命名空间 中的 lang 属性 可以用于 XML 文档 中的 HTML 元素, 也可以用户其他命名空间中的元素,只要相关规范允许(特别低, MathML 和 SVG 允许其元素上指定 XML 命名空间 中的lang 属性 )。如果同时在同一个元素上指定了 无命名空间的 lang 属性,和 XML 命名空间 中的 lang 属性, 它们必须有 ASCII 大小写不敏感的 同样的值。

作者不得在 HTML 文档 中的 HTML 元素 上使用 XML 命名空间 中的 lang 属性。 为了便于与 XML 之间迁移,作者可以在 HTML 文档 中的 HTML 元素 上 指定一个没有命名空间的,没有前缀的属性,其 localname 为 "xml:lang", 但指定该属性时必须同时指定一个无命名空间的 lang 属性, 它们必须有 ASCII 大小写不敏感的 同样的值。

没有命名空间没有前缀的 localname 是 "xml:lang" 的属性对语言处理没有任何影响。


确定节点的 language,用户代理必须寻找设置了 XML 命名空间 中的 lang 属性 或无命名空间的 lang 属性的, 最近的祖先元素(包括该元素自身,如果该节点是元素的话)。 该属性指定了节点的语言(不管它的值是什么)。

如果同时在同一个元素上指定了 无命名空间的 lang 属性,和 XML 命名空间 中的 lang 属性, 在确定元素的语言时,用户代理必须使用 XML 命名空间 中的 lang 属性, 必须 忽略 无命名空间的 lang 属性。

如果节点的 包括自身在内的祖先 两个属性都没设置, 但是设置了一个 编译指示的默认语言,那么这就是该节点的语言。 如果没有设置 编译指示的默认语言, 那么必须使用上级协议(比如 HTTP)的语言信息(如果有的话)作为最终的 fallback 语言。 如果没有该语言信息,或者上级协议报告了多种语言,该节点的语言就是未知的,对应的语言标签是空字符串。

如果结果值不是可识别的的语言标签,那么它必须被视为具有给定语言标签的未知语言,区别于所有其他语言。 为了与预期该语言标签的其他服务进行往返或通信,用户代理应通过未修改的方式传递未知语言标签, 并将其标记为 BCP 47 语言标签,以防后续服务将数据解释为另一种语言描述。 [BCP47]

因此,例如具有 lang="xyzzy" 的元素将被选择器 :lang(xyzzy) 匹配(例如在 CSS 中), 但是它不会被 :lang(abcde) 匹配,虽然两者都是无效的。 类似地,如果要 Web 浏览器和屏幕阅读器一致地传达关于元素的语言, 则浏览器将告诉屏幕阅读器该语言是 “xyzzy”,即使它知道这个语言是无效的, 以防屏幕阅读器实际上支持该标签的语言。即使屏幕阅读器支持 BCP 47 和用于编码语言名称的另一语法, 比如在这一语法中字符串 “xyzzy” 表示白俄罗斯语言,那么屏幕阅读器将会 错误地 把文本当做白俄罗斯语言处理, 因为 “xyzzy” 不是 BCP 47 规范中描述的白俄罗斯语言(BCP 47 使用 “be” 表示白俄罗斯语言)。

如果结果值是空字符串,那么必须把它解释为该节点的语言显式地声明为未知。


用户代理可以使用元素的语言来决定适当的处理和渲染(例如选择合适的字体和标点, 选择合适的字典,或者用于表单控件的 UI 比如日期选择器)。


HTMLElement/lang

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

lang IDL 属性必须 反映 无命名空间的 lang 内容属性。

3.2.6.3 translate 属性

Global_attributes/translate

FirefoxNoSafari6+Chrome19+
Opera15+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS6+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android14+

translate 属性是一个 枚举属性,用于指定元素在本地化时应该翻译其属性值和 Text 子节点的值,还是让它们保持不变。

该属性的关键字是空字符串,yes,和 no。 空字符串和 yes 关键字映射为 yes 状态。 no 关键字映射为 no 状态。 此外还有第三种状态,inherit 状态,这是 缺失值默认 (以及 非法值默认)。

每个元素(甚至非 HTML 元素)都有 翻译模式,处于 启用翻译 状态或者 不翻译 状态。 如果 HTML 元素translate 属性处于 yes 状态,那么该元素的 翻译模式 处于 启用翻译 状态;否则该元素的 translate 属性处于 no 状态,那么该元素的 翻译模式 处于 不翻译 状态。 否则,元素的 translate 属性处于 inherit 状态,或者该元素不是 HTML 元素 因此没有 translate 属性;任何一种情况下该元素的 翻译模式 都将与其父元素处于同样的状态(如果有父元素的话), 否则该元素是一个 文档元素,则处于 启用翻译 状态。

当元素处于 启用翻译 状态时,该元素的 可翻译的属性 及其 Text 子节点的值将会在页面本地化时进行翻译。

当元素处于 不翻译 状态时,该元素的属性值及其 Text 子节点的值将会在页面本地化时保留原样。例如因为该元素包含人名或者计算机程序名。

下面的属性是 可翻译属性

其他规范可能会定义其他 可翻译的属性。例如 ARIA 可能会把 aria-label 属性定义为可翻译的。


在读取时,translate IDL 属性必须返回 true 如果元素的 翻译模式启用翻译; 否则返回 false。当设置时,它必须设置该内容属性的值为 "yes" 如果新值为 true; 否则设置该内容属性的值为 "no"。

在这个例子中,在本地化时文档中的所有东西都会被翻译,除了示例键盘输入和示例程序输出:

<!DOCTYPE HTML>
<html lang=en> <!-- default on the document element is translate=yes -->
 <head>
  <title>The Bee Game</title> <!-- implied translate=yes inherited from ancestors -->
 </head>
 <body>
  <p>The Bee Game is a text adventure game in English.</p>
  <p>When the game launches,the first thing you should do is type
  <kbd translate=no>eat honey</kbd>。 The game will respond with:</p>
  <pre><samp translate=no>Yum yum! That was some good honey!</samp></pre>
 </body>
</html>
3.2.6.4 dir 属性

dir 属性指定了元素的文本方向。 该属性是一个 枚举属性 关键字和状态如下:

ltr 关键字,映射到 ltr 状态

表示该元素的内容是明确的独立方向隔离的从左到右的文本。

rtl 关键字,映射到 rtl 状态

表示该元素的内容是明确的独立方向隔离的从右到左的文本。

auto 关键字,映射到 auto 状态

表示该元素的内容是明确的方向隔离的文本,但其方向需要通过元素的内容以编程方式确定(描述如下)。

这种状态使用的启发式是非常粗糙的(类似于双向算法中的段落级别确定,查看第一个具有较强方向性的字符)。 强烈建议作者只有在文本的方向是未知,并且服务器端没有更好的启发式算法的情况下才使用该值作为最后的手段。 [BIDI]

对于 textareapre 元素,该启发式算法按段落级别生效。

该属性没有 非法值默认缺失值默认


元素(任意元素,不仅是 HTML 元素)的 方向 或者是 'ltr',或者是'rtl', 由下列列表中第一个适用的步骤确定:

如果该元素的 dir 属性处于 ltr 状态
如果该元素是一个 文档元素dir 属性不处于已定义状态(即未出现或具有非法值)
如果该元素是一个 input 元素 type 属性处于 电话 状态, 且 dir 属性不处于已定义状态(即未出现或具有非法值)

元素的 方向 为 'ltr'。

如果该元素的 dir 属性处于 rtl 状态

元素的 方向 为 'rtl'。

如果该元素是 input 元素,且它的 type 属性处于 文本搜索电话URL,或 E-mail 状态, 且 dir 属性处于 auto 状态
如果该元素是 textarea 元素,且它的 dir 属性处于 auto 状态

如果该元素的 value 包含一个双向字符类型 AL 或 R 的字符, 且它之前不包含双向字符类型 L 的字符,则该元素的 方向 为 'rtl'。 [BIDI]

否则,如果该元素的 value 不是空字符串, 或者该元素是一个 文档元素,该元素的 方向 为 'ltr'。

否则,该元素的 方向 与该元素的父元素的 方向 相同。

如果该元素的 dir 属性处于 auto 状态
如果该元素是一个 bdi 元素且 dir 属性不处于已定义状态(即未出现或具有非法值)

找到按照 树序 的第一个匹配下列条件的字符:

如果找到了这样的字符且它属于双向字符类型 AL 或 R,该元素的 方向rtl'。

如果找到了这样的字符且它属于双向字符类型 L,该元素的 方向ltr'。

否则,如果该元素是 文档元素, 该元素的 方向ltr'。

否则,该元素的 方向 与该元素的父元素的 方向 相同。

如果有父元素且 dir 属性处于未定义状态 (即未出现或具有非法值)

该元素的 方向 与该元素的父元素的 方向 相同。

因为只有 HTML 元素 定义有 dir 属性, 它不得出现在其他命名空间的元素上。所以其他命名空间的元素只从它们的父元素继承 方向,如果没有父元素则默认为 'ltr'。

该属性 有涉及双向算法的渲染要求


当该属性的文本用于渲染过程时,HTML 元素 属性的方向 由第一个合适的步骤决定:

如果该属性是一个 有方向的属性 且该元素的 dir 属性处于 auto 状态

找到该属性值中第一个属于双向字符类型 L,AL,或 R (按照逻辑顺序)的字符。 [BIDI]

如果找到了这样一个字符,且它的双向字符类型是 AL 或 R, 该属性的方向 为 'rtl'。

否则,该属性的方向 为 'ltr'。

否则
该属性的方向 与该元素的 方向 相同。

下列属性属于 有方向的属性


document . dir [ = value ]

返回 html 元素dir 属性值,如果有的话。

可以设置为 "ltr","rtl",或 "auto" 来替换掉 html 元素dir 属性值。

如果不存在 html 元素,则返回空字符串,忽略新的值。

HTMLElement/dir

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

元素的 dir IDL 属性必须 反映dir 内容属性, 仅限于已知值

Document/dir

Support in all current engines.

Firefox1+Safari10.1+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS10.3+Chrome Android64+WebView Android64+Samsung Internet9.0+Opera Android47+

Document 对象上的 dir IDL 属性必须 反映 html 元素dir 内容属性,如果有的话, 仅限于已知值。如果没有这样的元素, 该属性必须返回空字符串,且在设置时什么都不做。

强烈建议作者使用 dir 属性而不是 CSS 来指明文本方向。因为这样的话即使没有 CSS 文档也会正确地渲染。 (例如被搜索引擎解释时)。

这个标记片段是关于 IM 对话的。

<p dir=auto class="u1"><b><bdi>Student</bdi>:</b> How do you write "What的 your name?" in Arabic?</p>
<p dir=auto class="u2"><b><bdi>Teacher</bdi>:</b> ما اسمك؟</p>
<p dir=auto class="u1"><b><bdi>Student</bdi>:</b> Thanks.</p>
<p dir=auto class="u2"><b><bdi>Teacher</bdi>:</b> That的 written "شكرًا".</p>
<p dir=auto class="u2"><b><bdi>Teacher</bdi>:</b> Do you know how to write "Please"?</p>
<p dir=auto class="u1"><b><bdi>Student</bdi>:</b> "من فضلك",right?</p>

给定 p 元素合适的样式表和默认对齐样式,也就是说把文本对齐到段落 起始端,渲染结果可能是这样的:

Each paragraph rendered as a separate block,with the paragraphs left-aligned except the second paragraph and the last one,which would  be right aligned,with the usernames (的tudent' and 'Teacher' in this example) flush right,with a colon to their left,and the text first to the left of that.

就像之前提到的,auto 值不是万能药。 这个例子中最后一个段落被错误地解释为从右向左的文本, 因为它以一个阿拉伯字符开始,这会导致 "right?" 出现在阿拉伯文字的左边。

3.2.6.5 style 属性

所有 HTML 元素 都可以设置 style 内容属性。 这个 style 属性 定义在 CSS Style Attributes 规范中。 [CSSATTR]

在支持 CSS 的用户代理中,当添加或改变这个属性时必须 , 根据 style 属性 的规则解析该属性的值。 [CSSATTR]

但是如果 是否应该根据内容安全策略禁止元素的内联行为 算法对 属性的 元素,"style attribute",和属性值返回了 "Blocked" , 那么该属性值中定义的样式规则不得应用于该 元素[CSP]

在任何元素上使用了 style 属性的文档必须 在那些属性移除之后仍然可以理解和使用。

特别是使用 style 属性来隐藏和显示内容, 或者传达文档中本没有的含义,这些都是不合规范的。 (隐藏和显示内容,可以使用 hidden 属性)


element . style

返回该元素的 style 属性的 CSSStyleDeclaration 对象。

style IDL 属性定义在 CSS Object Model (CSSOM) 规范中。 [CSSOM]

下面的例子中,使用 span 元素和 style 属性 来标记指代颜色的词,来让它们在视觉媒体中显示相关的颜色。

<p>My sweat suit is <span style="color: green; background:
transparent">green</span> and my eyes are <span style="color: blue;
background: transparent">blue</span>.</p>
3.2.6.6 使用 data-* 属性 嵌入自定义不可见数据

Global_attributes/data-*

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

自定义数据属性 是一个无命名空间的属性,其名字以 字符串 "data-" 起始,连字符后有至少一个字符, 兼容于 XML,且不得包含非 ASCII 大写字母

HTML 文档HTML 元素 上所有属性名都会被自动 ASCII 小写化,所以 ASCII 大写字母的限制不会影响这种文档。

自定义数据属性 用于存储页面或应用私有的,自定义的数据、状态、注解和类似东西,只有在找不到更合适的属性或元素时才能使用。

这些属性不适用于所属站点管理员不知道的软件。对于很多独立工具使用的通用扩展, 或者需要扩展本规范来显式地提供该特性,或者应该使用类似 microdata 的技术(使用标准化的词汇)。

例如一个音乐相关的站点可能会在表示专辑音轨的列表项中, 使用自定义数据属性来表示每个音轨的长度。 用户可能会用该信息对列表进行排序,或者按照某个长度来过滤列表。

<ol>
 <li data-length="2m11s">Beyond The Sea</li>
 ..。
</ol>

但是用户使用与这个音乐站点不相关的通用软件来根据这个数据搜索某个长度的音轨是不合适的。

这是因为这些属性只适用于该站点自己的脚本,并不是一种公众可用的元数据的通用扩展机制。

类似地,页面作者可能会编写一些标记来为他们打算使用的翻译工具提供一些信息:

<p>The third <span data-mytrans-de="Anspruch">claim</span> covers the case of <span
translate="no">HTML</span> markup.</p>

这个例子中,"data-mytrans-de" 属性给出的文字 提供给 MyTrans 产品使用,把 "claim" 翻译到德语。但是标准的 translate 属性用于指示, 在所有语言环境中 "HTML" 要保持不变。当有标准属性可用时,就没必要使用 自定义数据属性 了。

在这个例子中,自定义数据属性用于存储 PaymentRequest 特性探测的结果,可能会用于 CSS 中,对付款页面做特殊的样式。

<script>
 if ('PaymentRequest' in window) {
   document.documentElement.dataset.hasPaymentRequest = '';
 }
</script>

这里 data-has-payment-request 属性被当做 布尔属性 来使用;检查该属性是否出现就足够了。 但是如果作者希望,它后续也可以填充一些值,比如用来标识该特性的功能限制。

每个 HTML 元素 都可以指定任意个 自定义数据属性,指定为任意值。

作者应该仔细地设计这样的扩展,当属性被忽略或者任何相关 CSS 被丢弃时,页面仍然可用。

用户代理不得从这些属性和值腿短任何实现行为。用户代理的相关规范不得为这些属性定义任何有意义的值。

JavaScript 库可以使用 自定义数据属性,因为它们也是页面的一部分。 鼓励有很多人用的库的作者在属性名中包含名字,来减小冲突的风险。 如果可行的话,鼓励库的作者支持自定义实际在用的名字,这样不小心选了重复名字的库也可以用于同一个页面, 同一个库的多个版本也可以用于同一个页面,即使它们互相不兼容。

例如一个叫做 "DoQuery" 的库可能会使用叫做 data-doquery-range 的属性名, 另一个叫做 "jJo" 的库可能会使用叫做 data-jjo-range 的属性名。 jJo 库也可以提供一个 API 来设置使用哪个前缀(例如 J.setDataPrefix('j2'), 使属性的名字变成 data-j2-range)。


element . dataset

HTMLElement/dataset

Support in all current engines.

Firefox6+Safari5.1+Chrome8+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android6+Safari iOS5+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android11+

SVGElement/dataset

Support in all current engines.

Firefox51+Safari5.1+Chrome55+
Opera41+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android51+Safari iOS5+Chrome Android55+WebView Android55+Samsung Internet6.0+Opera Android41+

返回该元素的 data-* 属性的 DOMStringMap 对象。

连字符连接的名字会变成驼峰的。例如 data-foo-bar="" 变成了 element.dataset.fooBar

dataset IDL 属性 为元素上的所有 data-* 属性提供了便利访问器。 当读取时,dataset IDL 属性必须返回一个与该元素关联的 DOMStringMap

DOMStringMap 接口用于 dataset 属性。每个 DOMStringMap 有一个 关联的元素

[OverrideBuiltins]
interface DOMStringMap {
  getter DOMString (DOMString name);
  [CEReactions] setter void (DOMString name,DOMString value);
  [CEReactions] deleter void (DOMString name);
};

获取 DOMStringMap 的键值对,需呀执行以下算法:

  1. list 为一个键值对的空列表。

  2. 对于 DOMStringMap关联元素 上的每个前五个字符是 "data-" 且剩余字符(如果有的话)不包含任何 ASCII 大写字母 的内容属性, 按照这些属性在 属性列表 中出现的顺序, 在 list 中新增一个键值对,属性名移除前五个字符后作为键,属性值作为值。

  3. list 中的每个键中的每个后面跟随着一个 ASCII 小写字母 的 U+002D HYPHEN-MINUS 字符 (-) ,移除这个 U+002D HYPHEN-MINUS 字符 (-)并且将后面的这个字符替换为 同一个字母 转换为 ASCII 大写 的结果。

  4. 返回 list

任一时刻,DOMStringMap 对象上 支持的属性名 都是那一时刻 获取 DOMStringMap 的键值对 返回的每个键值对的键构成的列表,并按照返回的顺序排序。

对一个 DOMStringMap 确定命名属性 name 的值获取 DOMStringMap 的键值对 返回的列表中键是 name 的键值对的值。

给定属性名 name 和一个新值 value, 为一个 DOMStringMap 设置一个新命名属性的值设置已有属性的值 ,需要执行以下步骤:

  1. 如果 name 包含一个 U+002D HYPHEN-MINUS 字符(-) 紧跟着 ASCII 小写字母, 则抛出一个 "SyntaxError" DOMException 并中止这些步骤。

  2. 对每一个 name 中的 ASCII 大写字母 , 在该字符前插入一个 U+002D HYPHEN-MINUS 字符(-),并把这个字母替换为同一字母 转换为 ASCII 小写 的结果。

  3. name 之前插入字符串 data-

  4. 如果 name 不匹配 XML Name 生成式, 抛出一个 "InvalidCharacterError" DOMException 并中止这些步骤。

  5. 使用 namevalueDOMStringMap关联元素 设置属性值

为一个 DOMStringMap 删除一个既有命名属性 name ,需要执行以下步骤:

  1. 对每一个 name 中的 ASCII 大写字母 , 在该字符前插入一个 U+002D HYPHEN-MINUS 字符(-),并把这个字母替换为同一字母 转换为 ASCII 小写 的结果。

  2. name 之前插入字符串 data-

  3. 给定 nameDOMStringMap关联元素 通过属性名移除属性

Web IDL 规范只会使用前述 获取 DOMStringMap 的键值对 算法给出的名字调用该算法。 [WEBIDL]

如果一个 Web 页面想要一个元素来表示宇宙飞船,比如作为游戏的一部分,他可能必须同时使用 class 属性与 data-* 属性:

<div class="spaceship" data-ship-id="92432"
     data-weapons="laser 2" data-shields="50%"
     data-x="30" data-y="10" data-z="90">
 <button class="fire"
         onclick="spaceships[this.parentNode.dataset.shipId].fire()">
  Fire
 </button>
</div>

注意连字符连接的属性名在 API 中变成了驼峰命名的。

给定下面的相似构造的片段和元素:

<img class="tower" id="tower5" data-x="12" data-y="5"
     data-ai="robotarget" data-hp="46" data-ability="flames"
     src="towers/rocket.png" alt="Rocket Tower">

...可能会想到用一个 splashDamage() 函数,它接受的第一个参数是被处理的元素:

function splashDamage(node,x,y,damage) {
  if (node.classList.contains('tower') && // checking the 'class' attribute
      node.dataset.x == x && // reading the 'data-x' attribute
      node.dataset.y == y) { // reading the 'data-y' attribute
    var hp = parseInt(node.dataset.hp); // reading the 'data-hp' attribute
    hp = hp - damage;
    if (hp < 0) {
      hp = 0;
      node.dataset.ai = 'dead'; // setting the 'data-ai' attribute
      delete node.dataset.ability; // removing the 'data-ability' attribute
    }
    node.dataset.hp = hp; // setting the 'data-hp' attribute
  }
}

3.2.7 The innerText getter and setter

HTMLElement/innerText

Support in all current engines.

Firefox45+Safari3+Chrome1+
Opera9.6+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android45+Safari iOS1+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android10.1+
element . innerText [ = value ]

Returns the element's text content "as rendered".

Can be set, to replace the element's children with the given value, but with line breaks converted to br elements.

The innerText getter steps are:

  1. If this is not being rendered or if the user agent is a non-CSS user agent, then return this's descendant text content.

    This step can produce surprising results, as when the innerText getter is invoked on an element not being rendered, its text contents are returned, but when accessed on an element that is being rendered, all of its children that are not being rendered have their text contents ignored.

  2. Let results be a new empty list.

  3. For each child node node of this:

    1. Let current be the list resulting in running the inner text collection steps with node. Each item in results will either be a string or a positive integer (a required line break count).

      Intuitively, a required line break count item means that a certain number of line breaks appear at that point, but they can be collapsed with the line breaks induced by adjacent required line break count items, reminiscent to CSS margin-collapsing.

    2. For each item item in current, append item to results.

  4. Remove any items from results that are the empty string.

  5. Remove any runs of consecutive required line break count items at the start or end of results.

  6. Replace each remaining run of consecutive required line break count items with a string consisting of as many U+000A LINE FEED (LF) characters as the maximum of the values in the required line break count items.

  7. Return the concatenation of the string items in results.

The inner text collection steps, given a node node, are as follows:

  1. Let items be the result of running the inner text collection steps with each child node of node in tree order, and then concatenating the results to a single list.

  2. If node's computed value of 'visibility' is not 'visible', then return items.

  3. If node is not being rendered, then return items. For the purpose of this step, the following elements must act as described if the computed value of the 'display' property is not 'none':

    items can be non-empty due to 'display:contents'.

  4. If node is a Text node, then for each CSS text box produced by node, in content order, compute the text of the box after application of the CSS 'white-space' processing rules and 'text-transform' rules, set items to the list of the resulting strings, and return items. The CSS 'white-space' processing rules are slightly modified: collapsible spaces at the end of lines are always collapsed, but they are only removed if the line is the last line of the block, or it ends with a br element. Soft hyphens should be preserved. [CSSTEXT]

  5. If node is a br element, then append a string containing a single U+000A LINE FEED (LF) character to items.

  6. If node's computed value of 'display' is 'table-cell', and node's CSS box is not the last 'table-cell' box of its enclosing 'table-row' box, then append a string containing a single U+0009 CHARACTER TABULATION (tab) character to items.

  7. If node's computed value of 'display' is 'table-row', and node's CSS box is not the last 'table-row' box of the nearest ancestor 'table' box, then append a string containing a single U+000A LINE FEED (LF) character to items.

  8. If node is a p element, then append 2 (a required line break count) at the beginning and end of items.

  9. If node's used value of 'display' is block-level or 'table-caption', then append 1 (a required line break count) at the beginning and end of items. [CSSDISPLAY]

    Floats and absolutely-positioned elements fall into this category.

  10. Return items.

Note that descendant nodes of most replaced elements (e.g., textarea, input, and video — but not button) are not rendered by CSS, strictly speaking, and therefore have no CSS boxes for the purposes of this algorithm.

This algorithm is amenable to being generalized to work on ranges. Then we can use it as the basis for Selection's stringifier and maybe expose it directly on ranges. See Bugzilla bug 10583.

The innerText setter steps are:

  1. Let document be this's node document.

  2. Let fragment be a new DocumentFragment object whose node document is document.

  3. Let input be the given value.

  4. Let position be a pointer into input, initially pointing at the start of the string.

  5. Let text be the empty string.

  6. While position is not past the end of input:

    1. Collect a sequence of code points that are not U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters from input given position. Set text to the collected characters.

    2. If text is not the empty string, then append a new Text node whose data is text and node document is document to fragment.

    3. While position is not past the end of input, and the character at position is either a U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) character:

      1. If the character at position is a U+000D CARRIAGE RETURN (CR) character and the next character is a U+000A LINE FEED (LF) character, then advance position to the next character in input.

      2. Advance position to the next character in input.

      3. Append the result of creating an element given document, br, and the HTML namespace to fragment.

  7. Replace all with fragment within this.

3.2.8 与双向算法相关的要求

3.2.8.1 双向算法格式化字符的编写一致性标准

内容 中包含 Text 节点的 HTML 元素 中的 文本内容, 以及允许自由文本的 HTML 元素 属性中的文本, 可以包含 U+202A 到 U+202E,和 U+2066 到 U+2069 (双向算法的格式化字符) 范围内的字符。 [BIDI]

鼓励作者使用 dir 属性, bdo 元素,以及 bdi 元素, 而不是手动地维护双向算法字符。双向算法格式化字符与 CSS 的交互性很差。

3.2.8.2 用户代理一致性标准

用户代理必须实现 Unicode 双向算法,以便在渲染文档或文档部分时确定合适的字符顺序。[BIDI]

HTML 到 Unicode 双向算法的映射必须以这三种方式中的任何一种来完成。 一,用户代理必须实现 CSS,特别是 CSS 'unicode-bidi''direction',和 'content' 属性, 并且在其用户代理样式表中必须包含在本规范的 渲染 章节中给出的用到了这些属性的规则。 二,用户代理必须表现得就像实现了前述属性一样,并且用户代理样式表中包含所有前述规则,但没有让文档中指定的样式表覆盖它们。 三,用户代理必须实现另一种具有等价语义的样式语言。 [CSSGC]

以下元素和属性具有由 渲染 部分定义的要求, 由于本节中的要求,那些要求对所有用户代理都有效(不仅仅是那些 支持建议默认渲染的):

3.2.9 ARIA 与 平台可访问性 API 相关的要求

HTML 元素 上实现可访问性 API 语义的用户代理要求定义在 HTML Accessibility API Mappings 中。 [HTMLAAM]

对一致性检查器检查 HTML 元素 上 ARIA rolearia-* 属性的使用 的相关要求定义在 ARIA in HTML[ARIAHTML]

4 HTML 元素

4.1 文档元素

4.1.1 html 元素

Element/html

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLHtmlElement

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
类别
无。
该元素可用的上下文
作为文档的 文档元素
复合文档中允许子文档片段的地方。
内容模型
head 元素紧接着 body 元素。
text/html 中的标签省略
An html element's start tag can be omitted if the first thing inside the html element is not a comment.
An html element's end tag can be omitted if the html element is not immediately followed by a comment.
内容属性
全局属性
manifestApplication cache manifest
DOM 接口
[HTMLConstructor]
interface HTMLHtmlElement : HTMLElement {};

html 元素 表示 HTML 文档的根。

鼓励作者在根 html 元素上指定 lang 属性, 给出文档的语言。这可以帮助语音合成工具确定要使用的发音,帮助翻译工具确定要使用的规则, 等等。

manifest 属性给出文档的 应用缓存 manifest 的地址,如果有的话。 如果出现了该属性,其值必须是一个 可能被空格包裹的合法的非空URL

manifest 属性是是遗留的 "离线 Web 应用" 特性的一部分, 该特性正在从 Web 平台移除。(这是一个很长的过程,可能持续很多年。) 现在强烈不推荐使用 manifest 属性。 使用 service workers 来替代。 [SW]

manifest 属性只在文档加载的早期阶段 起作用。 因此动态改变该属性没有效果(因此没有为该属性提供任何 DOM API)。

应用缓存选择 中,后续的 base 元素影响不了 manifest 属性的 URL 解析,因为在还没看到这些元素时就进行了这些属性的处理。

window.applicationCache IDL 属性提供了对离线 应用缓存 机制的脚本访问。

下面例子中的 html 元素声明了该文档的语言是英语。

<!DOCTYPE html>
<html lang="en">
<head>
<title>Swapping Songs</title>
</head>
<body>
<h1>Swapping Songs</h1>
<p>Tonight I swapped some of the songs I wrote with some friends,who
gave me some of the songs they wrote. I love sharing my music.</p>
</body>
</html>

4.2 文档元数据

4.2.1 head 元素

Element/head

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLHeadElement

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
类别
无。
该元素可用的上下文
作为 html 元素的第一个元素。
内容模型
如果该文档是 iframe srcdoc 文档, 或者如果在更高级协议上有标题信息可用:大于等于0个 元数据内容 元素,其中不多于一个 title 元素, 不多于一个 base 元素。
否则:一个或更多 元数据内容 元素,其中恰好一个是 title 元素, 且不多于一个 base 元素。
text/html 中的标签省略
A head element's start tag can be omitted if the element is empty, or if the first thing inside the head element is an element.
A head element's end tag can be omitted if the head element is not immediately followed by ASCII whitespace or a comment.
内容属性
全局属性
DOM 接口
[HTMLConstructor]
interface HTMLHeadElement : HTMLElement {};

head 元素 表示 Document 的元数据集合。

head 元素中的元数据集合可大可小。这里有一个非常小的例子:

<!doctype html>
<html lang=en>
 <head>
  <title>A document with a short head</title>
 </head>
 <body>
 ...

这是一个更长的例子:

<!DOCTYPE HTML>
<HTML LANG="EN">
 <HEAD>
  <META CHARSET="UTF-8">
  <BASE HREF="https://www.example.com/">
  <TITLE>An application with a long head</TITLE>
  <LINK REL="STYLESHEET" HREF="default.css">
  <LINK REL="STYLESHEET ALTERNATE" HREF="big.css" TITLE="Big Text">
  <SCRIPT SRC="support.js"></SCRIPT>
  <META NAME="APPLICATION-NAME" CONTENT="Long headed application">
 </HEAD>
 <BODY>
 ...

title 元素在多数场景下都是必须的子元素,但是当更高级协议提供了标题信息时, 例如在 e-mail 中使用 HTML 作为编写格式,有标题行时就可以忽略 title 元素。

4.2.2 title 元素

Element/title

Support in all current engines.

Firefox1+Safari1+Chrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet Explorer1+
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLTitleElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
类别
元数据内容
该元素可用的上下文
在不包含 titlehead 元素中。
内容模型
元素间空白文本内容
text/html 中的标签省略
哪个标签都不能省略。
内容属性
全局属性
DOM 接口
[HTMLConstructor]
interface HTMLTitleElement : HTMLElement {
  [CEReactions] attribute DOMString text;
};

title 元素 表示 文档的标题或名称。 作者应该使用标识其文档的标题,这个标题在其他上下文中也会被使用,例如在用户的历史、书签,或搜索结果中。 文档的标题常常与第一个标题元素不同,因为第一个标题不需要在上下文之外有意义。

每个文档不得有多个 title 元素。

如果 Document 没有标题是合理的,则可能不要求有 title 元素。在 head 元素的内容模型中描述了何时该元素是必须的。

title . text [ = value ]

返回该元素的 子文本内容

设置时用给定的值替换该元素的子内容。

text IDL 属性必须返回 title 元素的 子文本内容。 当设置时,必须与 textContent IDL 属性的表现一致。

这是一些合适的标题的例子,以及同一页面中可能有的顶层标题。

  <title>Introduction to The Mating Rituals of Bees</title>
    ...
  <h1>Introduction</h1>
  <p>This companion guide to the highly successful
  <cite>Introduction to Medieval Bee-Keeping</cite> book is...

The next page might be a part of the same site。 Note how the title describes the subject matter unambiguously,while the first heading assumes the reader knows what the context is and therefore won't wonder if the dances are Salsa or Waltz:

  <title>Dances used during bee mating rituals</title>
    ...
  <h1>The Dances</h1>

document.title IDL 属性用作文档的标题。

当用户代理在其用户界面中引用文档时,应该使用该文档的标题。 当这样使用 title 元素的内容时, 应该使用该 title 元素的 方向 设置用户界面中该文档标题的方向。

4.2.3 base 元素

HTMLBaseElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
类别
元数据内容
该元素可用的上下文
不包含其他 base 元素的 head 元素中。
内容模型
text/html 中的标签省略
哪个标签都不能省略。
内容属性
全局属性
hrefDocument base URL
target — Default browsing context for hyperlink navigation and form submission
DOM 接口
[Exposed=Window,
 HTMLConstructor]
interface HTMLBaseElement : HTMLElement {
  [CEReactions] attribute USVString href;
  [CEReactions] attribute DOMString target;
};

base 元素允许作者指定用于 解析 URL文档基 URL, 以及用于 跟随超链接 的默认 浏览上下文 的名称。 该元素不 表示 超出该信息的任何内容。

每个文档中不得包含多个 base 元素。

base 元素有一个 href 属性, 或者 target 属性,或者两者都有。

如果指定了 href 内容属性, 必须包含一个 可能被空白包裹的合法的 URL

如果 base 元素有 href 属性, 则必须出现在树中的任何使用 URL 的其他元素之前, html 元素除外(其 manifest 属性不受 base 元素的影响)。

如果有多个有 href 属性的 base 元素, 则忽略除第一个之外的。

如果指定了 target 属性,则必须包含一个 合法的浏览上下文名称或关键字, 它指定了当 Document 中的 超链接表单 产生 导航 时默认使用哪个 浏览上下文

base 元素如果有 target 属性, 必须出现在树中表示 超链接 的其他元素之前。

如果有多个有 target 属性的 base 元素,则忽略除第一个之外的。

给定 aarea, 或 form 元素 element, 要 获得元素的 target,执行这些步骤:

  1. 如果 elementtarget 属性,则返回该属性的值。

  2. 如果 element节点文档 包含一个 有 target 属性的 base 元素, 则返回第一个这样的 base 元素的这一 target 属性的值。

  3. 返回空字符串。


在文档树中 第一个有 href 内容属性的 base 元素元素有一个 冻结的 base URL。当下列情况发生时, 必须 立即 设置 元素的 冻结的 base URL

为元素 element 设置冻结的 base URL 步骤如下:

  1. documentelement节点文档

  2. urlRecord 为用 documentfallback base URL, 以及 document字符编码 解析 elementhref 内容属性的值的结果。 (因此 base 元素不影响它自己。)

  3. 如果 urlRecord 是失败或者 在 结果 URL 记录document 上执行 Document 是否允许 base? 返回了 "Blocked", 则设置 element冻结的 base URLdocumentfallback base URL;否则设置为 urlRecord

在读取时,href IDL 属性必须返回运行以下算法的结果:

  1. documentelement节点文档

  2. url 该元素的 href 属性的值, 如果没有则为空字符串。

  3. urlRecord 为用 documentfallback base URL, 以及 document字符编码 解析 elementhref 内容属性的值的结果。 (因此 base 元素不影响它自己。)

  4. 如果 urlRecord 是失败,则返回 url

  5. 返回 urlRecord序列化

在设置 href IDL 属性时,必须设置 href 内容属性为给定的新值。

target IDL 属性必须 反映 同名的内容属性。

在这个例子中,用一个 base 元素来设置 文档的 base URL

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>This is an example for the &lt;base&gt; element</title>
        <base href="https://www.example.com/news/index.html">
    </head>
    <body>
        <p>Visit the <a href="archives.html">archives</a>.</p>
    </body>
</html>

上面例子中的链接地址是 "https://www.example.com/news/archives.html"。

HTMLLinkElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
类别
元数据内容
如果 body 中允许 该元素:流式内容
如果 body 中允许 该元素:短语内容
该元素可用的上下文
期望 元数据内容 的地方。
head 中的 noscript 元素中。
如果 body 中允许 该元素: 期望 短语内容 的地方。
内容模型
text/html 中的标签省略
哪个标签都不能省略。
内容属性
全局属性
href — Address of the hyperlink
crossorigin — How the element handles crossorigin requests
rel — Relationship between the document containing the hyperlink and the destination resource
media — Applicable media
integrity — Integrity metadata used in Subresource Integrity checks [SRI]
hreflang — Language of the linked resource
type — Hint for the type of the referenced resource
referrerpolicyReferrer policy for fetches initiated by the element
sizes — Sizes of the icons (for rel="icon")
imagesrcset — Images to use in different situations, e.g., high-resolution displays, small monitors, etc. (for rel="preload")
imagesizes — Image sizes for different page layouts (for rel="preload")
asPotential destination for a preload request (for rel="preload" and rel="modulepreload")
color — Color to use when customizing a site's icon (for rel="mask-icon")
disabled — Whether the link is disabled
此外,在该元素上 title 属性 有特殊的语义。 — Title of the link — CSS style sheet set name
可访问性相关
使用者版本
实现者版本
DOM 接口
[Exposed=Window]
interface HTMLLinkElement : HTMLElement {
  [HTMLConstructor] constructor();
  [CEReactions] attribute USVString href;
  [CEReactions] attribute DOMString? crossOrigin;
  [CEReactions] attribute DOMString rel;
  [CEReactions] attribute DOMString as; // (default "")
  [SameObject,PutForwards=value] readonly attribute DOMTokenList relList;
  [CEReactions] attribute DOMString media;
  [CEReactions] attribute DOMString integrity;
  [CEReactions] attribute DOMString hreflang;
  [CEReactions] attribute DOMString type;
  [SameObject,PutForwards=value] readonly attribute DOMTokenList sizes;
  [CEReactions] attribute USVString imageSrcset;
  [CEReactions] attribute DOMString imageSizes;
  [CEReactions] attribute DOMString referrerPolicy;
  [CEReactions] attribute boolean disabled;

  // also has obsolete members
};
HTMLLinkElement includes LinkStyle;

link 元素允许作者把他们的文档链接到其他资源。

链接的地址由 href 属性给出。 如果存在 href 属性,那么它的值必须是一个 可能由空格包裹的合法的非空 URL。 必须存在 hrefimagesrcset 属性。

如果 hrefimagesrcset 属性都不存在,那么该元素就不包含链接的定义。

crossorigin 属性是一个 CORS 设置属性,用于 外部资源链接

链接指示的类型(关系)由 rel 属性的值给出。该属性如果出现则它的值必须是一个 由空格分隔的唯一令牌的无序集合允许的关键字及其含义 定义在后续章节中。 如果 rel 属性缺失, 不包含关键字,或者没有出现(根据本规范中的定义)允许的关键字, 则该元素不创建任何链接。

rel 支持的令牌HTML 链接类型 中定义的, link 元素上允许的,影响处理模型的,用户代理支持的关键字。 可能的 支持的令牌 包括 alternatedns-prefetchiconmodulepreload, nextpingbackpreconnectprefetchpreloadprerendersearch,和 stylesheetrel支持的令牌 必须只包含这个列表中用户代理实现了相应处理模型的令牌。

理论上用户代理可能会支持 canonical 关键字的处理模型, 比如用户代理是一个执行 JavaScript 的搜索引擎的话。虽然实践中基本不会发生。 所以大多数场景下,canonical 不应属于 rel 支持的令牌

link 元素必须有一个 rel 属性或者 itemprop 属性,但不能同时有这两个。

如果 link 元素有一个 itemprop 属性, 或者有一个只包含 body-ok 关键字的 rel 属性, 则称该元素 允许出现在 body 中。 这意味着该元素可以用于期望 短语内容 的地方。

如果用了 rel 属性, 该元素只能用于页面中的 body 部分。如果用了 itemprop 属性,该元素既可以用于页面中的 head 元素也可以用于 body 元素,取决于元数据模型的约束。

使用 link 元素可以创建两类链接: 外部资源链接超链接链接类型一章 定义了 特定的链接类型是外部资源还是超链接。 一个 link 元素可以创建多个链接(其中有些可能是 外部资源链接,有些可能是 超链接);具体创建了哪种链接,创建了多少个取决于 rel 属性中给出的关键字。 用户代理必须逐链接而不是逐元素进行处理。

link 元素创建的每个链接都会被单独处理。 例如,如果有两个有 rel="stylesheet"link 元素, 它们每个都被当做独立的外部资源,每个都会独立地受自己的属性影响。 类似地,如果单个 link 元素有一个 值为 next stylesheet rel 属性, 它(为 next 关键字)创建了一个 超链接,同时也 (为 stylesheet 关键字)创建了一个 外部资源链接, 它们分别受其他属性(例如 mediatitle)的影响。

例如下面的 link 元素创建了两个 超链接 (指向同一页面):

<link rel="author license" href="/about">

该元素创建的这两个链接,一个的语义是目标页面具有关于当前页面作者的信息, 另一个的语义是目标页面具有提供当前页面的授权信息。

link 元素和它的 rel 属性创建的 超链接 适用于整个文档。 这区别于 aarea 元素的 rel 属性,它们指定了链接的类型, 链接的上下文由链接在文档中的位置给出。

外部资源链接 的确切行为取决于由相关的 链接类型 定义的具体关系。

media 属性指定了该资源适用哪种媒体。 它的值必须是 合法的媒体查询列表

nonce 属性表示一个加密随机数 ("一次性数字")用于 Content Security Policy 来确定 该链接指定的外部资源 是否会被加载和应用于该文档。它的值是文本。 [CSP]

integrity 属性表示该元素负责的请求的 integrity 元信息。 值为文本。该属性只能用于 rel 属性包含 stylesheetpreloadmodulepreload 关键字的 link 元素。[SRI]

link 元素上的 hreflang 属性与 a 元素上的 hreflang 属性 具有相同的语义。

type 属性给出了被链接资源的 MIME 类型。它纯属建议性的。它的值必须是 合法的 MIME 类型

对于 外部资源链接type 属性用于提示用户代理避免获取它们不支持的资源。

referrerpolicy 属性是一个 引荐策略属性。 它用于 外部资源链接, 帮助设置 获取和处理 该外部资源时的 引荐策略[REFERRERPOLICY]

title 属性给出了链接的标题。 有一个特例中,它是纯建议性的。它的值是文本。 特例是 在文档树 中的样式表链接, 对它而言 title 属性定义了 CSS 样式表集合

link 元素上的 title 属性 与多数其他元素的全局 title 属性不同, 没有标题的链接不继承父元素的标题:它只是没有标题。


imagesrcset 属性可以是一个 srcset 属性

imagesrcsethref 属性(如果没有使用 宽度描述符) 一起给 source set 提供 图片源

如果 imagesrcset 属性存在且有任一个 图片候选字符串 使用了 宽度描述符imagesizes 属性就必须存在,且是一个 尺寸属性imagesizes 属性给 source set 提供 源尺寸

imagesrcsetimagesizes 属性只能用于 rel 属性指定了 preload 关键字,且 as 属性在处于 "image" 状态的 link 元素上。

这些属性运行预加载适当的资源, 后续 img 被使用 srcsetsizes 属性:

<link rel="preload" as="image"
      imagesrcset="wolf_400px.jpg 400w, wolf_800px.jpg 800w, wolf_1600px.jpg 1600w"
      imagesizes="50vw">

<!-- ... later, or perhaps inserted dynamically ... -->
<img src="wolf.jpg" alt="A rad wolf"
     srcset="wolf_400px.jpg 400w, wolf_800px.jpg 800w, wolf_1600px.jpg 1600w"
     sizes="50vw">

注意我们忽略了 href 属性,因为它会在不支持 imagesrcset 的浏览器中起作用,可能会预加载错误的图片。

imagesrcset 属性可以和 media 属性一起使用来预加载适当的资源 picture 元素选择的资源,来实现 美术设计

<link rel="preload" as="image"
      imagesrcset="dog-cropped-1x.jpg, dog-cropped-2x.jpg 2x"
      media="(max-width: 800px)">
<link rel="preload" as="image"
      imagesrcset="dog-wide-1x.jpg, dog-wide-2x.jpg 2x"
      media="(min-width: 801px)">

<!-- ... later, or perhaps inserted dynamically ... -->
<picture>
  <source srcset="dog-cropped-1x.jpg, dog-cropped-2x.jpg 2x"
          media="(max-width: 800px)">
  <img src="dog-wide-1x.jpg" srcset="dog-wide-2x.jpg 2x"
       alt="An awesome dog">
</picture>

sizes 属性给出了 视觉媒体的图标大小。它的值(如果存在的话)只是建议性的。 用户代理可以根据它的值来在多个可用的图标中选择使用哪个。 如果指定了,这个属性的值必须是 ASCII 大小写不敏感空格分隔的无序不重复令牌集合。 每个值必须 ASCII 大小写不敏感 地匹配字符串 "any",或包含两个 合法的非负整数 且不得有前导 U+0030 DIGIT ZERO (0) 字符, 并以单个 U+0078 LATIN SMALL LETTER X 或 U+0058 LATIN CAPITAL LETTER X 字符分隔。 该属性只能用于 rel 属性指定了 icon 关键字或 apple-touch-icon 关键字的 link 元素。

apple-touch-icon 关键字是一个已注册的 链接类型的预定义集合扩展,但不要求用户代理支持它。


as 属性为 href 指定的资源的预加载请求指定了 可能的地址。 这是一个 枚举属性。 每个 可能的地址 是一个关键字, 映射为一个同名的状态。该属性必须指定在 rel 属性包含 preload 关键字的 link 元素上。也可以指定在 rel 属性包含 modulepreload 关键字的 link 元素上;这种情况下它的值必须是 script-like 地址。 其他 link 元素不能使用这个属性。

如何使用 as 属性的处理模型在 每个 link 类型的 获取和处理链接资源 算法中给出。

该属性没有 缺失值默认非法值默认,意味着非法值或缺失值不映射到任何状态。 这在处理模型中有所解释。


color 属性用于 mask-icon 链接类型。该属性不得指定在 rel 属性不包含 mask-icon 关键字的 link 元素上。它的值必须是一个匹配 CSS <color> 生成式的字符串, 用于定义一个用户代理在用户固定一个网站时用来自定义图标展示的建议颜色。

本规范在 color 属性上对用户代理没有任何要求。

mask-icon 关键字是一个已注册的 链接类型的预定义集合扩展,但不要求用户代理支持。


link 元素有一个关联的 explicitly enabled 布尔。它默认为假。

disabled 属性是一个 布尔属性,用在 stylesheet 链接类型上。该属性只能用在 rel 属性包含 stylesheet 关键字的 link 元素上。

只要 disabled 属性被移除,就设置 link 元素的 explicitly enabled 属性为真。

动态地移除 disabled 属性,例如用 document.querySelector("link").removeAttribute("disabled"),会去获取并应用样式:

<link disabled rel="alternate stylesheet" href="css/pooh">

HTMLLinkElement/rel

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

IDL 属性 hrefhreflangintegritymedianoncerelscopesizestype,和 disabled 都必须 反映 对应的同名内容属性。

color 属性没有相应的 IDL 属性,但今后可能会增加。

HTMLLinkElement/as

Support in all current engines.

Firefox56+Safari10+Chrome50+
Opera37+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android56+Safari iOS10+Chrome Android50+WebView Android50+Samsung Internet5.0+Opera Android37+

as IDL 属性必须 反映 as 内容属性, 并限制为已知的值

crossOrigin IDL 属性必须 反映 crossorigin 内容属性。

HTMLLinkElement/referrerPolicy

Support in all current engines.

Firefox50+Safari14.1+Chrome58+
Opera45+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android50+Safari iOS14.5+Chrome Android58+WebView Android58+Samsung Internet7.0+Opera Android43+

referrerPolicy IDL 属性必须 反映 referrerpolicy 内容属性,并 限制到已知的值

The imageSrcset IDL 属性必须 反映 imagesrcset 内容属性。

The imageSizes IDL 属性必须 反映 the imagesizes 内容属性。

HTMLLinkElement/relList

Support in all current engines.

Firefox30+Safari9+Chrome50+
Opera37+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android30+Safari iOS9+Chrome Android50+WebView Android50+Samsung Internet5.0+Opera Android37+

relList IDL 属性必须 反映 rel 内容属性。

4.2.4.1 处理 media 属性

如果该链接是 超链接 那么 media 属性就是纯建议性的, 描述了该文档是为哪种媒体设计的。

但如果该链接是 外部资源链接,则 media 属性则是指定的。 当 media 属性值 匹配当前环境 以及其他相关条件时, 用户代理必须应用这一外部资源。其他情况不得应用该资源。

如果忽略 media 属性, 默认值是 "all",表示默认情况下链接适用于所有媒体。

外部资源可能会在此限制范围内限定其适用性。 例如,CSS样式表可能有一些 @media 块。 本规范不会覆盖这些进一步的限制或要求。

4.2.4.2 处理 type 属性

如果存在 type 属性,那么用户代理必须假定 该资源属于给定的类型(即使它不是 合法的 MIME 类型, 例如空字符串)。 如果忽略了该属性,但 外部资源链接 类型定义有默认值,则用户代理必须假定该资源属于那种类型。 如果 UA 对指定的链接关系不支持给定的 MIME 类型, 那么 UA 不应 获取和处理 该资源;如果 UA 对指定的链接关系支持给定的 MIME 类型, 那么 UA 应该按照 外部资源链接 的特定类型所指定的 适当时机 获取和处理 该资源。 如果忽略了该属性,且 外部资源链接 类型没有定义默认值,但如果已知类型且支持的话用户代理会 获取和处理 该资源, 那么用户代理就应该假设支持该资源并且 获取和处理 它。

用户代理不得将 type 属性当做权威的 — 也就是说获取该资源时用户代理不得使用 type 属性来决定实际的类型。只能用实际的类型(定义在下一段)而不是前述的假设的类型 来决定是否应用该资源。

stylesheet 链接类型定义了处理资源的 Content-Type 元数据 的规则。

一旦用户代理建立了该资源的类型,而且这是一个支持的类型并满足其他相关条件,就必须应用该资源。 否则就必须忽略该资源。

如果一个文档包含如下标记的样式表链接:

<link rel="stylesheet" href="A" type="text/plain">
<link rel="stylesheet" href="B" type="text/css">
<link rel="stylesheet" href="C">

那么一个只支持 CSS 样式表的满足规范的 UA 会获取 B 和 C 文件, 并跳过 A (因为 text/plain 不是 CSS 样式表的 MIME type)。

对于文件 B 和 C,它会检查服务器返回的实际类型。对于作为 text/css 发送的, 它将会应用样式,但对于标记为 text/plain 或其他类型则不会。

如果这两个文件中的一个返回时没有 Content-Type 元数据, 或者有一个语法错误的类型比如 Content-Type: "null", 那么就使用 stylesheet 链接的默认类型。 因为这个默认类型是 text/css,所以这个样式表 将会 被应用。

给定 link 元素 el默认的获取和处理链接资源 如下:

  1. 如果 href 属性的值是空字符串,则中止这些步骤。

  2. 给定 href 属性,相对于该元素的 节点文档 解析 URL。如果失败则返回。否则,令 url结果 URL 记录

  3. corsAttributeState 为该元素的 crossorigin 内容属性的当前状态。

  4. request 为给定 url,空字符串,以及 corsAttributeState 创建一个可能跨域的请求 的结果。

  5. 设置 request异步标志

  6. 设置requestclientlink 元素的 节点文档相关设置对象

  7. 设置requestnonce 元数据link 元素的 [[CryptographicNonce]] 内部槽的当前值。

  8. 设置request完整性元数据link 元素的 integrity 内容属性的当前值。

  9. 设置requestreferrer policylink 元素的 referrerpolicy 属性的为当前状态。

  10. 执行 链接资源获取配置步骤 并传入 elrequest。如果结果为 false 就返回。

  11. 并行地 执行以下步骤:

    1. response获取 request 的结果。

    2. success 为 true。

    3. 如果 response网络错误 或它的 状态 不是 OK, 这是 success 为 false。

      注意内容相关错误比如 CSS 解析错误或 PNG 解码错误不影响 success

    4. 如果 success 为 true,等待 链接资源关键子资源 结束加载。

      定义链接类型的 关键子资源 的标准(比如 CSS) 应该描述这些如何获取和处理这些子资源。本标准描述描述等待 链接资源关键子资源 获取和处理时,假设它得到了正确地处理。

    5. 网络任务源入队 一个元素为 el 的元素任务,用来 处理链接资源( 给它传入 elsuccessresponse)。

用户代理在需要这些资源时才会去 获取和处理, 而不是预先获取所有未应用的 外部资源

获取和处理链接资源 算法类似,所有 外部资源链接 都有对应的 处理链接资源 算法, 接受一个 link 元素 el,布尔值 success响应 response。 除非个别链接类型提供了它自己的 处理链接资源 算法, 就是用给定 link 元素 el 和布尔值 success (忽略 response)的 默认的处理链接资源 算法:

  1. 如果 success 为 true,在 el触发 名为 load 的事件。

  2. 否则,在 el触发 名为 error 的事件。

除非给定的 rel 关键字另有说明, 在获取该资源及其 关键子资源 的所有尝试完成之前, 必须 推迟 该元素的 节点文档 的 load 事件。 (用户代理还没尝试获取的资源不会 推迟 load 事件,比如因为它在等待需要的资源。)

如果支持 HTTP `Link` 协议头, 则必须假定它们在文档的 link 之前,按照在 HTTP 消息中的顺序到达。 这些头将会按照相关规范给出的规则进行处理。 [HTTP] [WEBLINK]

HTTP `Link` 中的关系类型注册 与 HTML link 类型 不同, 因此它们与同名 HTML 类型的语义也可能不同。

交互式的用户代理可能会在用户界面里为用户提供一种 跟随 使用 link 元素创建的超链接的方式。 本规范没有定义具体的界面,但是它可以对文档中每个由 link 元素创建的 hyperlink, 包含某种形式的(可能会被简化)以下信息(从元素的属性获取,下文有相应定义):

用户代理也可以包含其他信息,比如资源类型(由 type 属性给出)。

创建 超链接link 元素的 激活行为 就是如下步骤:

  1. 如果 link 元素的 节点文档 没有 完全激活,则中止这些步骤。

  2. 跟随link 元素创建的超链接。

4.2.5 meta 元素

Element/meta

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLMetaElement

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
类别
元数据内容
如果有 itemprop 属性: 流式内容
如果有 itemprop 属性: 短语内容
该元素可用的上下文
如果有 charset 属性,或者元素的 http-equiv 属性处于 编码声明状态:在 head 元素中。
如果有 http-equiv 属性但不在 编码声明状态:在 head 元素中。
如果有 http-equiv 属性但不在 编码声明状态:在 head 元素的 noscript 子元素中。
如果有 name 属性:期望 元数据内容 的地方。
如果有 itemprop 属性: 期望元数据内容 的地方。
如果有 itemprop 属性: 期望短语内容 的地方。
内容模型
text/html 中的标签省略
哪个标签都不能省略。
内容属性
全局属性
name — Metadata name
http-equiv — Pragma directive
content — Value of the element
charsetCharacter encoding declaration
DOM 接口
[HTMLConstructor]
interface HTMLMetaElement : HTMLElement {
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString httpEquiv;
  [CEReactions] attribute DOMString content;
};

meta 元素 表示 很多不能用 titlebaselinkstyle, 和 script 元素表达的元数据。

meta 元素可以通过 name 属性表示文档级别的元数据, 通过 http-equiv 属性表示编译指示, 通过 charset 属性表示 HTML 文档序列化为字符串时(例如用于网络传输或者磁盘存储时) 文件的 字符编码声明

必须指定这些属性中的一个:namehttp-equivcharset, 和 itemprop

如果指定了 namehttp-equiv, 或 itemprop,那么必须也指定 content 属性。 否则必须忽略它。

charset 属性指定了文档使用的字符编码。 这是一个 字符编码声明。如果在 XML 文档 上指定了该属性,其值必须 ASCII 大小写不敏感地 匹配 "utf-8" (且该文档必须使用 UTF-8 作为它的编码)。

meta 元素上 charset 属性 对 XML 文档不起作用,允许它只是为了方便与 XML 之间进行迁移。

每个文档必须存在不少于一个有 charset 属性的 meta 元素。

content 属性给出了文档元数据或编译指令的值。 允许的值取决于确切的上下文,见本规范的后续章节的描述。

如果 meta 元素有一个 name 属性, 它设置了文档元数据。文档元数据以 name-value 对表达,meta 元素的 name 属性给出了名字,同一元素的 content 属性 给出了值。名字指定了要设置哪方面的元数据;合法的名字连同它的值的含义在后续章节描述。 如果 meta 元素没有 content 属性,那么 name-value 对的值的部分是空字符串。

namecontent IDL 属性必须 反映 相应的同名内容属性。IDL 属性 httpEquiv 必须 反映 http-equiv 内容属性。

4.2.5.1 标准元数据名

本规范为 meta 元素的 name 属性定义了一些名字。

名字是大小写不敏感的,必须以 ASCII 大小写不敏感 的方式进行比较

application-name

值必须是一个简短的格式自由的字符串,给出本页面表示的 Web 应用的名字。 如果该页面不是一个 Web 应用,不得使用 application-name 元数据名。 必须使用 lang 属性来指定该 Web 应用的每个名字的语言。

给定一个 language,一个文档中不得有多个 name 属性设为 application-namemeta 元素。

用户代理可能会在 UI 中使用应用名来取代 title,因为标题可能包含某一特定时刻页面的状态信息。

为了从给定语言的应用名有序列表(比如 British English, American English, 和 English)中选取要用的应用名, 用户代理必须执行以下步骤:

  1. languages 为语言列表。

  2. default languageDocument文档元素语言,如果有并且那个语言不是未知的话。

  3. 如果有一个 default language, 并且如果它与 languages 中的语言都不同, 把它追加到 languages 上。

  4. winning languagelanguages 中的第一个满足这个条件的语言: 在 Document 中存在一个 name 属性设为 application-namelanguage 是那个语言的 meta 元素。

    如果所有语言都没有对应的 meta 元素,那么中止这些步骤;没有给定的应用名。

  5. 返回 content 属性的值。 Document按照树序 的第一个 name 属性为 application-namelanguagewinning languagemeta 元素。

浏览器需要页面名字时可能会使用本算法,比如设置书签的标签时。 提供给本算法的语言列表可能来自用户的偏好设置。

author

值必须是格式自由的字符串,给出了本页面的作者的名字。

description

值必须是描述本页面的格式自由的字符串,必须适合用于页面字典,例如搜索引擎。 每个文档中不得有多个 meta 元素的 name 属性设为 description

generator

值必须是一个表示用于产生该文档的软件包的格式自由的字符串。 这个值不得用于不是由软件产生的页面上,例如用户在文本编辑器上编写的页面。

这是一个名为 "Frontweaver" 的工具在页面 head 元素中的输出,来标识该页面是由它这个工具生成的:

<meta name=generator content="Frontweaver 8.2">
keywords

值必须是一个 逗号分隔的令牌集合, 其中每一项都是页面的关键字。

关于英国高速公路的字体的页面使用 meta 元素来指定一些关键字(用户可能用这些关键字来查找该页面):

<!DOCTYPE HTML>
<html lang="en-GB">
 <head>
  <title>Typefaces on UK motorways</title>
  <meta name="keywords" content="british,type face,font,fonts,highway,highways">
 </head>
 <body>
  ...

很多搜索引擎不会考虑这些关键字,因为该特性是不可靠的甚至会导致垃圾结果,对用户并没有帮助。

为了获得作者指定的关键字列表,用户代理必须执行以下步骤:

  1. keywords 为一个空列表。

  2. 对每一个 name 属性的值是 keywords, 且有一个 content 属性的 meta 元素:

    1. 用逗号 分割该元素的 content 属性的值

    2. 把得到的结果添加到 keywords,如果有的话。

  3. keywords 移除所有重复。

  4. 返回 keywords。这就是作者指定的页面关键字列表。

对值的可靠性没有足够的信心时,用户代理不应使用这一信息。

例如,内容管理系统可能会使用页面关键字来填充站内搜索引擎的索引, 但使用这一信息进行大规模的内容聚合时可能会发现某些用户会尝试利用不合适的关键字来对排序机制作弊。

referrer

值必须是 引荐策略, 它为 Document 定义了默认的 引荐策略[REFERRERPOLICY]

如果有 meta 元素 插入文档从文档中移除,或者现有的 meta 元素的 namecontent 属性变化, 用户代理必须执行以下算法:

  1. candidate elements 为所有符合以下条件的 meta 元素的列表,按照 树序 排列:

  2. candidate elements 中的每一个 element

    1. valueelementcontent 属性 转化为 ASCII 小写 后的值。

    2. 如果 value 的值属于下表中第一列,则设置 value 为第二列的值:

      遗留的值 引荐策略
      never no-referrer
      default no-referrer-when-downgrade
      always unsafe-url
      origin-when-crossorigin origin-when-cross-origin
    3. 如果 value 是一个 引荐策略, 则设置 element节点文档引荐策略policy

    对每个元素应用这些步骤使得 旧的用户代理仍然可以使用这些值[REFERRERPOLICY]

theme-color

Element/meta/name/theme-color

FirefoxNoSafari15+Chrome🔰 73+
OperaNoEdge🔰 79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS15+Chrome Android80+WebView AndroidNoSamsung Internet6.2+Opera AndroidNo

值必须是匹配 CSS <color> 生成式的字符串, 为用户代理定义了一个建议的颜色, 用来自定义该页面或周边 UI 的显示。例如,浏览器可能会用指定的颜色渲染页面的标题栏, 或者把它作为任标签栏或务栏的高亮颜色。

每个文档至少要有一个 meta 元素的 name 属性设为 theme-color

This standard itself uses "WHATWG green" as its theme color:

<!DOCTYPE HTML>
<title>HTML Standard</title>
<meta name="theme-color" content="#3c790a">
...

用户代理必须执行以下步骤来获取页面的主题颜色:

  1. candidate elements 为所有符合以下条件的 meta 元素, 按照 树序 排列:

  2. candidate elements 中每一个 element

    1. value 为把 elementcontent 属性的值 移除前后 ASCII 空白 后的结果。

    2. 如果 value 可以解析为 CSS 颜色值, 返回解析后的值。

  3. 如果到达了这一步,该页面没有主题颜色。

如果有任何 meta 元素 插入到文档中 或者 从文档中移除, 或者现有 meta 元素的 namecontent 属性发生了改变,用户代理必须重新执行以上算法,并应用所有影响 UI 的结果。

在 UI 中使用主题颜色时,用户代理可能会调整具体的实现细节。例如,如果用户代理要用主题色作背景在上面显示白色的文字, 则可能会在 UI 的这一部分使用主题颜色的较暗变体,以确保充分的对比度。

4.2.5.2 其他元数据名称

任何人都可以 对预定义元数据名称集的扩展, 创建和使用自己的元数据。而且无需注册此类扩展。

但是在以下任何情况下,都不应创建新的元数据名:

另外,在创建和使用新的元数据名称之前,建议查阅 WHATWG Wiki MetaExtensions 页面 — 来避免选择已经在使用的元数据名,以及与既有元数据名的用途冗余, 以及避免新标准化的名称与你选择的冲突。 [WHATWGWIKI]

任何人在任何时候都可以编辑 WHATWG Wiki MetaExtensions 页面,添加想要的元数据名称。 新的元数据名称可以用下列信息来说明:

关键字

要定义的实际名称。名称不应与任何其他定义的名称混淆相似(比如,仅区分大小写)。

简要说明

对这个元数据名称的含义的一个简短的非规范的描述,包括它的取值所需的格式。

规范
指向关于该元数据名称的语义和要求的更详细的描述的链接。它可以是 Wiki 上的另一页,也可以是一个外部页面。
同义词

具有完全相同的处理要求的其他名称的列表。 作者不应使用定义为同义词的名称(它们只是用于允许用户代理支持遗留内容)。 任何人都可以移除实践中不再使用的同义词;只有需要当做同义词做兼容处理的名称才能以这种方式注册。

状态

以下之一:

已提出
该名称还没有得到广泛的 peer review 和 approval。有人提出了它并且正在用或者现在或马上就要使用。
已批准
该名称已经接受了广泛的 peer review 和 approval。它有一个明确定义了如何处理使用该名称的页面的规范,包括当它们以不正确的方式使用该名称时。
已终止
该名称已经接受了广泛同行的 peer review 并且被认为是有用的。现有页面正在使用此元数据名称,但新页面应避免使用此名称。“简要说明”和“规范”条目将给出作者应该使用什么的细节,如果有的话。

如果一个元数据名称与其他现存的值冗余,那么应该把它移除并列为那个现存值的同义词。

如果一个元数据名称添加到 “已提议” 状态经过一个多月的时间并未被使用或标准化, 那么应该把它从 WHATWG Wiki MetaExtensions 页面移除。

如果一个元数据名称添加到 “已提议” 状态,并且发现与现存的值冗余, 就应该把它移除并列为该现存值的同义词。 如果一个名称被添加到 “已提议” 状态但被发现有害,则应该把它改为 “已终止” 状态。

任何人都可以随时更新状态,但应该根据上述定义进行更新。

4.2.5.3 Pragma directives

When the http-equiv attribute is specified on a meta element, the element is a pragma directive.

The http-equiv attribute is an enumerated attribute. The following table lists the keywords defined for this attribute. The states given in the first cell of the rows with keywords give the states to which those keywords map. Some of the keywords are non-conforming, as noted in the last column.

State Keyword Notes
Content Language content-language Non-conforming
Encoding declaration content-type
Default style default-style
Refresh refresh
Set-Cookie set-cookie Non-conforming
X-UA-Compatible x-ua-compatible
Content security policy content-security-policy

When a meta element is inserted into the document, if its http-equiv attribute is present and represents one of the above states, then the user agent must run the algorithm appropriate for that state, as described in the following list:

Content language state (http-equiv="content-language")

This feature is non-conforming. Authors are encouraged to use the lang attribute instead.

This pragma sets the pragma-set default language. Until such a pragma is successfully processed, there is no pragma-set default language.

  1. If the meta element has no content attribute, then return.

  2. If the element's content attribute contains a U+002C COMMA character (,) then return.

  3. Let input be the value of the element's content attribute.

  4. Let position point at the first character of input.

  5. Skip ASCII whitespace within input given position.

  6. Collect a sequence of code points that are not ASCII whitespace from input given position.

  7. Let candidate be the string that resulted from the previous step.

  8. If candidate is the empty string, return.

  9. Set the pragma-set default language to candidate.

    If the value consists of multiple space-separated tokens, tokens after the first are ignored.

This pragma is almost, but not quite, entirely unlike the HTTP `Content-Language` header of the same name. [HTTP]

Encoding declaration state (http-equiv="content-type")

The Encoding declaration state is just an alternative form of setting the charset attribute: it is a character encoding declaration. This state's user agent requirements are all handled by the parsing section of the specification.

For meta elements with an http-equiv attribute in the Encoding declaration state, the content attribute must have a value that is an ASCII case-insensitive match for a string that consists of: the literal string "text/html;", optionally followed by any number of ASCII whitespace, followed by the literal string "charset=utf-8".

A document must not contain both a meta element with an http-equiv attribute in the Encoding declaration state and a meta element with the charset attribute present.

The Encoding declaration state may be used in HTML documents, but elements with an http-equiv attribute in that state must not be used in XML documents.

Default style state (http-equiv="default-style")

This pragma sets the name of the default CSS style sheet set.

  1. If the meta element has no content attribute, or if that attribute's value is the empty string, then return.

  2. Change the preferred CSS style sheet set name with the name being the value of the element's content attribute. [CSSOM]

Refresh state (http-equiv="refresh")

This pragma acts as timed redirect.

A Document object has an associated will declaratively refresh (a boolean). It is initially false.

  1. If the meta element has no content attribute, or if that attribute's value is the empty string, then return.

  2. Let input be the value of the element's content attribute.

  3. Run the shared declarative refresh steps with the meta element's node document, input, and the meta element.

The shared declarative refresh steps, given a Document object document, string input, and optionally a meta element meta, are as follows:

  1. If document's will declaratively refresh is true, then return.

  2. Let position point at the first code point of input.

  3. Skip ASCII whitespace within input given position.

  4. Let time be 0.

  5. Collect a sequence of code points that are ASCII digits from input given position, and let the result be timeString.

  6. If timeString is the empty string, then:

    1. If the code point in input pointed to by position is not U+002E (.), then return.

  7. Otherwise, set time to the result of parsing timeString using the rules for parsing non-negative integers.

  8. Collect a sequence of code points that are ASCII digits and U+002E FULL STOP characters (.) from input given position. Ignore any collected characters.

  9. Let urlRecord be document's URL.

  10. If position is not past the end of input, then:

    1. If the code point in input pointed to by position is not U+003B (;), U+002C (,), or ASCII whitespace, then return.

    2. Skip ASCII whitespace within input given position.

    3. If the code point in input pointed to by position is U+003B (;) or U+002C (,), then advance position to the next code point.

    4. Skip ASCII whitespace within input given position.

  11. If position is not past the end of input, then:

    1. Let urlString be the substring of input from the code point at position to the end of the string.

    2. If the code point in input pointed to by position is U+0055 (U) or U+0075 (u), then advance position to the next code point. Otherwise, jump to the step labeled skip quotes.

    3. If the code point in input pointed to by position is U+0052 (R) or U+0072 (r), then advance position to the next code point. Otherwise, jump to the step labeled parse.

    4. If the code point in input pointed to by position is U+004C (L) or U+006C (l), then advance position to the next code point. Otherwise, jump to the step labeled parse.

    5. Skip ASCII whitespace within input given position.

    6. If the code point in input pointed to by position is U+003D (=), then advance position to the next code point. Otherwise, jump to the step labeled parse.

    7. Skip ASCII whitespace within input given position.

    8. Skip quotes: If the code point in input pointed to by position is U+0027 (') or U+0022 ("), then let quote be that code point, and advance position to the next code point. Otherwise, let quote be the empty string.

    9. Set urlString to the substring of input from the code point at position to the end of the string.

    10. If quote is not the empty string, and there is a code point in urlString equal to quote, then truncate urlString at that code point, so that it and all subsequent code points are removed.

    11. Parse: Parse urlString relative to document. If that fails, return. Otherwise, set urlRecord to the resulting URL record.

  12. Set document's will declaratively refresh to true.

  13. Perform one or more of the following steps:

    In addition, the user agent may, as with anything, inform the user of any and all aspects of its operation, including the state of any timers, the destinations of any timed redirects, and so forth.

For meta elements with an http-equiv attribute in the Refresh state, the content attribute must have a value consisting either of:

In the former case, the integer represents a number of seconds before the page is to be reloaded; in the latter case the integer represents a number of seconds before the page is to be replaced by the page at the given URL.

A news organization's front page could include the following markup in the page's head element, to ensure that the page automatically reloads from the server every five minutes:

<meta http-equiv="Refresh" content="300">

A sequence of pages could be used as an automated slide show by making each page refresh to the next page in the sequence, using markup such as the following:

<meta http-equiv="Refresh" content="20; URL=page4.html">
Set-Cookie state (http-equiv="set-cookie")

This pragma is non-conforming and has no effect.

User agents are required to ignore this pragma.

X-UA-Compatible state (http-equiv="x-ua-compatible")

In practice, this pragma encourages Internet Explorer to more closely follow the specifications.

For meta elements with an http-equiv attribute in the X-UA-Compatible state, the content attribute must have a value that is an ASCII case-insensitive match for the string "IE=edge".

User agents are required to ignore this pragma.

Content security policy state (http-equiv="content-security-policy")

This pragma enforces a Content Security Policy on a Document. [CSP]

  1. If the meta element is not a child of a head element, return.

  2. If the meta element has no content attribute, or if that attribute's value is the empty string, then return.

  3. Let policy be the result of executing Content Security Policy's parse a serialized Content Security Policy algorithm on the meta element's content attribute's value, with a source of "meta", and a disposition of "enforce".

  4. Remove all occurrences of the report-uri, frame-ancestors, and sandbox directives from policy.

  5. Enforce the policy policy.

For meta elements with an http-equiv attribute in the Content security policy state, the content attribute must have a value consisting of a valid Content Security Policy, but must not contain any report-uri, frame-ancestors, or sandbox directives. The Content Security Policy given in the content attribute will be enforced upon the current document. [CSP]

A page might choose to mitigate the risk of cross-site scripting attacks by preventing the execution of inline JavaScript, as well as blocking all plugin content, using a policy such as the following:

<meta http-equiv="Content-Security-Policy" content="script-src 'self'; object-src 'none'">

There must not be more than one meta element with any particular state in the document at a time.

4.2.5.4 Specifying the document's character encoding

A character encoding declaration is a mechanism by which the character encoding used to store or transmit a document is specified.

The Encoding standard requires use of the UTF-8 character encoding and requires use of the "utf-8" encoding label to identify it. Those requirements necessitate that the document's character encoding declaration, if it exists, specifies an encoding label using an ASCII case-insensitive match for "utf-8". Regardless of whether a character encoding declaration is present or not, the actual character encoding used to encode the document must be UTF-8. [ENCODING]

To enforce the above rules, authoring tools must default to using UTF-8 for newly-created documents.

The following restrictions also apply:

In addition, due to a number of restrictions on meta elements, there can only be one meta-based character encoding declaration per document.

If an HTML document does not start with a BOM, and its encoding is not explicitly given by Content-Type metadata, and the document is not an iframe srcdoc document, then the encoding must be specified using a meta element with a charset attribute or a meta element with an http-equiv attribute in the Encoding declaration state.

A character encoding declaration is required (either in the Content-Type metadata or explicitly in the file) even when all characters are in the ASCII range, because a character encoding is needed to process non-ASCII characters entered by the user in forms, in URLs generated by scripts, and so forth.

Using non-UTF-8 encodings can have unexpected results on form submission and URL encodings, which use the document's character encoding by default.

If the document is an iframe srcdoc document, the document must not have a character encoding declaration. (In this case, the source is already decoded, since it is part of the document that contained the iframe.)

In XML, the XML declaration should be used for inline character encoding information, if necessary.

In HTML, to declare that the character encoding is UTF-8, the author could include the following markup near the top of the document (in the head element):

<meta charset="utf-8">

In XML, the XML declaration would be used instead, at the very top of the markup:

<?xml version="1.0" encoding="utf-8"?>

4.2.6 The style element

Element/style

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3.5+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

HTMLStyleElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Metadata content.
Contexts in which this element can be used:
Where metadata content is expected.
In a noscript element that is a child of a head element.
Content model:
Text that gives a conformant style sheet.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
media — Applicable media
Also, the title attribute has special semantics on this element: CSS style sheet set name.
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLStyleElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString media;

  // also has obsolete members
};
HTMLStyleElement includes LinkStyle;

The style element allows authors to embed CSS style sheets in their documents. The style element is one of several inputs to the styling processing model. The element does not represent content for the user.

The media attribute says which media the styles apply to. The value must be a valid media query list. The user agent must apply the styles when the media attribute's value matches the environment and the other relevant conditions apply, and must not apply them otherwise.

The styles might be further limited in scope, e.g. in CSS with the use of @media blocks. This specification does not override such further restrictions or requirements.

The default, if the media attribute is omitted, is "all", meaning that by default styles apply to all media.

The title attribute on style elements defines CSS style sheet sets. If the style element has no title attribute, then it has no title; the title attribute of ancestors does not apply to the style element. If the style element is not in a document tree, then the title attribute is ignored. [CSSOM]

The title attribute on style elements, like the title attribute on link elements, differs from the global title attribute in that a style block without a title does not inherit the title of the parent element: it merely has no title.

The child text content of a style element must be that of a conformant style sheet.


The user agent must run the update a style block algorithm whenever one of the following conditions occur:

The update a style block algorithm is as follows:

  1. Let element be the style element.

  2. If element has an associated CSS style sheet, remove the CSS style sheet in question.

  3. If element's root is neither a shadow root nor a document, then return.

  4. If element's type attribute is present and its value is neither the empty string nor an ASCII case-insensitive match for "text/css", then return.

    In particular, a type value with parameters, such as "text/css; charset=utf-8", will cause this algorithm to return early.

  5. If the Should element's inline behavior be blocked by Content Security Policy? algorithm returns "Blocked" when executed upon the style element, "style", and the style element's child text content, then return. [CSP]

  6. Create a CSS style sheet with the following properties:

    type

    text/css

    owner node

    element

    media

    The media attribute of element.

    This is a reference to the (possibly absent at this time) attribute, rather than a copy of the attribute's current value. CSSOM defines what happens when the attribute is dynamically set, changed, or removed.

    title

    The title attribute of element, if element is in a document tree, or the empty string otherwise.

    Again, this is a reference to the attribute.

    alternate flag

    Unset.

    origin-clean flag

    Set.

    location
    parent CSS style sheet
    owner CSS rule

    null

    disabled flag

    Left at its default value.

    CSS rules

    Left uninitialized.

    This doesn't seem right. Presumably we should be using the element's child text content? Tracked as issue #2997.

Once the attempts to obtain the style sheet's critical subresources, if any, are complete, or, if the style sheet has no critical subresources, once the style sheet has been parsed and processed, the user agent must run these steps:

  1. Let element be the style element associated with the style sheet in question.

  2. Let success be true.

  3. If the attempts to obtain any of the style sheet's critical subresources failed for any reason (e.g., DNS error, HTTP 404 response, a connection being prematurely closed, unsupported Content-Type), set success to false.

    Note that content-specific errors, e.g., CSS parse errors or PNG decoding errors, do not affect success.

  4. Queue an element task on the networking task source given element and the following steps:

    1. If success is true, fire an event named load at element.

    2. Otherwise, fire an event named error at element.

    3. If element contributes a script-blocking style sheet:

      1. Assert: element's node document's script-blocking style sheet counter is greater than 0.

      2. Decrement element's node document's script-blocking style sheet counter by 1.

The element must delay the load event of the element's node document until all the attempts to obtain the style sheet's critical subresources, if any, are complete.

This specification does not specify a style system, but CSS is expected to be supported by most web browsers. [CSS]

HTMLStyleElement/media

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The media IDL attribute must reflect the content attribute of the same name.

The LinkStyle interface is also implemented by this element. [CSSOM]

The following document has its stress emphasis styled as bright red text rather than italics text, while leaving titles of works and Latin words in their default italics. It shows how using appropriate elements enables easier restyling of documents.

<!DOCTYPE html>
<html lang="en-US">
 <head>
  <title>My favorite book</title>
  <style>
   body { color: black; background: white; }
   em { font-style: normal; color: red; }
  </style>
 </head>
 <body>
  <p>My <em>favorite</em> book of all time has <em>got</em> to be
  <cite>A Cat's Life</cite>. It is a book by P. Rahmel that talks
  about the <i lang="la">Felis Catus</i> in modern human society.</p>
 </body>
</html>

4.2.7 Interactions of styling and scripting

If the style sheet referenced no other resources (e.g., it was an internal style sheet given by a style element with no @import rules), then the style rules must be immediately made available to script; otherwise, the style rules must only be made available to script once the event loop reaches its update the rendering step.

An element el in the context of a Document of an HTML parser or XML parser contributes a script-blocking style sheet if all of the following conditions are true:

It is expected that counterparts to the above rules also apply to <?xml-stylesheet?> PIs and HTTP `Link` headers. However, this has not yet been thoroughly investigated.

A Document has a script-blocking style sheet counter, which is a number, initially 0.

A Document has a style sheet that is blocking scripts if its script-blocking style sheet counter is greater than 0, or if that Document has a non-null browsing context whose container document is non-null and has a script-blocking style sheet counter greater than 0.

A Document has no style sheet that is blocking scripts if it does not have a style sheet that is blocking scripts as defined in the previous paragraph.

4.3 Section

4.3.1 The body element

Element/body

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome Android18+WebView AndroidYesSamsung Internet1.0+Opera AndroidYes

HTMLBodyElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Sectioning root.
Contexts in which this element can be used:
As the second element in an html element.
Content model:
Flow content.
text/html 中的标签省略
A body element's start tag can be omitted if the element is empty, or if the first thing inside the body element is not ASCII whitespace or a comment, except if the first thing inside the body element is a meta, link, script, style, or template element.
A body element's end tag can be omitted if the body element is not immediately followed by a comment.
Content attributes:
Global attributes
onafterprint
onbeforeprint
onbeforeunload
onhashchange
onlanguagechange
onmessage
onmessageerror
onoffline
ononline
onpagehide
onpageshow
onpopstate
onrejectionhandled
onstorage
onunhandledrejection
onunload
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLBodyElement : HTMLElement {
  [HTMLConstructor] constructor();

  // also has obsolete members
};

HTMLBodyElement includes WindowEventHandlers;

The body element represents the contents of the document.

In conforming documents, there is only one body element. The document.body IDL attribute provides scripts with easy access to a document's body element.

Some DOM operations (for example, parts of the drag and drop model) are defined in terms of "the body element". This refers to a particular element in the DOM, as per the definition of the term, and not any arbitrary body element.

The body element exposes as event handler content attributes a number of the event handlers of the Window object. It also mirrors their event handler IDL attributes.

The event handlers of the Window object named by the Window-reflecting body element event handler set, exposed on the body element, replace the generic event handlers with the same names normally supported by HTML elements.

Thus, for example, a bubbling error event dispatched on a child of the body element of a Document would first trigger the onerror event handler content attributes of that element, then that of the root html element, and only then would it trigger the onerror event handler content attribute on the body element. This is because the event would bubble from the target, to the body, to the html, to the Document, to the Window, and the event handler on the body is watching the Window not the body. A regular event listener attached to the body using addEventListener(), however, would be run when the event bubbled through the body and not when it reaches the Window object.

This page updates an indicator to show whether or not the user is online:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Online or offline?</title>
  <script>
   function update(online) {
     document.getElementById('status').textContent =
       online ? 'Online' : 'Offline';
   }
  </script>
 </head>
 <body ononline="update(true)"
       onoffline="update(false)"
       onload="update(navigator.onLine)">
  <p>You are: <span id="status">(Unknown)</span></p>
 </body>
</html>

4.3.2 The article element

Element/article

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS4.2+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android11.1+
Categories:
Flow content.
Sectioning content.
Palpable content.
Contexts in which this element can be used:
Where sectioning content is expected.
Content model:
Flow content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The article element represents a complete, or self-contained, composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

When article elements are nested, the inner article elements represent articles that are in principle related to the contents of the outer article. For instance, a blog entry on a site that accepts user-submitted comments could represent the comments as article elements nested within the article element for the blog entry.

Author information associated with an article element (q.v. the address element) does not apply to nested article elements.

When used specifically with content to be redistributed in syndication, the article element is similar in purpose to the entry element in Atom. [ATOM]

The schema.org microdata vocabulary can be used to provide the publication date for an article element, using one of the CreativeWork subtypes.

When the main content of the page (i.e. excluding footers, headers, navigation blocks, and sidebars) is all one single self-contained composition, that content may be marked with an article, but it is technically redundant in that case (since it's self-evident that the page is a single composition, as it is a single document).

This example shows a blog post using the article element, with some schema.org annotations:

<article itemscope itemtype="http://schema.org/BlogPosting">
 <header>
  <h1 itemprop="headline">The Very First Rule of Life</h1>
  <p><time itemprop="datePublished" datetime="2009-10-09">3 days ago</time></p>
  <link itemprop="url" href="?comments=0">
 </header>
 <p>If there's a microphone anywhere near you, assume it's hot and
 sending whatever you're saying to the world. Seriously.</p>
 <p>...</p>
 <footer>
  <a itemprop="discussionUrl" href="?comments=1">Show comments...</a>
 </footer>
</article>

Here is that same blog post, but showing some of the comments:

<article itemscope itemtype="http://schema.org/BlogPosting">
 <header>
  <h1 itemprop="headline">The Very First Rule of Life</h1>
  <p><time itemprop="datePublished" datetime="2009-10-09">3 days ago</time></p>
  <link itemprop="url" href="?comments=0">
 </header>
 <p>If there's a microphone anywhere near you, assume it's hot and
 sending whatever you're saying to the world. Seriously.</p>
 <p>...</p>
 <section>
  <h1>Comments</h1>
  <article itemprop="comment" itemscope itemtype="http://schema.org/UserComments" id="c1">
   <link itemprop="url" href="#c1">
   <footer>
    <p>Posted by: <span itemprop="creator" itemscope itemtype="http://schema.org/Person">
     <span itemprop="name">George Washington</span>
    </span></p>
    <p><time itemprop="commentTime" datetime="2009-10-10">15 minutes ago</time></p>
   </footer>
   <p>Yeah! Especially when talking about your lobbyist friends!</p>
  </article>
  <article itemprop="comment" itemscope itemtype="http://schema.org/UserComments" id="c2">
   <link itemprop="url" href="#c2">
   <footer>
    <p>Posted by: <span itemprop="creator" itemscope itemtype="http://schema.org/Person">
     <span itemprop="name">George Hammond</span>
    </span></p>
    <p><time itemprop="commentTime" datetime="2009-10-10">5 minutes ago</time></p>
   </footer>
   <p>Hey, you have the same first name as me.</p>
  </article>
 </section>
</article>

Notice the use of footer to give the information for each comment (such as who wrote it and when): the footer element can appear at the start of its section when appropriate, such as in this case. (Using header in this case wouldn't be wrong either; it's mostly a matter of authoring preference.)

In this example, article elements are used to host widgets on a portal page. The widgets are implemented as customized built-in elements in order to get specific styling and scripted behavior.

<!DOCTYPE HTML>
<html lang=en>
<title>eHome Portal</title>
<script src="/scripts/widgets.js"></script>
<link rel=stylesheet href="/styles/main.css">
<article is="stock-widget">
 <h1>Stocks</h1>
 <table>
  <thead> <tr> <th> Stock <th> Value <th> Delta
  <tbody> <template> <tr> <td> <td> <td> </template>
 </table>
 <p> <input type=button value="Refresh" onclick="this.parentElement.refresh()">
</article>
<article is="news-widget">
 <h1>News</h1>
 <ul>
  <template>
   <li>
    <p><img> <strong></strong>
    <p>
  </template>
 </ul>
 <p> <input type=button value="Refresh" onclick="this.parentElement.refresh()">
</article>

4.3.3 The section element

Element/section

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS4.2+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android11.1+
Categories:
Flow content.
Sectioning content.
Palpable content.
Contexts in which this element can be used:
Where sectioning content is expected.
Content model:
Flow content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.

Examples of sections would be chapters, the various tabbed pages in a tabbed dialog box, or the numbered sections of a thesis. A web site's home page could be split into sections for an introduction, news items, and contact information.

Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element.

The section element is not a generic container element. When an element is needed only for styling purposes or as a convenience for scripting, authors are encouraged to use the div element instead. A general rule is that the section element is appropriate only if the element's contents would be listed explicitly in the document's outline.

In the following example, we see an article (part of a larger web page) about apples, containing two short sections.

<article>
 <hgroup>
  <h1>Apples</h1>
  <h2>Tasty, delicious fruit!</h2>
 </hgroup>
 <p>The apple is the pomaceous fruit of the apple tree.</p>
 <section>
  <h1>Red Delicious</h1>
  <p>These bright red apples are the most common found in many
  supermarkets.</p>
 </section>
 <section>
  <h1>Granny Smith</h1>
  <p>These juicy, green apples make a great filling for
  apple pies.</p>
 </section>
</article>

Notice how the use of section means that the author can use h1 elements throughout, without having to worry about whether a particular section is at the top level, the second level, the third level, and so on.

Here is a graduation programme with two sections, one for the list of people graduating, and one for the description of the ceremony. (The markup in this example features an uncommon style sometimes used to minimize the amount of inter-element whitespace.)

<!DOCTYPE Html>
<Html Lang=En
 ><Head
   ><Title
     >Graduation Ceremony Summer 2022</Title
   ></Head
 ><Body
   ><H1
     >Graduation</H1
   ><Section
     ><H1
       >Ceremony</H1
     ><P
       >Opening Procession</P
     ><P
       >Speech by Validactorian</P
     ><P
       >Speech by Class President</P
     ><P
       >Presentation of Diplomas</P
     ><P
       >Closing Speech by Headmaster</P
   ></Section
   ><Section
     ><H1
       >Graduates</H1
     ><Ul
       ><Li
         >Molly Carpenter</Li
       ><Li
         >Anastasia Luccio</Li
       ><Li
         >Ebenezar McCoy</Li
       ><Li
         >Karrin Murphy</Li
       ><Li
         >Thomas Raith</Li
       ><Li
         >Susan Rodriguez</Li
     ></Ul
   ></Section
 ></Body
></Html>

In this example, a book author has marked up some sections as chapters and some as appendices, and uses CSS to style the headers in these two classes of section differently.

<style>
 section { border: double medium; margin: 2em; }
 section.chapter h1 { font: 2em Roboto, Helvetica Neue, sans-serif; }
 section.appendix h1 { font: small-caps 2em Roboto, Helvetica Neue, sans-serif; }
</style>
<header>
 <hgroup>
  <h1>My Book</h1>
  <h2>A sample with not much content</h2>
 </hgroup>
 <p><small>Published by Dummy Publicorp Ltd.</small></p>
</header>
<section class="chapter">
 <h1>My First Chapter</h1>
 <p>This is the first of my chapters. It doesn't say much.</p>
 <p>But it has two paragraphs!</p>
</section>
<section class="chapter">
 <h1>It Continues: The Second Chapter</h1>
 <p>Bla dee bla, dee bla dee bla. Boom.</p>
</section>
<section class="chapter">
 <h1>Chapter Three: A Further Example</h1>
 <p>It's not like a battle between brightness and earthtones would go
 unnoticed.</p>
 <p>But it might ruin my story.</p>
</section>
<section class="appendix">
 <h1>Appendix A: Overview of Examples</h1>
 <p>These are demonstrations.</p>
</section>
<section class="appendix">
 <h1>Appendix B: Some Closing Remarks</h1>
 <p>Hopefully this long example shows that you <em>can</em> style
 sections, so long as they are used to indicate actual sections.</p>
</section>

4.3.4 The nav element

Element/nav

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS4.2+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android11.1+
Categories:
Flow content.
Sectioning content.
Palpable content.
Contexts in which this element can be used:
Where sectioning content is expected.
Content model:
Flow content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The nav element represents a section of a page that links to other pages or to parts within the page: a section with navigation links.

Not all groups of links on a page need to be in a nav element — the element is primarily intended for sections that consist of major navigation blocks. In particular, it is common for footers to have a short list of links to various pages of a site, such as the terms of service, the home page, and a copyright page. The footer element alone is sufficient for such cases; while a nav element can be used in such cases, it is usually unnecessary.

User agents (such as screen readers) that are targeted at users who can benefit from navigation information being omitted in the initial rendering, or who can benefit from navigation information being immediately available, can use this element as a way to determine what content on the page to initially skip or provide on request (or both).

In the following example, there are two nav elements, one for primary navigation around the site, and one for secondary navigation around the page itself.

<body>
 <h1>The Wiki Center Of Exampland</h1>
 <nav>
  <ul>
   <li><a href="/">Home</a></li>
   <li><a href="/events">Current Events</a></li>
   ...more...
  </ul>
 </nav>
 <article>
  <header>
   <h1>Demos in Exampland</h1>
   <p>Written by A. N. Other.</p>
  </header>
  <nav>
   <ul>
    <li><a href="#public">Public demonstrations</a></li>
    <li><a href="#destroy">Demolitions</a></li>
    ...more...
   </ul>
  </nav>
  <div>
   <section id="public">
    <h1>Public demonstrations</h1>
    <p>...more...</p>
   </section>
   <section id="destroy">
    <h1>Demolitions</h1>
    <p>...more...</p>
   </section>
   ...more...
  </div>
  <footer>
   <p><a href="?edit">Edit</a> | <a href="?delete">Delete</a> | <a href="?Rename">Rename</a></p>
  </footer>
 </article>
 <footer>
  <p><small>© copyright 1998 Exampland Emperor</small></p>
 </footer>
</body>

In the following example, the page has several places where links are present, but only one of those places is considered a navigation section.

<body itemscope itemtype="http://schema.org/Blog">
 <header>
  <h1>Wake up sheeple!</h1>
  <p><a href="news.html">News</a> -
     <a href="blog.html">Blog</a> -
     <a href="forums.html">Forums</a></p>
  <p>Last Modified: <span itemprop="dateModified">2009-04-01</span></p>
  <nav>
   <h1>Navigation</h1>
   <ul>
    <li><a href="articles.html">Index of all articles</a></li>
    <li><a href="today.html">Things sheeple need to wake up for today</a></li>
    <li><a href="successes.html">Sheeple we have managed to wake</a></li>
   </ul>
  </nav>
 </header>
 <main>
  <article itemprop="blogPosts" itemscope itemtype="http://schema.org/BlogPosting">
   <header>
    <h1 itemprop="headline">My Day at the Beach</h1>
   </header>
   <div itemprop="articleBody">
    <p>Today I went to the beach and had a lot of fun.</p>
    ...more content...
   </div>
   <footer>
    <p>Posted <time itemprop="datePublished" datetime="2009-10-10">Thursday</time>.</p>
   </footer>
  </article>
  ...more blog posts...
 </main>
 <footer>
  <p>Copyright ©
   <span itemprop="copyrightYear">2010</span>
   <span itemprop="copyrightHolder">The Example Company</span>
  </p>
  <p><a href="about.html">About</a> -
     <a href="policy.html">Privacy Policy</a> -
     <a href="contact.html">Contact Us</a></p>
 </footer>
</body>

You can also see microdata annotations in the above example that use the schema.org vocabulary to provide the publication date and other metadata about the blog post.

A nav element doesn't have to contain a list, it can contain other kinds of content as well. In this navigation block, links are provided in prose:

<nav>
 <h1>Navigation</h1>
 <p>You are on my home page. To the north lies <a href="/blog">my
 blog</a>, from whence the sounds of battle can be heard. To the east
 you can see a large mountain, upon which many <a
 href="/school">school papers</a> are littered. Far up thus mountain
 you can spy a little figure who appears to be me, desperately
 scribbling a <a href="/school/thesis">thesis</a>.</p>
 <p>To the west are several exits. One fun-looking exit is labeled <a
 href="https://games.example.com/">"games"</a>. Another more
 boring-looking exit is labeled <a
 href="https://isp.example.net/">ISP™</a>.</p>
 <p>To the south lies a dark and dank <a href="/about">contacts
 page</a>. Cobwebs cover its disused entrance, and at one point you
 see a rat run quickly out of the page.</p>
</nav>

In this example, nav is used in an email application, to let the user switch folders:

<p><input type=button value="Compose" onclick="compose()"></p>
<nav>
 <h1>Folders</h1>
 <ul>
  <li> <a href="/inbox" onclick="return openFolder(this.href)">Inbox</a> <span class=count></span>
  <li> <a href="/sent" onclick="return openFolder(this.href)">Sent</a>
  <li> <a href="/drafts" onclick="return openFolder(this.href)">Drafts</a>
  <li> <a href="/trash" onclick="return openFolder(this.href)">Trash</a>
  <li> <a href="/customers" onclick="return openFolder(this.href)">Customers</a>
 </ul>
</nav>

4.3.5 The aside element

Element/aside

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS4.2+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android11.1+
Categories:
Flow content.
Sectioning content.
Palpable content.
Contexts in which this element can be used:
Where sectioning content is expected.
Content model:
Flow content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The aside element represents a section of a page that consists of content that is tangentially related to the content around the aside element, and which could be considered separate from that content. Such sections are often represented as sidebars in printed typography.

The element can be used for typographical effects like pull quotes or sidebars, for advertising, for groups of nav elements, and for other content that is considered separate from the main content of the page.

It's not appropriate to use the aside element just for parentheticals, since those are part of the main flow of the document.

The following example shows how an aside is used to mark up background material on Switzerland in a much longer news story on Europe.

<aside>
 <h1>Switzerland</h1>
 <p>Switzerland, a land-locked country in the middle of geographic
 Europe, has not joined the geopolitical European Union, though it is
 a signatory to a number of European treaties.</p>
</aside>

The following example shows how an aside is used to mark up a pull quote in a longer article.

...

<p>He later joined a large company, continuing on the same work.
<q>I love my job. People ask me what I do for fun when I'm not at
work. But I'm paid to do my hobby, so I never know what to
answer. Some people wonder what they would do if they didn't have to
work... but I know what I would do, because I was unemployed for a
year, and I filled that time doing exactly what I do now.</q></p>

<aside>
 <q> People ask me what I do for fun when I'm not at work. But I'm
 paid to do my hobby, so I never know what to answer. </q>
</aside>

<p>Of course his work — or should that be hobby? —
isn't his only passion. He also enjoys other pleasures.</p>

...

The following extract shows how aside can be used for blogrolls and other side content on a blog:

<body>
 <header>
  <h1>My wonderful blog</h1>
  <p>My tagline</p>
 </header>
 <aside>
  <!-- this aside contains two sections that are tangentially related
  to the page, namely, links to other blogs, and links to blog posts
  from this blog -->
  <nav>
   <h1>My blogroll</h1>
   <ul>
    <li><a href="https://blog.example.com/">Example Blog</a>
   </ul>
  </nav>
  <nav>
   <h1>Archives</h1>
   <ol reversed>
    <li><a href="/last-post">My last post</a>
    <li><a href="/first-post">My first post</a>
   </ol>
  </nav>
 </aside>
 <aside>
  <!-- this aside is tangentially related to the page also, it
  contains twitter messages from the blog author -->
  <h1>Twitter Feed</h1>
  <blockquote cite="https://twitter.example.net/t31351234">
   I'm on vacation, writing my blog.
  </blockquote>
  <blockquote cite="https://twitter.example.net/t31219752">
   I'm going to go on vacation soon.
  </blockquote>
 </aside>
 <article>
  <!-- this is a blog post -->
  <h1>My last post</h1>
  <p>This is my last post.</p>
  <footer>
   <p><a href="/last-post" rel=bookmark>Permalink</a>
  </footer>
 </article>
 <article>
  <!-- this is also a blog post -->
  <h1>My first post</h1>
  <p>This is my first post.</p>
  <aside>
   <!-- this aside is about the blog post, since it's inside the
   <article> element; it would be wrong, for instance, to put the
   blogroll here, since the blogroll isn't really related to this post
   specifically, only to the page as a whole -->
   <h1>Posting</h1>
   <p>While I'm thinking about it, I wanted to say something about
   posting. Posting is fun!</p>
  </aside>
  <footer>
   <p><a href="/first-post" rel=bookmark>Permalink</a>
  </footer>
 </article>
 <footer>
  <p><a href="/archives">Archives</a> -
   <a href="/about">About me</a> -
   <a href="/copyright">Copyright</a></p>
 </footer>
</body>

4.3.6 The h1, h2, h3, h4, h5, and h6 elements

Element/Heading_Elements

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Element/Heading_Elements

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Element/Heading_Elements

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Element/Heading_Elements

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Element/Heading_Elements

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Element/Heading_Elements

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLHeadingElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Heading content.
Palpable content.
Contexts in which this element can be used:
As a child of an hgroup element.
Where heading content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLHeadingElement : HTMLElement {
  [HTMLConstructor] constructor();

  // also has obsolete members
};

These elements represent headings for their sections.

The semantics and meaning of these elements are defined in the section on headings and sections.

These elements have a rank given by the number in their name. The h1 element is said to have the highest rank, the h6 element has the lowest rank, and two elements with the same name have equal rank.

As far as their respective document outlines (their heading and section structures) are concerned, these two snippets are semantically equivalent:

<body>
<h1>Let's call it a draw(ing surface)</h1>
<h2>Diving in</h2>
<h2>Simple shapes</h2>
<h2>Canvas coordinates</h2>
<h3>Canvas coordinates diagram</h3>
<h2>Paths</h2>
</body>
<body>
 <h1>Let's call it a draw(ing surface)</h1>
 <section>
  <h1>Diving in</h1>
 </section>
 <section>
  <h1>Simple shapes</h1>
 </section>
 <section>
  <h1>Canvas coordinates</h1>
  <section>
   <h1>Canvas coordinates diagram</h1>
  </section>
 </section>
 <section>
  <h1>Paths</h1>
 </section>
</body>

Authors might prefer the former style for its terseness, or the latter style for its convenience in the face of heavy editing; which is best is purely an issue of preferred authoring style.

The two styles can be combined, for compatibility with legacy tools while still future-proofing for when that compatibility is no longer needed. This third snippet again has the same outline as the previous two:

<body>
 <h1>Let's call it a draw(ing surface)</h1>
 <section>
  <h2>Diving in</h2>
 </section>
 <section>
  <h2>Simple shapes</h2>
 </section>
 <section>
  <h2>Canvas coordinates</h2>
  <section>
   <h3>Canvas coordinates diagram</h3>
  </section>
 </section>
 <section>
  <h2>Paths</h2>
 </section>
</body>

4.3.7 The hgroup element

Element/hgroup

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS4.2+Chrome AndroidYesWebView Android2.2+Samsung InternetYesOpera Android11.1+
Categories:
Flow content.
Heading content.
Palpable content.
Contexts in which this element can be used:
Where heading content is expected.
Content model:
One or more h1, h2, h3, h4, h5, h6 elements, optionally intermixed with script-supporting elements.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The hgroup element represents the heading of a section, which consists of all the h1h6 element children of the hgroup element. The element is used to group a set of h1h6 elements when the heading has multiple levels, such as subheadings, alternative titles, or taglines.

The rank of an hgroup element is the rank of the highest-ranked h1h6 element descendant of the hgroup element, if there are any such elements, or otherwise the same as for an h1 element (the highest rank). Other h1h6 elements of heading content in the hgroup element indicate subheadings or subtitles or (secondary) alternative titles.

The section on headings and sections defines how hgroup elements are assigned to individual sections.

Here are some examples of valid headings.

<hgroup>
 <h1>The reality dysfunction</h1>
 <h2>Space is not the only void</h2>
</hgroup>
<hgroup>
 <h1>Dr. Strangelove</h1>
 <h2>Or: How I Learned to Stop Worrying and Love the Bomb</h2>
</hgroup>

The point of using hgroup in these examples is to prevent the h2 element (which acts as a secondary title) from creating a separate section of its own in any outline and to instead cause the contents of the h2 to be shown in rendered output from the outline algorithm in some way to indicate that it is not the title of a separate section but instead just a secondary title in a group of titles.

How a user agent exposes such multi-level headings in user interfaces (e.g. in tables of contents or search results) is left open to implementers, as it is a user interface issue. The first example above could be rendered as:

The reality dysfunction: Space is not the only void

Alternatively, it could look like this:

The reality dysfunction (Space is not the only void)

In interfaces where a title can be rendered on multiple lines, it could be rendered as follows, maybe with the first line in a bigger font size:

The reality dysfunction
Space is not the only void

The following two examples show ways in which two h1 headings could be used within an hgroup element to group the US and UK names for the same movie.

<hgroup>
 <h1>The Avengers</h1>
 <h1>Avengers Assemble</h1>
</hgroup>

<hgroup>
 <h1>Avengers Assemble</h1>
 <h1>The Avengers</h1>
</hgroup>

The first example above shows how the movie names might be grouped in a publication in the US, with the US name The Avengers as the (primary) title, and the UK name Avengers Assemble as the (secondary) alternative title. The second example above shows how the movie names might be grouped in a publication in the UK, with the UK name as the (primary) title, and the US name as the (secondary) alternative title.

In both cases it is important to note the use of the hgroup element to group the two titles indicates that the titles are not equivalent; instead the first h1 gives the (primary) title while the second gives the (secondary) alternative title. Even though both the title and alternative title are marked up with h1 elements, in a rendered view of output from the outline algorithm, the second h1 in the hgroup will be shown in some way that clearly indicates it is secondary; for example:

In a US publication:

The Avengers (Avengers Assemble)

In a UK publication:

Avengers Assemble (The Avengers)

In the following example, an hgroup element is used to mark up a two-level heading in a wizard-style dialog box:

<dialog onclose="walletSetup.continue(this.returnValue)">
 <hgroup>
  <h1>Wallet Setup</h1>
  <h2>Configure your Wallet funding source</h2>
 </hgroup>
 <p>Your Wallet can be used to buy wands at the merchant in town, to buy potions from travelling
 salesmen you may find in the dungeons, and to pay for mercenaries.</p>
 <p>We support two payment sources:</p>
 <form method=dialog>
  <fieldset oninput="this.getElementsByTagName('input')[0].checked = true">
   <legend> <label> <input type=radio name=payment-type value=cc> Credit Card </label> </legend>
   <p><label>Name on card: <input name=cc1 autocomplete="section-cc cc-name" placeholder="Y. Name"></label>
   <p><label>Card number: <input name=cc2 inputmode=numeric autocomplete="section-cc cc-number" placeholder="6331 1019 9999 0016"></label>
   <p><label>Expiry Date: <input name=cc3 type=month autocomplete="section-cc cc-exp" placeholder="2020-02"></label>
   <p><label>Security Code: <input name=cc4 inputmode=numeric autocomplete="section-cc cc-csc" placeholder="246"></label>
  </fieldset>
  <fieldset oninput="this.getElementsByTagName('input')[0].checked = true">
   <legend> <label> <input type=radio name=payment-type value=bank> Checking Account </label> </legend>
   <p><label>Name on account: <input name=bank1 autocomplete="section-bank cc-name"></label>
   <p><label>Routing number: <input name=bank2 inputmode=numeric></label>
   <p><label>Account number: <input name=bank3 inputmode=numeric></label>
  </fieldset>
  <button type=submit value="back"> ← Back </button>
  <button type=submit value="next"> Next → </button>
 </form>
</dialog>

4.3.8 The header element

Element/header

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS4.2+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android11.1+
Categories:
Flow content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Flow content, but with no header or footer element descendants.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
If the nearest ancestor sectioning content or sectioning root element is the body element: for authors; for implementers.
Otherwise: for authors; for implementers.
DOM interface:
Uses HTMLElement.

The header element represents a group of introductory or navigational aids.

A header element is intended to usually contain the section's heading (an h1h6 element or an hgroup element), but this is not required. The header element can also be used to wrap a section's table of contents, a search form, or any relevant logos.

Here are some sample headers. This first one is for a game:

<header>
 <p>Welcome to...</p>
 <h1>Voidwars!</h1>
</header>

The following snippet shows how the element can be used to mark up a specification's header:

<header>
 <hgroup>
  <h1>Fullscreen API</h1>
  <h2>Living Standard — Last Updated 19 October 2015</h2>
 </hgroup>
 <dl>
  <dt>Participate:</dt>
  <dd><a href="https://github.com/whatwg/fullscreen">GitHub whatwg/fullscreen</a></dd>
  <dt>Commits:</dt>
  <dd><a href="https://github.com/whatwg/fullscreen/commits">GitHub whatwg/fullscreen/commits</a></dd>
 </dl>
</header>

The header element is not sectioning content; it doesn't introduce a new section.

In this example, the page has a page heading given by the h1 element, and two subsections whose headings are given by h2 elements. The content after the header element is still part of the last subsection started in the header element, because the header element doesn't take part in the outline algorithm.

<body>
 <header>
  <h1>Little Green Guys With Guns</h1>
  <nav>
   <ul>
    <li><a href="/games">Games</a>
    <li><a href="/forum">Forum</a>
    <li><a href="/download">Download</a>
   </ul>
  </nav>
  <h2>Important News</h2> <!-- this starts a second subsection -->
  <!-- this is part of the subsection entitled "Important News" -->
  <p>To play today's games you will need to update your client.</p>
  <h2>Games</h2> <!-- this starts a third subsection -->
 </header>
 <p>You have three active games:</p>
 <!-- this is still part of the subsection entitled "Games" -->
 ...

Element/footer

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS4.2+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android11.1+
Categories:
Flow content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Flow content, but with no header or footer element descendants.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
If the nearest ancestor sectioning content or sectioning root element is the body element: for authors; for implementers.
Otherwise: for authors; for implementers.
DOM interface:
Uses HTMLElement.

The footer element represents a footer for its nearest ancestor sectioning content or sectioning root element. A footer typically contains information about its section such as who wrote it, links to related documents, copyright data, and the like.

When the footer element contains entire sections, they represent appendices, indexes, long colophons, verbose license agreements, and other such content.

Contact information for the author or editor of a section belongs in an address element, possibly itself inside a footer. Bylines and other information that could be suitable for both a header or a footer can be placed in either (or neither). The primary purpose of these elements is merely to help the author write self-explanatory markup that is easy to maintain and style; they are not intended to impose specific structures on authors.

Footers don't necessarily have to appear at the end of a section, though they usually do.

When the nearest ancestor sectioning content or sectioning root element is the body element, then it applies to the whole page.

The footer element is not sectioning content; it doesn't introduce a new section.

Here is a page with two footers, one at the top and one at the bottom, with the same content:

<body>
 <footer><a href="../">Back to index...</a></footer>
 <hgroup>
  <h1>Lorem ipsum</h1>
  <h2>The ipsum of all lorems</h2>
 </hgroup>
 <p>A dolor sit amet, consectetur adipisicing elit, sed do eiusmod
 tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
 veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
 ea commodo consequat. Duis aute irure dolor in reprehenderit in
 voluptate velit esse cillum dolore eu fugiat nulla
 pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
 culpa qui officia deserunt mollit anim id est laborum.</p>
 <footer><a href="../">Back to index...</a></footer>
</body>

Here is an example which shows the footer element being used both for a site-wide footer and for a section footer.

<!DOCTYPE HTML>
<HTML LANG="en"><HEAD>
<TITLE>The Ramblings of a Scientist</TITLE>
<BODY>
<H1>The Ramblings of a Scientist</H1>
<ARTICLE>
 <H1>Episode 15</H1>
 <VIDEO SRC="/fm/015.ogv" CONTROLS PRELOAD>
  <P><A HREF="/fm/015.ogv">Download video</A>.</P>
 </VIDEO>
 <FOOTER> <!-- footer for article -->
  <P>Published <TIME DATETIME="2009-10-21T18:26-07:00">on 2009/10/21 at 6:26pm</TIME></P>
 </FOOTER>
</ARTICLE>
<ARTICLE>
 <H1>My Favorite Trains</H1>
 <P>I love my trains. My favorite train of all time is a Köf.</P>
 <P>It is fun to see them pull some coal cars because they look so
 dwarfed in comparison.</P>
 <FOOTER> <!-- footer for article -->
  <P>Published <TIME DATETIME="2009-09-15T14:54-07:00">on 2009/09/15 at 2:54pm</TIME></P>
 </FOOTER>
</ARTICLE>
<FOOTER> <!-- site wide footer -->
 <NAV>
  <P><A HREF="/credits.html">Credits</A> —
     <A HREF="/tos.html">Terms of Service</A> —
     <A HREF="/index.html">Blog Index</A></P>
 </NAV>
 <P>Copyright © 2009 Gordon Freeman</P>
</FOOTER>
</BODY>
</HTML>

Some site designs have what is sometimes referred to as "fat footers" — footers that contain a lot of material, including images, links to other articles, links to pages for sending feedback, special offers... in some ways, a whole "front page" in the footer.

This fragment shows the bottom of a page on a site with a "fat footer":

...
 <footer>
  <nav>
   <section>
    <h1>Articles</h1>
    <p><img src="images/somersaults.jpeg" alt=""> Go to the gym with
    our somersaults class! Our teacher Jim takes you through the paces
    in this two-part article. <a href="articles/somersaults/1">Part
    1</a> · <a href="articles/somersaults/2">Part 2</a></p>
    <p><img src="images/kindplus.jpeg"> Tired of walking on the edge of
    a clif<!-- sic -->? Our guest writer Lara shows you how to bumble
    your way through the bars. <a href="articles/kindplus/1">Read
    more...</a></p>
    <p><img src="images/crisps.jpeg"> The chips are down, now all
    that's left is a potato. What can you do with it? <a
    href="articles/crisps/1">Read more...</a></p>
   </section>
   <ul>
    <li> <a href="/about">About us...</a>
    <li> <a href="/feedback">Send feedback!</a>
    <li> <a href="/sitemap">Sitemap</a>
   </ul>
  </nav>
  <p><small>Copyright © 2015 The Snacker —
  <a href="/tos">Terms of Service</a></small></p>
 </footer>
</body>

4.3.10 The address element

Element/address

Support in all current engines.

Firefox1+Safari1+ChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Flow content, but with no heading content descendants, no sectioning content descendants, and no header, footer, or address element descendants.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The address element represents the contact information for its nearest article or body element ancestor. If that is the body element, then the contact information applies to the document as a whole.

For example, a page at the W3C web site related to HTML might include the following contact information:

<ADDRESS>
 <A href="../People/Raggett/">Dave Raggett</A>,
 <A href="../People/Arnaud/">Arnaud Le Hors</A>,
 contact persons for the <A href="Activity">W3C HTML Activity</A>
</ADDRESS>

The address element must not be used to represent arbitrary addresses (e.g. postal addresses), unless those addresses are in fact the relevant contact information. (The p element is the appropriate element for marking up postal addresses in general.)

The address element must not contain information other than contact information.

For example, the following is non-conforming use of the address element:

<ADDRESS>Last Modified: 1999/12/24 23:37:50</ADDRESS>

Typically, the address element would be included along with other information in a footer element.

The contact information for a node node is a collection of address elements defined by the first applicable entry from the following list:

If node is an article element
If node is a body element

The contact information consists of all the address elements that have node as an ancestor and do not have another body or article element ancestor that is a descendant of node.

If node has an ancestor element that is an article element
If node has an ancestor element that is a body element

The contact information of node is the same as the contact information of the nearest article or body element ancestor, whichever is nearest.

If node's node document has a body element

The contact information of node is the same as the contact information of the body element of the Document.

Otherwise

There is no contact information for node.

User agents may expose the contact information of a node to the user, or use it for other purposes, such as indexing sections based on the sections' contact information.

In this example the footer contains contact information and a copyright notice.

<footer>
 <address>
  For more details, contact
  <a href="mailto:js@example.com">John Smith</a>.
 </address>
 <p><small>© copyright 2038 Example Corp.</small></p>
</footer>

4.3.11 标题和章节

h1h6 元素和 hgroup 元素是标题。

章节内容 元素中的第一个 标题内容 元素 表示着 那个章节的标题。 后续同样 级别 或更高级别的标题(默认)开启新的章节, 更低 级别 的标题默认开启前述章节的子章节。 两种场景中标题元素都 表示 那个默认章节的标题。

某些元素称为 章节根, 包括 blockquotetd 元素。 这些元素可以有自己的目录结构,但这些元素内的章节和标题不会形成它们祖先节点的目录结构。

章节内容 元素总是被视为 最近的祖先 章节根元素 的章节, 或者最近的祖先 章节内容 元素的章节。 这里只要最近的,不论是否属于其他标题默认创建的章节。

对下面的片段:

<body>
 <h1>Foo</h1>
 <h2>Bar</h2>
 <blockquote>
  <h3>Bla</h3>
 </blockquote>
 <p>Baz</p>
 <h2>Quux</h2>
 <section>
  <h3>Thud</h3>
 </section>
 <p>Grunt</p>
</body>

结构可能是:

  1. Foo (显式 body 章节的标题,包含 "Grunt" 一段)
    1. Bar (这个标题默认创建了章节,来包含一个引用块和 "Baz" 一段)
    2. Quux (这个标题默认创建了一个没有其他内容的章节,标题除外)
    3. Thud (显式 section 章节的标题)

注意上述 section 结束了前一个隐式创建的章节, 这样后续的段落("Grunt")重新回到了顶级。

章节可以包含任何 级别 的标题, 但强烈建议作者或者只用 h1 元素, 或者使用与章节的嵌套级别相应 级别 的标题元素。

也强烈建议作者在 章节内容 的元素上显式地包装一个章节元素, 而不是在同一个 章节内容 元素内写多个标题并依赖隐式的章节生成。

例如,下面的片段是正确的:

<body>
 <h4>Apples</h4>
 <p>Apples are fruit.</p>
 <section>
  <h2>Taste</h2>
  <p>They taste lovely.</p>
  <h6>Sweet</h6>
  <p>Red apples are sweeter than green ones.</p>
  <h1>Color</h1>
  <p>Apples come in various colors.</p>
 </section>
</body>

然而同一个文档可以更清晰地表达为:

<body>
 <h1>Apples</h1>
 <p>Apples are fruit.</p>
 <section>
  <h2>Taste</h2>
  <p>They taste lovely.</p>
  <section>
   <h3>Sweet</h3>
   <p>Red apples are sweeter than green ones.</p>
  </section>
 </section>
 <section>
  <h2>Color</h2>
  <p>Apples come in various colors.</p>
 </section>
</body>

上述两个文档语义上等价,而且在兼容的用户代理上会产生同样的目录结构。

下面第三个例子语义上也是等价的,可能更容易维护 (例如,如果在编辑中经常移动章节的话):

<body>
 <h1>Apples</h1>
 <p>Apples are fruit.</p>
 <section>
  <h1>Taste</h1>
  <p>They taste lovely.</p>
  <section>
   <h1>Sweet</h1>
   <p>Red apples are sweeter than green ones.</p>
  </section>
 </section>
 <section>
  <h1>Color</h1>
  <p>Apples come in various colors.</p>
 </section>
</body>

这最后一个例子可能需要加一些显式的样式规则才能在旧浏览器中很好地呈现。 没有 CSS 支持的旧浏览器会把所有标题渲染成顶级标题。

4.3.11.1 Creating an outline

This section defines an algorithm for creating an outline for a sectioning content element or a sectioning root element. It is defined in terms of a walk over the nodes of a DOM tree, in tree order, with each node being visited when it is entered and when it is exited during the walk.

The outline for a sectioning content element or a sectioning root element consists of a list of one or more potentially nested sections. The element for which an outline is created is said to be the outline's owner.

A section is a container that corresponds to some nodes in the original DOM tree. Each section can have one heading associated with it, and can contain any number of further nested sections. The algorithm for the outline also associates each node in the DOM tree with a particular section and potentially a heading. (The sections in the outline aren't section elements, though some may correspond to such elements — they are merely conceptual sections.)

The following markup fragment:

<body>
  <hgroup id="document-title">
    <h1>HTML</h1>
    <h2>Living Standard — Last Updated 12 August 2016</h2>
  </hgroup>
  <p>Some intro to the document.</p>
  <h2>Table of contents</h2>
  <ol id=toc>...</ol>
  <h2>First section</h2>
  <p>Some intro to the first section.</p>
</body>

...results in the following outline being created for the body node (and thus the entire document):

  1. Section created for body node.

    Associated with heading <hgroup id="document-title">...</hgroup> consisting of primary heading <h1>HTML</h1> and secondary heading <h2>Living Standard — Last Updated 12 August 2016</h2>.

    Also associated with the paragraph <p>Some intro to the document.</p> (though it likely would not be shown in a rendered view of the outline).

    Nested sections:

    1. Section implied for first h2 element.

      Associated with heading <h2>Table of contents</h2>.

      Also associated with the ordered list <ol id=toc>...</ol> (though it likely would not be shown in a rendered view of the outline).

      No nested sections.

    2. Section implied for second h2 element.

      Associated with heading <h2>First section</h2>.

      Also associated with the paragraph <p>Some intro to the first section.</p> (though it likely would not be shown in a rendered view of the outline).

      No nested sections.

The following image shows what a rendered view of the outline might look like.

Top-level section with the
   multi-level heading "HTML: Living Standard — Last Updated 12 August 2016" and two
   subsections; "Table of contents" and "First section".

The algorithm that must be followed during a walk of a DOM subtree rooted at a sectioning content element or a sectioning root element to determine that element's outline is as follows:

  1. Let current outline target be null. (It holds the element whose outline is being created.)

  2. Let current section be null. (It holds a pointer to a section, so that elements in the DOM can all be associated with a section.)

  3. Create a stack to hold elements, which is used to handle nesting. Initialize this stack to empty.

  4. Walk over the DOM in tree order, starting with the sectioning content element or sectioning root element at the root of the subtree for which an outline is to be created, and trigger the first relevant step below for each element as the walk enters and exits it.

    When exiting an element, if that element is the element at the top of the stack

    The element being exited is a heading content element or an element with a hidden attribute.

    Pop that element from the stack.

    If the top of the stack is a heading content element or an element with a hidden attribute

    Do nothing.

    When entering an element with a hidden attribute

    Push the element being entered onto the stack. (This causes the algorithm to skip that element and any descendants of the element.)

    When entering a sectioning content element

    Run these steps:

    1. If current outline target is not null, then:

      1. If the current section has no heading, create an implied heading and let that be the heading for the current section.

      2. Push current outline target onto the stack.

    2. Let current outline target be the element that is being entered.

    3. Let current section be a newly created section for the current outline target element.

    4. Associate current outline target with current section.

    5. Let there be a new outline for the new current outline target, initialized with just the new current section as the only section in the outline.

    When exiting a sectioning content element, if the stack is not empty

    Run these steps:

    1. If the current section has no heading, create an implied heading and let that be the heading for the current section.

    2. Pop the top element from the stack, and let the current outline target be that element.

    3. Let current section be the last section in the outline of the current outline target element.

    4. Append the outline of the sectioning content element being exited to the current section. (This does not change which section is the last section in the outline.)

    When entering a sectioning root element

    Run these steps:

    1. If current outline target is not null, push current outline target onto the stack.

    2. Let current outline target be the element that is being entered.

    3. Let current outline target's parent section be current section.

    4. Let current section be a newly created section for the current outline target element.

    5. Let there be a new outline for the new current outline target, initialized with just the new current section as the only section in the outline.

    When exiting a sectioning root element, if the stack is not empty

    Run these steps:

    1. If the current section has no heading, create an implied heading and let that be the heading for the current section.

    2. Let current section be current outline target's parent section.

    3. Pop the top element from the stack, and let the current outline target be that element.

    When exiting a sectioning content element or a sectioning root element (when the stack is empty)

    The current outline target is the element being exited, and it is the sectioning content element or a sectioning root element at the root of the subtree for which an outline is being generated.

    If the current section has no heading, create an implied heading and let that be the heading for the current section.

    Skip to the next step in the overall set of steps. (The walk is over.)

    When entering a heading content element

    If the current section has no heading, let the element being entered be the heading for the current section.

    If the element being entered is an hgroup element, that hgroup as a whole is a multi-level heading for the current section, with the highest-ranked h1h6 descendant of the hgroup providing the primary heading for the current section, and with other h1h6 descendants of the hgroup providing secondary headings for the current section.

    Otherwise, if the element being entered has a rank equal to or higher than the heading of the last section of the outline of the current outline target, or if the heading of the last section of the outline of the current outline target is an implied heading, then create a new section and append it to the outline of the current outline target element, so that this new section is the new last section of that outline. Let current section be that new section. Let the element being entered be the new heading for the current section.

    Otherwise, run these substeps:

    1. Let candidate section be current section.

    2. Heading loop: If the element being entered has a rank lower than the rank of the heading of the candidate section, then create a new section, and append it to candidate section. (This does not change which section is the last section in the outline.) Let current section be this new section. Let the element being entered be the new heading for the current section. Abort these substeps.

    3. Let new candidate section be the section that contains candidate section in the outline of current outline target.

    4. Let candidate section be new candidate section.

    5. Return to the step labeled heading loop.

    Push the element being entered onto the stack. (This causes the algorithm to skip any descendants of the element.)

    Recall that h1 has the highest rank, and h6 has the lowest rank.

    Otherwise

    Do nothing.

    In addition, whenever the walk exits a node, after doing the steps above, if the node is not associated with a section yet, associate the node with the section current section.

  5. Associate all non-element nodes that are in the subtree for which an outline is being created with the section with which their parent element is associated.

  6. Associate all nodes in the subtree with the heading of the section with which they are associated, if any.

The tree of sections created by the algorithm above, or a proper subset thereof, must be used when generating document outlines, for example when generating tables of contents.

The outline created for the body element of a Document is the outline of the entire document.

When creating an interactive table of contents, entries should jump the user to the relevant sectioning content element, if the section was created for a real element in the original document, or to the relevant heading content element, if the section in the tree was generated for a heading in the above process.

Selecting the first section of the document therefore always takes the user to the top of the document, regardless of where the first heading in the body is to be found.

The outline depth of a heading content element associated with a section section is the number of sections that are ancestors of section in the outermost outline that section finds itself in when the outlines of its Document's elements are created, plus 1. The outline depth of a heading content element not associated with a section is 1.

User agents should provide default headings for sections that do not have explicit section headings.

Consider the following snippet:

<body>
 <nav>
  <p><a href="/">Home</a></p>
 </nav>
 <p>Hello world.</p>
 <aside>
  <p>My cat is cute.</p>
 </aside>
</body>

Although it contains no headings, this snippet has three sections: a document (the body) with two subsections (a nav and an aside). A user agent could present the outline as follows:

  1. Untitled document
    1. Navigation
    2. Sidebar

These default headings ("Untitled document", "Navigation", "Sidebar") are not specified by this specification, and might vary with the user's language, the page's language, the user's preferences, the user agent implementer's preferences, etc.

The following JavaScript function shows how the tree walk could be implemented. The root argument is the root of the tree to walk (either a sectioning content element or a sectioning root element), and the enter and exit arguments are callbacks that are called with the nodes as they are entered and exited. [JAVASCRIPT]

function (root, enter, exit) {
  var node = root;
  start: while (node) {
    enter(node);
    if (node.firstChild) {
      node = node.firstChild;
      continue start;
    }
    while (node) {
      exit(node);
      if (node == root) {
        node = null;
      } else if (node.nextSibling) {
        node = node.nextSibling;
        continue start;
      } else {
        node = node.parentNode;
      }
    }
  }
}
4.3.11.2 Sample outlines

This section is non-normative.

The following document shows a straight-forward application of the outline algorithm. First, here is the document, which is a book with very short chapters and subsections:

<!DOCTYPE HTML>
<html lang=en>
<title>The Tax Book (all in one page)</title>
<h1>The Tax Book</h1>
<h2>Earning money</h2>
<p>Earning money is good.</p>
<h3>Getting a job</h3>
<p>To earn money you typically need a job.</p>
<h2>Spending money</h2>
<p>Spending is what money is mainly used for.</p>
<h3>Cheap things</h3>
<p>Buying cheap things often not cost-effective.</p>
<h3>Expensive things</h3>
<p>The most expensive thing is often not the most cost-effective either.</p>
<h2>Investing money</h2>
<p>You can lend your money to other people.</p>
<h2>Losing money</h2>
<p>If you spend money or invest money, sooner or later you will lose money.
<h3>Poor judgement</h3>
<p>Usually if you lose money it's because you made a mistake.</p>

This book would form the following outline:

  1. The Tax Book
    1. Earning money
      1. Getting a job
    2. Spending money
      1. Cheap things
      2. Expensive things
    3. Investing money
    4. Losing money
      1. Poor judgement

Notice that the title element does not participate in the outline.

Here is a similar document, but this time using section elements to get the same effect:

<!DOCTYPE HTML>
<html lang=en>
<title>The Tax Book (all in one page)</title>
<h1>The Tax Book</h1>
<section>
 <h1>Earning money</h1>
 <p>Earning money is good.</p>
 <section>
  <h1>Getting a job</h1>
  <p>To earn money you typically need a job.</p>
 </section>
</section>
<section>
 <h1>Spending money</h1>
 <p>Spending is what money is mainly used for.</p>
 <section>
  <h1>Cheap things</h1>
  <p>Buying cheap things often not cost-effective.</p>
 </section>
 <section>
  <h1>Expensive things</h1>
  <p>The most expensive thing is often not the most cost-effective either.</p>
 </section>
</section>
<section>
 <h1>Investing money</h1>
 <p>You can lend your money to other people.</p>
</section>
<section>
 <h1>Losing money</h1>
 <p>If you spend money or invest money, sooner or later you will lose money.
 <section>
  <h1>Poor judgement</h1>
  <p>Usually if you lose money it's because you made a mistake.</p>
 </section>
</section>

This book would form the same outline:

  1. The Tax Book
    1. Earning money
      1. Getting a job
    2. Spending money
      1. Cheap things
      2. Expensive things
    3. Investing money
    4. Losing money
      1. Poor judgement

A document can contain multiple top-level headings:

<!DOCTYPE HTML>
<html lang=en>
<title>Alphabetic Fruit</title>
<h1>Apples</h1>
<p>Pomaceous.</p>
<h1>Bananas</h1>
<p>Edible.</p>
<h1>Carambola</h1>
<p>Star.</p>

This would form the following simple outline consisting of three top-level sections:

  1. Apples
  2. Bananas
  3. Carambola

Effectively, the body element is split into three.

Mixing both the h1h6 model and the section/h1 model can lead to some unintuitive results.

Consider for example the following, which is just the previous example but with the contents of the (implied) body wrapped in a section:

<!DOCTYPE HTML>
<html lang=en>
<title>Alphabetic Fruit</title>
<section>
 <h1>Apples</h1>
 <p>Pomaceous.</p>
 <h1>Bananas</h1>
 <p>Edible.</p>
 <h1>Carambola</h1>
 <p>Star.</p>
</section>

The resulting outline would be:

  1. (untitled page)
    1. Apples
    2. Bananas
    3. Carambola

This result is described as unintuitive because it results in three subsections even though there's only one section element. Effectively, the section is split into three, just like the implied body element in the previous example.

(In this example, "(untitled page)" is the implied heading for the body element, since it has no explicit heading.)

Headings never rise above other sections. Thus, in the following example, the first h1 does not actually describe the page header; it describes the header for the second half of the page:

<!DOCTYPE HTML>
<html lang=en>
<title>Feathers on The Site of Encyclopedic Knowledge</title>
<section>
 <h1>A plea from our caretakers</h1>
 <p>Please, we beg of you, send help! We're stuck in the server room!</p>
</section>
<h1>Feathers</h1>
<p>Epidermal growths.</p>

The resulting outline would be:

  1. (untitled page)
    1. A plea from our caretakers
  2. Feathers

Thus, when an article element starts with a nav block and only later has its heading, the result is that the nav block is not part of the same section as the rest of the article in the outline. For instance, take this document:

<!DOCTYPE HTML>
<html lang="en">
<title>We're adopting a child! — Ray's blog</title>
<h1>Ray's blog</h1>
<article>
 <header>
  <nav>
   <a href="?t=-1d">Yesterday</a>;
   <a href="?t=-7d">Last week</a>;
   <a href="?t=-1m">Last month</a>
  </nav>
  <h1>We're adopting a child!</h1>
 </header>
 <p>As of today, Janine and I have signed the papers to become
 the proud parents of baby Diane! We've been looking forward to
 this day for weeks.</p>
</article>
</html>

The resulting outline would be:

  1. Ray's blog
    1. Untitled article
      1. Untitled navigation section
    2. We're adopting a child!

Also worthy of note in this example is that the header element has no effect whatsoever on the document outline.

The hgroup element can be used for subheadings. For example:

<!DOCTYPE HTML>
<html lang="en">
<title>Chronotype: CS Student</title>
<hgroup>
 <h1> The morning </h1>
 <h2> 06:00 to 12:00 </h2>
</hgroup>
<p>We sleep.</p>
<hgroup>
 <h1> The afternoon </h1>
 <h2> 12:00 to 18:00 </h2>
</hgroup>
<p>We study.</p>
<hgroup>
 <h2>Additional Commentary</h2>
 <h3>Because not all this is necessarily true</h3>
 <h6>Ok it's almost certainly not true</h6>
</hgroup>
<p>Yeah we probably play, rather than study.</p>
<hgroup>
 <h1> The evening </h1>
 <h2> 18:00 to 00:00 </h2>
</hgroup>
<p>We play.</p>
<hgroup>
 <h1> The night </h1>
 <h2> 00:00 to 06:00 </h2>
</hgroup>
<p>We play some more.</p>
</html>

The resulting outline would be:

  1. The morning 06:00 to 12:00
  2. The afternoon 12:00 to 18:00
    1. Additional Commentary Because not all this is necessarily true Ok it's almost certainly not true
  3. The evening 18:00 to 00:00
  4. The night 00:00 to 06:00

Exactly how this is represented by user agents, as most interface issues, is left as a matter of implementation preference, but the key part is that the hgroup's descendant h1h6 elements are what form the element's heading. Thus, the following would be equally valid:

  1. The morning — 06:00 to 12:00
  2. The afternoon — 12:00 to 18:00
    1. Additional Commentary — Because not all this is necessarily true — Ok it's almost certainly not true
  3. The evening — 18:00 to 00:00
  4. The night — 00:00 to 06:00

But so would the following:

  1. The morning
  2. The afternoon
    1. Additional Commentary
  3. The evening
  4. The night

The following would also be valid, though maybe less practical in most contexts:

  1. The morning

    06:00 to 12:00

  2. The afternoon

    12:00 to 18:00

    1. Additional Commentary

      Because not all this is necessarily true

      Ok it's almost certainly not true

  3. The evening

    18:00 to 00:00

  4. The night

    00:00 to 06:00

4.3.11.3 暴露目录给用户

鼓励用户代理暴露页面目录结构给用户以帮助导航,这在非视觉媒体中尤其重要。比如屏幕阅读器。

但是为了减轻作者误用 章节内容 造成的麻烦,也鼓励用户代理提供一种只用 标题内容 来导航的模式。

例如,用户代理可以给箭头键做这些映射:

Shift+← Left
回到上一个章节,包括上一个章节的子章节
Shift+→ Right
跳到下一个章节,包括当前章节的子章节
Shift+↑ Up
跳到当前章节的父章节
Shift+↓ Down
跳到下一个章节,跳过当前章节的子章节

此外,用户代理还可以把 jk 键映射为导航到上一个/下一个 标题内容 的元素, 无论章节的目录深度并忽略没有标题的章节。

4.3.12 Usage summary

This section is non-normative.

Element Purpose
Example
body The contents of the document.
<!DOCTYPE HTML>
<html lang="en">
 <head> <title>Steve Hill's Home Page</title> </head>
 <body> <p>Hard Trance is My Life.</p> </body>
</html>
article A complete, or self-contained, composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.
<article>
 <img src="/tumblr_masqy2s5yn1rzfqbpo1_500.jpg" alt="Yellow smiley face with the caption 'masif'">
 <p>My fave Masif tee so far!</p>
 <footer>Posted 2 days ago</footer>
</article>
<article>
 <img src="/tumblr_m9tf6wSr6W1rzfqbpo1_500.jpg" alt="">
 <p>Happy 2nd birthday Masif Saturdays!!!</p>
 <footer>Posted 3 weeks ago</footer>
</article>
section A generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.
<h1>Biography</h1>
<section>
 <h1>The facts</h1>
 <p>1500+ shows, 14+ countries</p>
</section>
<section>
 <h1>2010/2011 figures per year</h1>
 <p>100+ shows, 8+ countries</p>
</section>
nav A section of a page that links to other pages or to parts within the page: a section with navigation links.
<nav>
 <p><a href="/">Home</a>
 <p><a href="/biog.html">Bio</a>
 <p><a href="/discog.html">Discog</a>
</nav>
aside A section of a page that consists of content that is tangentially related to the content around the aside element, and which could be considered separate from that content. Such sections are often represented as sidebars in printed typography.
<h1>Music</h1>
<p>As any burner can tell you, the event has a lot of trance.</p>
<aside>You can buy the music we played at our <a href="buy.html">playlist page</a>.</aside>
<p>This year we played a kind of trance that originated in Belgium, Germany, and the Netherlands in the mid 90s.</p>
h1h6 A section heading
<h1>The Guide To Music On The Playa</h1>
<h2>The Main Stage</h2>
<p>If you want to play on a stage, you should bring one.</p>
<h2>Amplified Music</h2>
<p>Amplifiers up to 300W or 90dB are welcome.</p>
hgroup The heading of a section, which consists of all the h1h6 element children of the hgroup element. The element is used to group a set of h1h6 elements when the heading has multiple levels, such as subheadings, alternative titles, or taglines.
<hgroup>
 <h1>Burning Music</h1>
 <h2>The Guide To Music On The Playa</h2>
</hgroup>
<section>
 <hgroup>
  <h1>Main Stage</h1>
  <h2>The Fiction Of A Music Festival</h2>
 </hgroup>
 <p>If you want to play on a stage, you should bring one.</p>
</section>
<section>
 <hgroup>
  <h1>Loudness!</h1>
  <h2>Questions About Amplified Music</h2>
 </hgroup>
 <p>Amplifiers up to 300W or 90dB are welcome.</p>
</section>
header A group of introductory or navigational aids.
<article>
 <header>
  <h1>Hard Trance is My Life</h1>
  <p>By DJ Steve Hill and Technikal</p>
 </header>
 <p>The album with the amusing punctuation has red artwork.</p>
</article>
footer A footer for its nearest ancestor sectioning content or sectioning root element. A footer typically contains information about its section such as who wrote it, links to related documents, copyright data, and the like.
<article>
 <h1>Hard Trance is My Life</h1>
 <p>The album with the amusing punctuation has red artwork.</p>
 <footer>
  <p>Artists: DJ Steve Hill and Technikal</p>
 </footer>
</article>
4.3.12.1 使用 article 还是 section?

This section is non-normative.

一个 section 是其他内容的一部分。一个 article 就是它自己。 但是怎么知道哪个是哪个?大多数情况下真正的答案“取决于作者的意图”。

例如,人们可以想象一本书有一章叫做“Granny Smith”,它只写了: “These juicy, green apples make a great filling for apple pies.”; 这就是一个 section,因为可能会有很多其他章节来介绍其他类型的苹果。

另一方面,人们也可以想象一条推文,Reddit 评论,Tumblr 文章,或报纸分类广告, 只是说“Granny Smith. These juicy, green apples make a great filling for apple pies.”; 那么它就可以成为一个 article,因为这就是整个事情。

article 的评论不是文章的一部分,因此它是它自己的 article

4.4 Grouping content

4.4.1 The p element

Element/p

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLParagraphElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
A p element's end tag can be omitted if the p element is immediately followed by an address, article, aside, blockquote, details, div, dl, fieldset, figcaption, figure, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, hr, main, menu, nav, ol, p, pre, section, table, or ul element, or if there is no more content in the parent element and the parent element is an HTML element that is not an a, audio, del, ins, map, noscript, or video element, or an autonomous custom element.
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLParagraphElement : HTMLElement {
  [HTMLConstructor] constructor();

  // also has obsolete members
};

The p element represents a paragraph.

While paragraphs are usually represented in visual media by blocks of text that are physically separated from adjacent blocks through blank lines, a style sheet or user agent would be equally justified in presenting paragraph breaks in a different manner, for instance using inline pilcrows (¶).

The following examples are conforming HTML fragments:

<p>The little kitten gently seated herself on a piece of
carpet. Later in her life, this would be referred to as the time the
cat sat on the mat.</p>
<fieldset>
 <legend>Personal information</legend>
 <p>
   <label>Name: <input name="n"></label>
   <label><input name="anon" type="checkbox"> Hide from other users</label>
 </p>
 <p><label>Address: <textarea name="a"></textarea></label></p>
</fieldset>
<p>There was once an example from Femley,<br>
Whose markup was of dubious quality.<br>
The validator complained,<br>
So the author was pained,<br>
To move the error from the markup to the rhyming.</p>

The p element should not be used when a more specific element is more appropriate.

The following example is technically correct:

<section>
 <!-- ... -->
 <p>Last modified: 2001-04-23</p>
 <p>Author: fred@example.com</p>
</section>

However, it would be better marked-up as:

<section>
 <!-- ... -->
 <footer>Last modified: 2001-04-23</footer>
 <address>Author: fred@example.com</address>
</section>

Or:

<section>
 <!-- ... -->
 <footer>
  <p>Last modified: 2001-04-23</p>
  <address>Author: fred@example.com</address>
 </footer>
</section>

List elements (in particular, ol and ul elements) cannot be children of p elements. When a sentence contains a bulleted list, therefore, one might wonder how it should be marked up.

For instance, this fantastic sentence has bullets relating to

and is further discussed below.

The solution is to realize that a paragraph, in HTML terms, is not a logical concept, but a structural one. In the fantastic example above, there are actually five paragraphs as defined by this specification: one before the list, one for each bullet, and one after the list.

The markup for the above example could therefore be:

<p>For instance, this fantastic sentence has bullets relating to</p>
<ul>
 <li>wizards,
 <li>faster-than-light travel, and
 <li>telepathy,
</ul>
<p>and is further discussed below.</p>

Authors wishing to conveniently style such "logical" paragraphs consisting of multiple "structural" paragraphs can use the div element instead of the p element.

Thus for instance the above example could become the following:

<div>For instance, this fantastic sentence has bullets relating to
<ul>
 <li>wizards,
 <li>faster-than-light travel, and
 <li>telepathy,
</ul>
and is further discussed below.</div>

This example still has five structural paragraphs, but now the author can style just the div instead of having to consider each part of the example separately.

4.4.2 The hr element

Element/hr

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLHRElement

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Nothing.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLHRElement : HTMLElement {
  [HTMLConstructor] constructor();

  // also has obsolete members
};

The hr element represents a paragraph-level thematic break, e.g. a scene change in a story, or a transition to another topic within a section of a reference book.

The following fictional extract from a project manual shows two sections that use the hr element to separate topics within the section.

<section>
 <h1>Communication</h1>
 <p>There are various methods of communication. This section
 covers a few of the important ones used by the project.</p>
 <hr>
 <p>Communication stones seem to come in pairs and have mysterious
 properties:</p>
 <ul>
  <li>They can transfer thoughts in two directions once activated
  if used alone.</li>
  <li>If used with another device, they can transfer one's
  consciousness to another body.</li>
  <li>If both stones are used with another device, the
  consciousnesses switch bodies.</li>
 </ul>
 <hr>
 <p>Radios use the electromagnetic spectrum in the meter range and
 longer.</p>
 <hr>
 <p>Signal flares use the electromagnetic spectrum in the
 nanometer range.</p>
</section>
<section>
 <h1>Food</h1>
 <p>All food at the project is rationed:</p>
 <dl>
  <dt>Potatoes</dt>
  <dd>Two per day</dd>
  <dt>Soup</dt>
  <dd>One bowl per day</dd>
 </dl>
 <hr>
 <p>Cooking is done by the chefs on a set rotation.</p>
</section>

There is no need for an hr element between the sections themselves, since the section elements and the h1 elements imply thematic changes themselves.

The following extract from Pandora's Star by Peter F. Hamilton shows two paragraphs that precede a scene change and the paragraph that follows it. The scene change, represented in the printed book by a gap containing a solitary centered star between the second and third paragraphs, is here represented using the hr element.

<p>Dudley was ninety-two, in his second life, and fast approaching
time for another rejuvenation. Despite his body having the physical
age of a standard fifty-year-old, the prospect of a long degrading
campaign within academia was one he regarded with dread. For a
supposedly advanced civilization, the Intersolar Commonwealth could be
appallingly backward at times, not to mention cruel.</p>
<p><i>Maybe it won't be that bad</i>, he told himself. The lie was
comforting enough to get him through the rest of the night's
shift.</p>
<hr>
<p>The Carlton AllLander drove Dudley home just after dawn. Like the
astronomer, the vehicle was old and worn, but perfectly capable of
doing its job. It had a cheap diesel engine, common enough on a
semi-frontier world like Gralmond, although its drive array was a
thoroughly modern photoneural processor. With its high suspension and
deep-tread tyres it could plough along the dirt track to the
observatory in all weather and seasons, including the metre-deep snow
of Gralmond's winters.</p>

The hr element does not affect the document's outline.

4.4.3 The pre element

Element/pre

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLPreElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
DOM interface:
[HTMLConstructor]
interface HTMLPreElement : HTMLElement {};

The pre element represents a block of preformatted text, in which structure is represented by typographic conventions rather than by elements.

In the HTML syntax, a leading newline character immediately following the pre element start tag is stripped.

Some examples of cases where the pre element could be used:

Authors are encouraged to consider how preformatted text will be experienced when the formatting is lost, as will be the case for users of speech synthesizers, braille displays, and the like. For cases like ASCII art, it is likely that an alternative presentation, such as a textual description, would be more universally accessible to the readers of the document.

To represent a block of computer code, the pre element can be used with a code element; to represent a block of computer output the pre element can be used with a samp element. Similarly, the kbd element can be used within a pre element to indicate text that the user is to enter.

This element has rendering requirements involving the bidirectional algorithm.

In the following snippet, a sample of computer code is presented.

<p>This is the <code>Panel</code> constructor:</p>
<pre><code>function Panel(element, canClose, closeHandler) {
  this.element = element;
  this.canClose = canClose;
  this.closeHandler = function () { if (closeHandler) closeHandler() };
}</code></pre>

In the following snippet, samp and kbd elements are mixed in the contents of a pre element to show a session of Zork I.

<pre><samp>You are in an open field west of a big white house with a boarded
front door.
There is a small mailbox here.

></samp> <kbd>open mailbox</kbd>

<samp>Opening the mailbox reveals:
A leaflet.

></samp></pre>

The following shows a contemporary poem that uses the pre element to preserve its unusual formatting, which forms an intrinsic part of the poem itself.

<pre>                maxling

it is with a          heart
               heavy

that i admit loss of a feline
        so           loved

a friend lost to the
        unknown
                                (night)

~cdr 11dec07</pre>

4.4.4 The blockquote element

Element/blockquote

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLQuoteElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Sectioning root.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Flow content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
cite — Link to the source of the quotation or more information about the edit
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLQuoteElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString cite;
};

The HTMLQuoteElement interface is also used by the q element.

The blockquote element represents a section that is quoted from another source.

Content inside a blockquote must be quoted from another source, whose address, if it has one, may be cited in the cite attribute.

If the cite attribute is present, it must be a valid URL potentially surrounded by spaces. To obtain the corresponding citation link, the value of the attribute must be parsed relative to the element's node document. User agents may allow users to follow such citation links, but they are primarily intended for private use (e.g., by server-side scripts collecting statistics about a site's use of quotations), not for readers.

The content of a blockquote may be abbreviated or may have context added in the conventional manner for the text's language.

For example, in English this is traditionally done using square brackets. Consider a page with the sentence "Jane ate the cracker. She then said she liked apples and fish."; it could be quoted as follows:

<blockquote>
 <p>[Jane] then said she liked [...] fish.</p>
</blockquote>

Attribution for the quotation, if any, must be placed outside the blockquote element.

For example, here the attribution is given in a paragraph after the quote:

<blockquote>
 <p>I contend that we are both atheists. I just believe in one fewer
 god than you do. When you understand why you dismiss all the other
 possible gods, you will understand why I dismiss yours.</p>
</blockquote>
<p>— Stephen Roberts</p>

The other examples below show other ways of showing attribution.

The cite IDL attribute must reflect the element's cite content attribute.

Here a blockquote element is used in conjunction with a figure element and its figcaption to clearly relate a quote to its attribution (which is not part of the quote and therefore doesn't belong inside the blockquote itself):

<figure>
 <blockquote>
  <p>The truth may be puzzling. It may take some work to grapple with.
  It may be counterintuitive. It may contradict deeply held
  prejudices. It may not be consonant with what we desperately want to
  be true. But our preferences do not determine what's true. We have a
  method, and that method helps us to reach not absolute truth, only
  asymptotic approaches to the truth — never there, just closer
  and closer, always finding vast new oceans of undiscovered
  possibilities. Cleverly designed experiments are the key.</p>
 </blockquote>
 <figcaption>Carl Sagan, in "<cite>Wonder and Skepticism</cite>", from
 the <cite>Skeptical Inquirer</cite> Volume 19, Issue 1 (January-February
 1995)</figcaption>
</figure>

This next example shows the use of cite alongside blockquote:

<p>His next piece was the aptly named <cite>Sonnet 130</cite>:</p>
<blockquote cite="https://quotes.example.org/s/sonnet130.html">
  <p>My mistress' eyes are nothing like the sun,<br>
  Coral is far more red, than her lips red,<br>
  ...

This example shows how a forum post could use blockquote to show what post a user is replying to. The article element is used for each post, to mark up the threading.

<article>
 <h1><a href="https://bacon.example.com/?blog=109431">Bacon on a crowbar</a></h1>
 <article>
  <header><strong>t3yw</strong> 12 points 1 hour ago</header>
  <p>I bet a narwhal would love that.</p>
  <footer><a href="?pid=29578">permalink</a></footer>
  <article>
   <header><strong>greg</strong> 8 points 1 hour ago</header>
   <blockquote><p>I bet a narwhal would love that.</p></blockquote>
   <p>Dude narwhals don't eat bacon.</p>
   <footer><a href="?pid=29579">permalink</a></footer>
   <article>
    <header><strong>t3yw</strong> 15 points 1 hour ago</header>
    <blockquote>
     <blockquote><p>I bet a narwhal would love that.</p></blockquote>
     <p>Dude narwhals don't eat bacon.</p>
    </blockquote>
    <p>Next thing you'll be saying they don't get capes and wizard
    hats either!</p>
    <footer><a href="?pid=29580">permalink</a></footer>
    <article>
     <article>
      <header><strong>boing</strong> -5 points 1 hour ago</header>
      <p>narwhals are worse than ceiling cat</p>
      <footer><a href="?pid=29581">permalink</a></footer>
     </article>
    </article>
   </article>
  </article>
  <article>
   <header><strong>fred</strong> 1 points 23 minutes ago</header>
   <blockquote><p>I bet a narwhal would love that.</p></blockquote>
   <p>I bet they'd love to peel a banana too.</p>
   <footer><a href="?pid=29582">permalink</a></footer>
  </article>
 </article>
</article>

This example shows the use of a blockquote for short snippets, demonstrating that one does not have to use p elements inside blockquote elements:

<p>He began his list of "lessons" with the following:</p>
<blockquote>One should never assume that his side of
the issue will be recognized, let alone that it will
be conceded to have merits.</blockquote>
<p>He continued with a number of similar points, ending with:</p>
<blockquote>Finally, one should be prepared for the threat
of breakdown in negotiations at any given moment and not
be cowed by the possibility.</blockquote>
<p>We shall now discuss these points...

Examples of how to represent a conversation are shown in a later section; it is not appropriate to use the cite and blockquote elements for this purpose.

4.4.5 The ol element

Element/ol

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLOListElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
If the element's children include at least one li element: Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Zero or more li and script-supporting elements.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
reversed — Number the list backwards
startStarting value of the list
type — Kind of list marker
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLOListElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean reversed;
  [CEReactions] attribute long start;
  [CEReactions] attribute DOMString type;

  // also has obsolete members
};

The ol element represents a list of items, where the items have been intentionally ordered, such that changing the order would change the meaning of the document.

The items of the list are the li element child nodes of the ol element, in tree order.

Element/ol#attr-reversed

Support in all current engines.

Firefox18+Safari6+Chrome18+
OperaYesEdge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android18+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

The reversed attribute is a boolean attribute. If present, it indicates that the list is a descending list (..., 3, 2, 1). If the attribute is omitted, the list is an ascending list (1, 2, 3, ...).

The start attribute, if present, must be a valid integer. It is used to determine the starting value of the list.

An ol element has a starting value, which is an integer determined as follows:

  1. If the ol element has a start attribute, then:

    1. Let parsed be the result of parsing the value of the attribute as an integer.

    2. If parsed is not an error, then return parsed.

  2. If the ol element has a reversed attribute, then return the number of owned li elements.

  3. Return 1.

The type attribute can be used to specify the kind of marker to use in the list, in the cases where that matters (e.g. because items are to be referenced by their number/letter). The attribute, if specified, must have a value that is identical to one of the characters given in the first cell of one of the rows of the following table. The type attribute represents the state given in the cell in the second column of the row whose first cell matches the attribute's value; if none of the cells match, or if the attribute is omitted, then the attribute represents the decimal state.

Keyword State Description Examples for values 1-3 and 3999-4001
1 (U+0031) decimal Decimal numbers 1. 2. 3. ... 3999. 4000. 4001. ...
a (U+0061) lower-alpha Lowercase latin alphabet a. b. c. ... ewu. ewv. eww. ...
A (U+0041) upper-alpha Uppercase latin alphabet A. B. C. ... EWU. EWV. EWW. ...
i (U+0069) lower-roman Lowercase roman numerals i. ii. iii. ... mmmcmxcix. i̅v̅. i̅v̅i. ...
I (U+0049) upper-roman Uppercase roman numerals I. II. III. ... MMMCMXCIX. I̅V̅. I̅V̅I. ...

User agents should render the items of the list in a manner consistent with the state of the type attribute of the ol element. Numbers less than or equal to zero should always use the decimal system regardless of the type attribute.

For CSS user agents, a mapping for this attribute to the 'list-style-type' CSS property is given in the rendering section (the mapping is straightforward: the states above have the same names as their corresponding CSS values).

It is possible to redefine the default CSS list styles used to implement this attribute in CSS user agents; doing so will affect how list items are rendered.

The reversed and type IDL attributes must reflect the respective content attributes of the same name.

The start IDL attribute must reflect the content attribute of the same name, with a default value of 1.

This means that the start IDL attribute does not necessarily match the list's starting value, in cases where the start content attribute is omitted and the reversed content attribute is specified.

The following markup shows a list where the order matters, and where the ol element is therefore appropriate. Compare this list to the equivalent list in the ul section to see an example of the same items using the ul element.

<p>I have lived in the following countries (given in the order of when
I first lived there):</p>
<ol>
 <li>Switzerland
 <li>United Kingdom
 <li>United States
 <li>Norway
</ol>

Note how changing the order of the list changes the meaning of the document. In the following example, changing the relative order of the first two items has changed the birthplace of the author:

<p>I have lived in the following countries (given in the order of when
I first lived there):</p>
<ol>
 <li>United Kingdom
 <li>Switzerland
 <li>United States
 <li>Norway
</ol>

4.4.6 The ul element

Element/ul

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLUListElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
If the element's children include at least one li element: Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Zero or more li and script-supporting elements.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLUListElement : HTMLElement {
  [HTMLConstructor] constructor();

  // also has obsolete members
};

The ul element represents a list of items, where the order of the items is not important — that is, where changing the order would not materially change the meaning of the document.

The items of the list are the li element child nodes of the ul element.

The following markup shows a list where the order does not matter, and where the ul element is therefore appropriate. Compare this list to the equivalent list in the ol section to see an example of the same items using the ol element.

<p>I have lived in the following countries:</p>
<ul>
 <li>Norway
 <li>Switzerland
 <li>United Kingdom
 <li>United States
</ul>

Note that changing the order of the list does not change the meaning of the document. The items in the snippet above are given in alphabetical order, but in the snippet below they are given in order of the size of their current account balance in 2007, without changing the meaning of the document whatsoever:

<p>I have lived in the following countries:</p>
<ul>
 <li>Switzerland
 <li>Norway
 <li>United Kingdom
 <li>United States
</ul>

4.4.7 The menu element

Element/menu

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLMenuElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
If the element's children include at least one li element: Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Zero or more li and script-supporting elements.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLMenuElement : HTMLElement {
  [HTMLConstructor] constructor();

  // also has obsolete members
};

The menu element represents a toolbar consisting of its contents, in the form of an unordered list of items (represented by li elements), each of which represents a command that the user can perform or activate.

The menu element is simply a semantic alternative to ul to express an unordered list of commands (a "toolbar").

In this example, a text-editing application uses a menu element to provide a series of editing commands:

<menu>
 <li><button onclick="copy()"><img src="copy.svg" alt="Copy"></button></li>
 <li><button onclick="cut()"><img src="cut.svg" alt="Cut"></button></li>
 <li><button onclick="paste()"><img src="paste.svg" alt="Paste"></button></li>
</menu>

Note that the styling to make this look like a conventional toolbar menu is up to the application.

4.4.8 The li element

Element/li

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLLIElement

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
None.
Contexts in which this element can be used:
Inside ol elements.
Inside ul elements.
Inside menu elements.
Content model:
Flow content.
text/html 中的标签省略
An li element's end tag can be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.
Content attributes:
Global attributes
If the element is not a child of an ul or menu element: valueOrdinal value of the list item
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLLIElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute long value;

  // also has obsolete members
};

The li element represents a list item. If its parent element is an ol, ul, or menu element, then the element is an item of the parent element's list, as defined for those elements. Otherwise, the list item has no defined list-related relationship to any other li element.

The value attribute, if present, must be a valid integer. It is used to determine the ordinal value of the list item, when the li's list owner is an ol element.


Any element whose computed value of 'display' is 'list-item' has a list owner, which is determined as follows:

  1. If the element is not being rendered, return null; the element has no list owner.

  2. Let ancestor be the element's parent.

  3. If the element has an ol, ul, or menu ancestor, set ancestor to the closest such ancestor element.

  4. Return the closest inclusive ancestor of ancestor that produces a CSS box.

    Such an element will always exist, as at the very least the document element will always produce a CSS box.

To determine the ordinal value of each element owned by a given list owner owner, perform the following steps:

  1. Let i be 1.

  2. If owner is an ol element, let numbering be owner's starting value. Otherwise, let numbering be 1.

  3. Loop: If i is greater than the number of list items that owner owns, then return; all of owner's owned list items have been assigned ordinal values.

  4. Let item be the ith of owner's owned list items, in tree order.

  5. If item is an li element that has a value attribute, then:

    1. Let parsed be the result of parsing the value of the attribute as an integer.

    2. If parsed is not an error, then set numbering to parsed.

  6. The ordinal value of item is numbering.

  7. If owner is an ol element, and owner has a reversed attribute, decrement numbering by 1; otherwise, increment numbering by 1.

  8. Increment i by 1.

  9. Go to the step labeled loop.


The value IDL attribute must reflect the value of the value content attribute.

The element's value IDL attribute does not directly correspond to its ordinal value; it simply reflects the content attribute. For example, given this list:

<ol>
 <li>Item 1
 <li value="3">Item 3
 <li>Item 4
</ol>

The ordinal values are 1, 3, and 4, whereas the value IDL attributes return 0, 3, 0 on getting.

The following example, the top ten movies are listed (in reverse order). Note the way the list is given a title by using a figure element and its figcaption element.

<figure>
 <figcaption>The top 10 movies of all time</figcaption>
 <ol>
  <li value="10"><cite>Josie and the Pussycats</cite>, 2001</li>
  <li value="9"><cite lang="sh">Црна мачка, бели мачор</cite>, 1998</li>
  <li value="8"><cite>A Bug's Life</cite>, 1998</li>
  <li value="7"><cite>Toy Story</cite>, 1995</li>
  <li value="6"><cite>Monsters, Inc</cite>, 2001</li>
  <li value="5"><cite>Cars</cite>, 2006</li>
  <li value="4"><cite>Toy Story 2</cite>, 1999</li>
  <li value="3"><cite>Finding Nemo</cite>, 2003</li>
  <li value="2"><cite>The Incredibles</cite>, 2004</li>
  <li value="1"><cite>Ratatouille</cite>, 2007</li>
 </ol>
</figure>

The markup could also be written as follows, using the reversed attribute on the ol element:

<figure>
 <figcaption>The top 10 movies of all time</figcaption>
 <ol reversed>
  <li><cite>Josie and the Pussycats</cite>, 2001</li>
  <li><cite lang="sh">Црна мачка, бели мачор</cite>, 1998</li>
  <li><cite>A Bug's Life</cite>, 1998</li>
  <li><cite>Toy Story</cite>, 1995</li>
  <li><cite>Monsters, Inc</cite>, 2001</li>
  <li><cite>Cars</cite>, 2006</li>
  <li><cite>Toy Story 2</cite>, 1999</li>
  <li><cite>Finding Nemo</cite>, 2003</li>
  <li><cite>The Incredibles</cite>, 2004</li>
  <li><cite>Ratatouille</cite>, 2007</li>
 </ol>
</figure>

While it is conforming to include heading elements (e.g. h1) inside li elements, it likely does not convey the semantics that the author intended. A heading starts a new section, so a heading in a list implicitly splits the list into spanning multiple sections.

4.4.9 The dl element

Element/dl

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLDListElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
If the element's children include at least one name-value group: Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Either: Zero or more groups each consisting of one or more dt elements followed by one or more dd elements, optionally intermixed with script-supporting elements.
Or: One or more div elements, optionally intermixed with script-supporting elements.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLDListElement : HTMLElement {
  [HTMLConstructor] constructor();

  // also has obsolete members
};

The dl element represents an association list consisting of zero or more name-value groups (a description list). A name-value group consists of one or more names (dt elements, possibly as children of a div element child) followed by one or more values (dd elements, possibly as children of a div element child), ignoring any nodes other than dt and dd element children, and dt and dd elements that are children of div element children. Within a single dl element, there should not be more than one dt element for each name.

Name-value groups may be terms and definitions, metadata topics and values, questions and answers, or any other groups of name-value data.

The values within a group are alternatives; multiple paragraphs forming part of the same value must all be given within the same dd element.

The order of the list of groups, and of the names and values within each group, may be significant.

In order to annotate groups with microdata attributes, or other global attributes that apply to whole groups, or just for styling purposes, each group in a dl element can be wrapped in a div element. This does not change the semantics of the dl element.

The name-value groups of a dl element dl are determined using the following algorithm. A name-value group has a name (a list of dt elements, initially empty) and a value (a list of dd elements, initially empty).

  1. Let groups be an empty list of name-value groups.

  2. Let current be a new name-value group.

  3. Let seenDd be false.

  4. Let child be dl's first child.

  5. Let grandchild be null.

  6. While child is not null:

    1. If child is a div element, then:

      1. Let grandchild be child's first child.

      2. While grandchild is not null:

        1. Process dt or dd for grandchild.

        2. Set grandchild to grandchild's next sibling.

    2. Otherwise, process dt or dd for child.

    3. Set child to child's next sibling.

  7. If current is not empty, then append current to groups.

  8. Return groups.

To process dt or dd for a node node means to follow these steps:

  1. Let groups, current, and seenDd be the same variables as those of the same name in the algorithm that invoked these steps.

  2. If node is a dt element, then:

    1. If seenDd is true, then append current to groups, set current to a new name-value group, and set seenDd to false.

    2. Append node to current's name.

  3. Otherwise, if node is a dd element, then append node to current's value and set seenDd to true.

When a name-value group has an empty list as name or value, it is often due to accidentally using dd elements in the place of dt elements and vice versa. Conformance checkers can spot such mistakes and might be able to advise authors how to correctly use the markup.

In the following example, one entry ("Authors") is linked to two values ("John" and "Luke").

<dl>
 <dt> Authors
 <dd> John
 <dd> Luke
 <dt> Editor
 <dd> Frank
</dl>

In the following example, one definition is linked to two terms.

<dl>
 <dt lang="en-US"> <dfn>color</dfn> </dt>
 <dt lang="en-GB"> <dfn>colour</dfn> </dt>
 <dd> A sensation which (in humans) derives from the ability of
 the fine structure of the eye to distinguish three differently
 filtered analyses of a view. </dd>
</dl>

The following example illustrates the use of the dl element to mark up metadata of sorts. At the end of the example, one group has two metadata labels ("Authors" and "Editors") and two values ("Robert Rothman" and "Daniel Jackson"). This example also uses the div element around the groups of dt and dd element, to aid with styling.

<dl>
 <div>
  <dt> Last modified time </dt>
  <dd> 2004-12-23T23:33Z </dd>
 </div>
 <div>
  <dt> Recommended update interval </dt>
  <dd> 60s </dd>
 </div>
 <div>
  <dt> Authors </dt>
  <dt> Editors </dt>
  <dd> Robert Rothman </dd>
  <dd> Daniel Jackson </dd>
 </div>
</dl>

The following example shows the dl element used to give a set of instructions. The order of the instructions here is important (in the other examples, the order of the blocks was not important).

<p>Determine the victory points as follows (use the
first matching case):</p>
<dl>
 <dt> If you have exactly five gold coins </dt>
 <dd> You get five victory points </dd>
 <dt> If you have one or more gold coins, and you have one or more silver coins </dt>
 <dd> You get two victory points </dd>
 <dt> If you have one or more silver coins </dt>
 <dd> You get one victory point </dd>
 <dt> Otherwise </dt>
 <dd> You get no victory points </dd>
</dl>

The following snippet shows a dl element being used as a glossary. Note the use of dfn to indicate the word being defined.

<dl>
 <dt><dfn>Apartment</dfn>, n.</dt>
 <dd>An execution context grouping one or more threads with one or
 more COM objects.</dd>
 <dt><dfn>Flat</dfn>, n.</dt>
 <dd>A deflated tire.</dd>
 <dt><dfn>Home</dfn>, n.</dt>
 <dd>The user's login directory.</dd>
</dl>

This example uses microdata attributes in a dl element, together with the div element, to annotate the ice cream desserts at a French restaurant.

<dl>
 <div itemscope itemtype="http://schema.org/Product">
  <dt itemprop="name">Café ou Chocolat Liégeois
  <dd itemprop="offers" itemscope itemtype="http://schema.org/Offer">
   <span itemprop="price">3.50</span>
   <data itemprop="priceCurrency" value="EUR">€</data>
  <dd itemprop="description">
   2 boules Café ou Chocolat, 1 boule Vanille, sause café ou chocolat, chantilly
 </div>

 <div itemscope itemtype="http://schema.org/Product">
  <dt itemprop="name">Américaine
  <dd itemprop="offers" itemscope itemtype="http://schema.org/Offer">
   <span itemprop="price">3.50</span>
   <data itemprop="priceCurrency" value="EUR">€</data>
  <dd itemprop="description">
   1 boule Crème brûlée, 1 boule Vanille, 1 boule Caramel, chantilly
 </div>
</dl>

Without the div element the markup would need to use the itemref attribute to link the data in the dd elements with the item, as follows.

<dl>
 <dt itemscope itemtype="http://schema.org/Product" itemref="1-offer 1-description">
  <span itemprop="name">Café ou Chocolat Liégeois</span>
 <dd id="1-offer" itemprop="offers" itemscope itemtype="http://schema.org/Offer">
  <span itemprop="price">3.50</span>
  <data itemprop="priceCurrency" value="EUR">€</data>
 <dd id="1-description" itemprop="description">
  2 boules Café ou Chocolat, 1 boule Vanille, sause café ou chocolat, chantilly

 <dt itemscope itemtype="http://schema.org/Product" itemref="2-offer 2-description">
  <span itemprop="name">Américaine</span>
 <dd id="2-offer" itemprop="offers" itemscope itemtype="http://schema.org/Offer">
  <span itemprop="price">3.50</span>
  <data itemprop="priceCurrency" value="EUR">€</data>
 <dd id="2-description" itemprop="description">
  1 boule Crème brûlée, 1 boule Vanille, 1 boule Caramel, chantilly
</dl>

The dl element is inappropriate for marking up dialogue. See some examples of how to mark up dialogue.

4.4.10 The dt element

Element/dt

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
None.
Contexts in which this element can be used:
Before dd or dt elements inside dl elements.
Before dd or dt elements inside div elements that are children of a dl element.
Content model:
Flow content, but with no header, footer, sectioning content, or heading content descendants.
text/html 中的标签省略
A dt element's end tag can be omitted if the dt element is immediately followed by another dt element or a dd element.
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The dt element represents the term, or name, part of a term-description group in a description list (dl element).

The dt element itself, when used in a dl element, does not indicate that its contents are a term being defined, but this can be indicated using the dfn element.

This example shows a list of frequently asked questions (a FAQ) marked up using the dt element for questions and the dd element for answers.

<article>
 <h1>FAQ</h1>
 <dl>
  <dt>What do we want?</dt>
  <dd>Our data.</dd>
  <dt>When do we want it?</dt>
  <dd>Now.</dd>
  <dt>Where is it?</dt>
  <dd>We are not sure.</dd>
 </dl>
</article>

4.4.11 The dd element

Element/dd

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
None.
Contexts in which this element can be used:
After dt or dd elements inside dl elements.
After dt or dd elements inside div elements that are children of a dl element.
Content model:
Flow content.
text/html 中的标签省略
A dd element's end tag can be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element.
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The dd element represents the description, definition, or value, part of a term-description group in a description list (dl element).

A dl can be used to define a vocabulary list, like in a dictionary. In the following example, each entry, given by a dt with a dfn, has several dds, showing the various parts of the definition.

<dl>
 <dt><dfn>happiness</dfn></dt>
 <dd class="pronunciation">/'hæ p. nes/</dd>
 <dd class="part-of-speech"><i><abbr>n.</abbr></i></dd>
 <dd>The state of being happy.</dd>
 <dd>Good fortune; success. <q>Oh <b>happiness</b>! It worked!</q></dd>
 <dt><dfn>rejoice</dfn></dt>
 <dd class="pronunciation">/ri jois'/</dd>
 <dd><i class="part-of-speech"><abbr>v.intr.</abbr></i> To be delighted oneself.</dd>
 <dd><i class="part-of-speech"><abbr>v.tr.</abbr></i> To cause one to be delighted.</dd>
</dl>

4.4.12 The figure element

Element/figure

Support in all current engines.

Firefox4+Safari5.1+Chrome8+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS5+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android11+
Categories:
Flow content.
Sectioning root.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Either: one figcaption element followed by flow content.
Or: flow content followed by one figcaption element.
Or: flow content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The figure element represents some flow content, optionally with a caption, that is self-contained (like a complete sentence) and is typically referenced as a single unit from the main flow of the document.

"Self-contained" in this context does not necessarily mean independent. For example, each sentence in a paragraph is self-contained; an image that is part of a sentence would be inappropriate for figure, but an entire sentence made of images would be fitting.

The element can thus be used to annotate illustrations, diagrams, photos, code listings, etc.

When a figure is referred to from the main content of the document by identifying it by its caption (e.g., by figure number), it enables such content to be easily moved away from that primary content, e.g., to the side of the page, to dedicated pages, or to an appendix, without affecting the flow of the document.

If a figure element is referenced by its relative position, e.g., "in the photograph above" or "as the next figure shows", then moving the figure would disrupt the page's meaning. Authors are encouraged to consider using labels to refer to figures, rather than using such relative references, so that the page can easily be restyled without affecting the page's meaning.

The first figcaption element child of the element, if any, represents the caption of the figure element's contents. If there is no child figcaption element, then there is no caption.

A figure element's contents are part of the surrounding flow. If the purpose of the page is to display the figure, for example a photograph on an image sharing site, the figure and figcaption elements can be used to explicitly provide a caption for that figure. For content that is only tangentially related, or that serves a separate purpose than the surrounding flow, the aside element should be used (and can itself wrap a figure). For example, a pull quote that repeats content from an article would be more appropriate in an aside than in a figure, because it isn't part of the content, it's a repetition of the content for the purposes of enticing readers or highlighting key topics.

This example shows the figure element to mark up a code listing.

<p>In <a href="#l4">listing 4</a> we see the primary core interface
API declaration.</p>
<figure id="l4">
 <figcaption>Listing 4. The primary core interface API declaration.</figcaption>
 <pre><code>interface PrimaryCore {
 boolean verifyDataLine();
 undefined sendData(sequence&lt;byte> data);
 undefined initSelfDestruct();
}</code></pre>
</figure>
<p>The API is designed to use UTF-8.</p>

Here we see a figure element to mark up a photo that is the main content of the page (as in a gallery).

<!DOCTYPE HTML>
<html lang="en">
<title>Bubbles at work — My Gallery™</title>
<figure>
 <img src="bubbles-work.jpeg"
      alt="Bubbles, sitting in his office chair, works on his
           latest project intently.">
 <figcaption>Bubbles at work</figcaption>
</figure>
<nav><a href="19414.html">Prev</a> — <a href="19416.html">Next</a></nav>

In this example, we see an image that is not a figure, as well as an image and a video that are. The first image is literally part of the example's second sentence, so it's not a self-contained unit, and thus figure would be inappropriate.

<h2>Malinko's comics</h2>

<p>This case centered on some sort of "intellectual property"
infringement related to a comic (see Exhibit A). The suit started
after a trailer ending with these words:

<blockquote>
 <img src="promblem-packed-action.png" alt="ROUGH COPY! Promblem-Packed Action!">
</blockquote>

<p>...was aired. A lawyer, armed with a Bigger Notebook, launched a
preemptive strike using snowballs. A complete copy of the trailer is
included with Exhibit B.

<figure>
 <img src="ex-a.png" alt="Two squiggles on a dirty piece of paper.">
 <figcaption>Exhibit A. The alleged <cite>rough copy</cite> comic.</figcaption>
</figure>

<figure>
 <video src="ex-b.mov"></video>
 <figcaption>Exhibit B. The <cite>Rough Copy</cite> trailer.</figcaption>
</figure>

<p>The case was resolved out of court.

Here, a part of a poem is marked up using figure.

<figure>
 <p>'Twas brillig, and the slithy toves<br>
 Did gyre and gimble in the wabe;<br>
 All mimsy were the borogoves,<br>
 And the mome raths outgrabe.</p>
 <figcaption><cite>Jabberwocky</cite> (first verse). Lewis Carroll, 1832-98</figcaption>
</figure>

In this example, which could be part of a much larger work discussing a castle, nested figure elements are used to provide both a group caption and individual captions for each figure in the group:

<figure>
 <figcaption>The castle through the ages: 1423, 1858, and 1999 respectively.</figcaption>
 <figure>
  <figcaption>Etching. Anonymous, ca. 1423.</figcaption>
  <img src="castle1423.jpeg" alt="The castle has one tower, and a tall wall around it.">
 </figure>
 <figure>
  <figcaption>Oil-based paint on canvas. Maria Towle, 1858.</figcaption>
  <img src="castle1858.jpeg" alt="The castle now has two towers and two walls.">
 </figure>
 <figure>
  <figcaption>Film photograph. Peter Jankle, 1999.</figcaption>
  <img src="castle1999.jpeg" alt="The castle lies in ruins, the original tower all that remains in one piece.">
 </figure>
</figure>

The previous example could also be more succinctly written as follows (using title attributes in place of the nested figure/figcaption pairs):

<figure>
 <img src="castle1423.jpeg" title="Etching. Anonymous, ca. 1423."
      alt="The castle has one tower, and a tall wall around it.">
 <img src="castle1858.jpeg" title="Oil-based paint on canvas. Maria Towle, 1858."
      alt="The castle now has two towers and two walls.">
 <img src="castle1999.jpeg" title="Film photograph. Peter Jankle, 1999."
      alt="The castle lies in ruins, the original tower all that remains in one piece.">
 <figcaption>The castle through the ages: 1423, 1858, and 1999 respectively.</figcaption>
</figure>

The figure is sometimes referenced only implicitly from the content:

<article>
 <h1>Fiscal negotiations stumble in Congress as deadline nears</h1>
 <figure>
  <img src="obama-reid.jpeg" alt="Obama and Reid sit together smiling in the Oval Office.">
  <figcaption>Barack Obama and Harry Reid. White House press photograph.</figcaption>
 </figure>
 <p>Negotiations in Congress to end the fiscal impasse sputtered on Tuesday, leaving both chambers
 grasping for a way to reopen the government and raise the country's borrowing authority with a
 Thursday deadline drawing near.</p>
 ...
</article>

4.4.13 The figcaption element

Element/figcaption

Support in all current engines.

Firefox4+Safari5.1+Chrome8+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS5+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android11+
Categories:
None.
Contexts in which this element can be used:
As the first or last child of a figure element.
Content model:
Flow content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The figcaption element represents a caption or legend for the rest of the contents of the figcaption element's parent figure element, if any.

The element can contain additional information about the source:

<figcaption>
 <p>A duck.</p>
 <p><small>Photograph courtesy of 🌟 News.</small></p>
</figcaption>
<figcaption>
 <p>Average rent for 3-room apartments, excluding non-profit apartments</p>
 <p>Zürich’s Statistics Office — <time datetime=2017-11-14>14 November 2017</time></p>
</figcaption>

4.4.14 The main element

Element/main

Support in all current engines.

Firefox21+Safari7+Chrome26+
Opera16+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android21+Safari iOS7+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected, but only if it is a hierarchically correct main element.
Content model:
Flow content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The main element represents the dominant contents of the document.

A document must not have more than one main element that does not have the hidden attribute specified.

A hierarchically correct main element is one whose ancestor elements are limited to html, body, div, form without an accessible name, and autonomous custom elements. Each main element must be a hierarchically correct main element.

In this example, the author has used a presentation where each component of the page is rendered in a box. To wrap the main content of the page (as opposed to the header, the footer, the navigation bar, and a sidebar), the main element is used.

<!DOCTYPE html>
<html lang="en">
<title>RPG System 17</title>
<style>
 header, nav, aside, main, footer {
   margin: 0.5em; border: thin solid; padding: 0.5em;
   background: #EFF; color: black; box-shadow: 0 0 0.25em #033;
 }
 h1, h2, p { margin: 0; }
 nav, main { float: left; }
 aside { float: right; }
 footer { clear: both; }
</style>
<header>
 <h1>System Eighteen</h1>
</header>
<nav>
 <a href="../16/">← System 17</a>
 <a href="../18/">RPXIX →</a>
</nav>
<aside>
 <p>This system has no HP mechanic, so there's no healing.
</aside>
<main>
 <h2>Character creation</h2>
 <p>Attributes (magic, strength, agility) are purchased at the cost of one point per level.</p>
 <h2>Rolls</h2>
 <p>Each encounter, roll the dice for all your skills. If you roll more than the opponent, you win.</p>
</main>
<footer>
 <p>Copyright © 2013
</footer>
</html>

In the following example, multiple main elements are used and script is used to make navigation work without a server roundtrip and to set the hidden attribute on those that are not current:

<!doctype html>
<html lang=en-CA>
<meta charset=utf-8>
<title> … </title>
<link rel=stylesheet href=spa.css>
<script src=spa.js async></script>
<nav>
 <a href=/>Home</a>
 <a href=/about>About</a>
 <a href=/contact>Contact</a>
</nav>
<main>
 <h1>Home</h1>
 …
</main>
<main hidden>
 <h1>About</h1>
 …
</main>
<main hidden>
 <h1>Contact</h1>
 …
</main>
<footer>Made with ❤️ by <a href=https://example.com/>Example 👻</a>.</footer>

4.4.15 The div element

Element/div

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLDivElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
As a child of a dl element.
Content model:
If the element is a child of a dl element: one or more dt elements followed by one or more dd elements, optionally intermixed with script-supporting elements.
If the element is not a child of a dl element: flow content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLDivElement : HTMLElement {
  [HTMLConstructor] constructor();

  // also has obsolete members
};

The div element has no special meaning at all. It represents its children. It can be used with the class, lang, and title attributes to mark up semantics common to a group of consecutive elements. It can also be used in a dl element, wrapping groups of dt and dd elements.

Authors are strongly encouraged to view the div element as an element of last resort, for when no other element is suitable. Use of more appropriate elements instead of the div element leads to better accessibility for readers and easier maintainability for authors.

For example, a blog post would be marked up using article, a chapter using section, a page's navigation aids using nav, and a group of form controls using fieldset.

On the other hand, div elements can be useful for stylistic purposes or to wrap multiple paragraphs within a section that are all to be annotated in a similar way. In the following example, we see div elements used as a way to set the language of two paragraphs at once, instead of setting the language on the two paragraph elements separately:

<article lang="en-US">
 <h1>My use of language and my cats</h1>
 <p>My cat's behavior hasn't changed much since her absence, except
 that she plays her new physique to the neighbors regularly, in an
 attempt to get pets.</p>
 <div lang="en-GB">
  <p>My other cat, coloured black and white, is a sweetie. He followed
  us to the pool today, walking down the pavement with us. Yesterday
  he apparently visited our neighbours. I wonder if he recognises that
  their flat is a mirror image of ours.</p>
  <p>Hm, I just noticed that in the last paragraph I used British
  English. But I'm supposed to write in American English. So I
  shouldn't say "pavement" or "flat" or "colour"...</p>
 </div>
 <p>I should say "sidewalk" and "apartment" and "color"!</p>
</article>

4.5 Text-level semantics

4.5.1 The a element

Element/a

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLAnchorElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Phrasing content.
If the element has an href attribute: Interactive content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Transparent, but there must be no interactive content descendant, a element descendant, or descendant with the tabindex attribute specified.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
href — Address of the hyperlink
targetBrowsing context for hyperlink navigation
download — Whether to download the resource instead of navigating to it, and its file name if so
pingURLs to ping
rel — Relationship between the location in the document containing the hyperlink and the destination resource
hreflang — Language of the linked resource
type — Hint for the type of the referenced resource
referrerpolicyReferrer policy for fetches initiated by the element
Accessibility considerations:
If the element has an href attribute: for authors; for implementers.
Otherwise: for authors; for implementers.
DOM interface:
[Exposed=Window]
interface HTMLAnchorElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString target;
  [CEReactions] attribute DOMString download;
  [CEReactions] attribute USVString ping;
  [CEReactions] attribute DOMString rel;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList relList;
  [CEReactions] attribute DOMString hreflang;
  [CEReactions] attribute DOMString type;

  [CEReactions] attribute DOMString text;

  [CEReactions] attribute DOMString referrerPolicy;

  // also has obsolete members
};
HTMLAnchorElement includes HTMLHyperlinkElementUtils;

If the a element has an href attribute, then it represents a hyperlink (a hypertext anchor) labeled by its contents.

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.

The target, download, ping, rel, hreflang, type, and referrerpolicy attributes must be omitted if the href attribute is not present.

If the itemprop attribute is specified on an a element, then the href attribute must also be specified.

If a site uses a consistent navigation toolbar on every page, then the link that would normally link to the page itself could be marked up using an a element:

<nav>
 <ul>
  <li> <a href="/">Home</a> </li>
  <li> <a href="/news">News</a> </li>
  <li> <a>Examples</a> </li>
  <li> <a href="/legal">Legal</a> </li>
 </ul>
</nav>

The href, target, download, ping, and referrerpolicy attributes affect what happens when users follow hyperlinks or download hyperlinks created using the a element. The rel, hreflang, and type attributes may be used to indicate to the user the likely nature of the target resource before the user follows the link.

The activation behavior of a elements that create hyperlinks is to run the following steps:

  1. If the target of the click event is an img element with an ismap attribute specified, then server-side image map processing must be performed, as follows:

    1. Let x and y be zero.
    2. If the click event was a real pointing-device-triggered click event on the img element, then set x to the distance in CSS pixels from the left edge of the image to the location of the click, and set y to the distance in CSS pixels from the top edge of the image to the location of the click.
    3. If x is negative, set x to zero.
    4. If y is negative, set y to zero.
    5. Let hyperlink suffix be a U+003F QUESTION MARK character, the value of x expressed as a base-ten integer using ASCII digits, a U+002C COMMA character (,), and the value of y expressed as a base-ten integer using ASCII digits.
  2. Follow the hyperlink or download the hyperlink created by the a element, as determined by the download attribute and any expressed user preference, passing hyperlink suffix, if the steps above defined it.

a . text

Same as textContent.

HTMLAnchorElement/download

Support in all current engines.

Firefox20+Safari10.1+Chrome15+
Opera15+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android20+Safari iOS10.3+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android14+

HTMLAnchorElement/rel

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The IDL attributes download, ping, target, rel, hreflang, and type, must reflect the respective content attributes of the same name.

HTMLAnchorElement/relList

Support in all current engines.

Firefox30+Safari9+Chrome65+
Opera52+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android30+Safari iOS9+Chrome Android65+WebView Android65+Samsung Internet9.0+Opera Android47+

The IDL attribute relList must reflect the rel content attribute.

HTMLAnchorElement/referrerPolicy

Support in all current engines.

Firefox50+Safari14+Chrome53+
Opera40+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android50+Safari iOS14+Chrome Android53+WebView Android53+Samsung Internet7.2+Opera Android41+

The IDL attribute referrerPolicy must reflect the referrerpolicy content attribute, limited to only known values.

The text attribute's getter must return this element's descendant text content.

The text attribute's setter must string replace all with the given value within this element.

The a element can be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g., buttons or other links). This example shows how this can be used to make an entire advertising block into a link:

<aside class="advertising">
 <h1>Advertising</h1>
 <a href="https://ad.example.com/?adid=1929&amp;pubid=1422">
  <section>
   <h1>Mellblomatic 9000!</h1>
   <p>Turn all your widgets into mellbloms!</p>
   <p>Only $9.99 plus shipping and handling.</p>
  </section>
 </a>
 <a href="https://ad.example.com/?adid=375&amp;pubid=1422">
  <section>
   <h1>The Mellblom Browser</h1>
   <p>Web browsing at the speed of light.</p>
   <p>No other browser goes faster!</p>
  </section>
 </a>
</aside>

The following example shows how a bit of script can be used to effectively make an entire row in a job listing table a hyperlink:

<table>
 <tr>
  <th>Position
  <th>Team
  <th>Location
 <tr>
  <td><a href="/jobs/manager">Manager</a>
  <td>Remotees
  <td>Remote
 <tr>
  <td><a href="/jobs/director">Director</a>
  <td>Remotees
  <td>Remote
 <tr>
  <td><a href="/jobs/astronaut">Astronaut</a>
  <td>Architecture
  <td>Remote
</table>
<script>
document.querySelector("table").onclick = ({ target }) => {
  if (target.parentElement.localName === "tr") {
    const link = target.parentElement.querySelector("a");
    if (link) {
      link.click();
    }
  }
}
</script>

4.5.2 The em element

Element/em

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The em element represents stress emphasis of its contents.

The level of stress that a particular piece of content has is given by its number of ancestor em elements.

The placement of stress emphasis changes the meaning of the sentence. The element thus forms an integral part of the content. The precise way in which stress is used in this way depends on the language.

These examples show how changing the stress emphasis changes the meaning. First, a general statement of fact, with no stress:

<p>Cats are cute animals.</p>

By emphasizing the first word, the statement implies that the kind of animal under discussion is in question (maybe someone is asserting that dogs are cute):

<p><em>Cats</em> are cute animals.</p>

Moving the stress to the verb, one highlights that the truth of the entire sentence is in question (maybe someone is saying cats are not cute):

<p>Cats <em>are</em> cute animals.</p>

By moving it to the adjective, the exact nature of the cats is reasserted (maybe someone suggested cats were mean animals):

<p>Cats are <em>cute</em> animals.</p>

Similarly, if someone asserted that cats were vegetables, someone correcting this might emphasize the last word:

<p>Cats are cute <em>animals</em>.</p>

By emphasizing the entire sentence, it becomes clear that the speaker is fighting hard to get the point across. This kind of stress emphasis also typically affects the punctuation, hence the exclamation mark here.

<p><em>Cats are cute animals!</em></p>

Anger mixed with emphasizing the cuteness could lead to markup such as:

<p><em>Cats are <em>cute</em> animals!</em></p>

The em element isn't a generic "italics" element. Sometimes, text is intended to stand out from the rest of the paragraph, as if it was in a different mood or voice. For this, the i element is more appropriate.

The em element also isn't intended to convey importance; for that purpose, the strong element is more appropriate.

4.5.3 The strong element

Element/strong

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The strong element represents strong importance, seriousness, or urgency for its contents.

Importance: the strong element can be used in a heading, caption, or paragraph to distinguish the part that really matters from other parts that might be more detailed, more jovial, or merely boilerplate. (This is distinct from marking up subheadings, for which the hgroup element is appropriate.)

For example, the first word of the previous paragraph is marked up with strong to distinguish it from the more detailed text in the rest of the paragraph.

Seriousness: the strong element can be used to mark up a warning or caution notice.

Urgency: the strong element can be used to denote contents that the user needs to see sooner than other parts of the document.

The relative level of importance of a piece of content is given by its number of ancestor strong elements; each strong element increases the importance of its contents.

Changing the importance of a piece of text with the strong element does not change the meaning of the sentence.

Here, the word "chapter" and the actual chapter number are mere boilerplate, and the actual name of the chapter is marked up with strong:

<h1>Chapter 1: <strong>The Praxis</strong></h1>

In the following example, the name of the diagram in the caption is marked up with strong, to distinguish it from boilerplate text (before) and the description (after):

<figcaption>Figure 1. <strong>Ant colony dynamics</strong>. The ants in this colony are
affected by the heat source (upper left) and the food source (lower right).</figcaption>

In this example, the heading is really "Flowers, Bees, and Honey", but the author has added a light-hearted addition to the heading. The strong element is thus used to mark up the first part to distinguish it from the latter part.

<h1><strong>Flowers, Bees, and Honey</strong> and other things I don't understand</h1>

Here is an example of a warning notice in a game, with the various parts marked up according to how important they are:

<p><strong>Warning.</strong> This dungeon is dangerous.
<strong>Avoid the ducks.</strong> Take any gold you find.
<strong><strong>Do not take any of the diamonds</strong>,
they are explosive and <strong>will destroy anything within
ten meters.</strong></strong> You have been warned.</p>

In this example, the strong element is used to denote the part of the text that the user is intended to read first.

<p>Welcome to Remy, the reminder system.</p>
<p>Your tasks for today:</p>
<ul>
 <li><p><strong>Turn off the oven.</strong></p></li>
 <li><p>Put out the trash.</p></li>
 <li><p>Do the laundry.</p></li>
</ul>

4.5.4 The small element

Element/small

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The small element represents side comments such as small print.

Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or for satisfying licensing requirements.

The small element does not "de-emphasize" or lower the importance of text emphasized by the em element or marked as important with the strong element. To mark text as not emphasized or important, simply do not mark it up with the em or strong elements respectively.

The small element should not be used for extended spans of text, such as multiple paragraphs, lists, or sections of text. It is only intended for short runs of text. The text of a page listing terms of use, for instance, would not be a suitable candidate for the small element: in such a case, the text is not a side comment, it is the main content of the page.

The small element must not be used for subheadings; for that purpose, use the hgroup element.

In this example, the small element is used to indicate that value-added tax is not included in a price of a hotel room:

<dl>
 <dt>Single room
 <dd>199 € <small>breakfast included, VAT not included</small>
 <dt>Double room
 <dd>239 € <small>breakfast included, VAT not included</small>
</dl>

In this second example, the small element is used for a side comment in an article.

<p>Example Corp today announced record profits for the
second quarter <small>(Full Disclosure: Foo News is a subsidiary of
Example Corp)</small>, leading to speculation about a third quarter
merger with Demo Group.</p>

This is distinct from a sidebar, which might be multiple paragraphs long and is removed from the main flow of text. In the following example, we see a sidebar from the same article. This sidebar also has small print, indicating the source of the information in the sidebar.

<aside>
 <h1>Example Corp</h1>
 <p>This company mostly creates small software and Web
 sites.</p>
 <p>The Example Corp company mission is "To provide entertainment
 and news on a sample basis".</p>
 <p><small>Information obtained from <a
 href="https://example.com/about.html">example.com</a> home
 page.</small></p>
</aside>

In this last example, the small element is marked as being important small print.

<p><strong><small>Continued use of this service will result in a kiss.</small></strong></p>

4.5.5 The s element

Element/s

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The s element represents contents that are no longer accurate or no longer relevant.

The s element is not appropriate when indicating document edits; to mark a span of text as having been removed from a document, use the del element.

In this example a recommended retail price has been marked as no longer relevant as the product in question has a new sale price.

<p>Buy our Iced Tea and Lemonade!</p>
<p><s>Recommended retail price: $3.99 per bottle</s></p>
<p><strong>Now selling for just $2.99 a bottle!</strong></p>

4.5.6 The cite element

Element/cite

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The cite element represents the title of a work (e.g. a book, a paper, an essay, a poem, a score, a song, a script, a film, a TV show, a game, a sculpture, a painting, a theatre production, a play, an opera, a musical, an exhibition, a legal case report, a computer program, etc). This can be a work that is being quoted or referenced in detail (i.e. a citation), or it can just be a work that is mentioned in passing.

A person's name is not the title of a work — even if people call that person a piece of work — and the element must therefore not be used to mark up people's names. (In some cases, the b element might be appropriate for names; e.g. in a gossip article where the names of famous people are keywords rendered with a different style to draw attention to them. In other cases, if an element is really needed, the span element can be used.)

This next example shows a typical use of the cite element:

<p>My favorite book is <cite>The Reality Dysfunction</cite> by
Peter F. Hamilton. My favorite comic is <cite>Pearls Before
Swine</cite> by Stephan Pastis. My favorite track is <cite>Jive
Samba</cite> by the Cannonball Adderley Sextet.</p>

This is correct usage:

<p>According to the Wikipedia article <cite>HTML</cite>, as it
stood in mid-February 2008, leaving attribute values unquoted is
unsafe. This is obviously an over-simplification.</p>

The following, however, is incorrect usage, as the cite element here is containing far more than the title of the work:

<!-- do not copy this example, it is an example of bad usage! -->
<p>According to <cite>the Wikipedia article on HTML</cite>, as it
stood in mid-February 2008, leaving attribute values unquoted is
unsafe. This is obviously an over-simplification.</p>

The cite element is obviously a key part of any citation in a bibliography, but it is only used to mark the title:

<p><cite>Universal Declaration of Human Rights</cite>, United Nations,
December 1948. Adopted by General Assembly resolution 217 A (III).</p>

A citation is not a quote (for which the q element is appropriate).

This is incorrect usage, because cite is not for quotes:

<p><cite>This is wrong!</cite>, said Ian.</p>

This is also incorrect usage, because a person is not a work:

<p><q>This is still wrong!</q>, said <cite>Ian</cite>.</p>

The correct usage does not use a cite element:

<p><q>This is correct</q>, said Ian.</p>

As mentioned above, the b element might be relevant for marking names as being keywords in certain kinds of documents:

<p>And then <b>Ian</b> said <q>this might be right, in a
gossip column, maybe!</q>.</p>

4.5.7 The q element

Element/q

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
cite — Link to the source of the quotation or more information about the edit
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLQuoteElement.

The q element represents some phrasing content quoted from another source.

Quotation punctuation (such as quotation marks) that is quoting the contents of the element must not appear immediately before, after, or inside q elements; they will be inserted into the rendering by the user agent.

Content inside a q element must be quoted from another source, whose address, if it has one, may be cited in the cite attribute. The source may be fictional, as when quoting characters in a novel or screenplay.

If the cite attribute is present, it must be a valid URL potentially surrounded by spaces. To obtain the corresponding citation link, the value of the attribute must be parsed relative to the element's node document. User agents may allow users to follow such citation links, but they are primarily intended for private use (e.g., by server-side scripts collecting statistics about a site's use of quotations), not for readers.

The q element must not be used in place of quotation marks that do not represent quotes; for example, it is inappropriate to use the q element for marking up sarcastic statements.

The use of q elements to mark up quotations is entirely optional; using explicit quotation punctuation without q elements is just as correct.

Here is a simple example of the use of the q element:

<p>The man said <q>Things that are impossible just take
longer</q>. I disagreed with him.</p>

Here is an example with both an explicit citation link in the q element, and an explicit citation outside:

<p>The W3C page <cite>About W3C</cite> says the W3C's
mission is <q cite="https://www.w3.org/Consortium/">To lead the
World Wide Web to its full potential by developing protocols and
guidelines that ensure long-term growth for the Web</q>. I
disagree with this mission.</p>

In the following example, the quotation itself contains a quotation:

<p>In <cite>Example One</cite>, he writes <q>The man
said <q>Things that are impossible just take longer</q>. I
disagreed with him</q>. Well, I disagree even more!</p>

In the following example, quotation marks are used instead of the q element:

<p>His best argument was ❝I disagree❞, which
I thought was laughable.</p>

In the following example, there is no quote — the quotation marks are used to name a word. Use of the q element in this case would be inappropriate.

<p>The word "ineffable" could have been used to describe the disaster
resulting from the campaign's mismanagement.</p>

4.5.8 The dfn element

Element/dfn

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content, but there must be no dfn element descendants.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Also, the title attribute has special semantics on this element: Full term or expansion of abbreviation.
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The dfn element represents the defining instance of a term. The paragraph, description list group, or section that is the nearest ancestor of the dfn element must also contain the definition(s) for the term given by the dfn element.

Defining term: if the dfn element has a title attribute, then the exact value of that attribute is the term being defined. Otherwise, if it contains exactly one element child node and no child Text nodes, and that child element is an abbr element with a title attribute, then the exact value of that attribute is the term being defined. Otherwise, it is the descendant text content of the dfn element that gives the term being defined.

If the title attribute of the dfn element is present, then it must contain only the term being defined.

The title attribute of ancestor elements does not affect dfn elements.

An a element that links to a dfn element represents an instance of the term defined by the dfn element.

In the following fragment, the term "Garage Door Opener" is first defined in the first paragraph, then used in the second. In both cases, its abbreviation is what is actually displayed.

<p>The <dfn><abbr title="Garage Door Opener">GDO</abbr></dfn>
is a device that allows off-world teams to open the iris.</p>
<!-- ... later in the document: -->
<p>Teal'c activated his <abbr title="Garage Door Opener">GDO</abbr>
and so Hammond ordered the iris to be opened.</p>

With the addition of an a element, the reference can be made explicit:

<p>The <dfn id=gdo><abbr title="Garage Door Opener">GDO</abbr></dfn>
is a device that allows off-world teams to open the iris.</p>
<!-- ... later in the document: -->
<p>Teal'c activated his <a href=#gdo><abbr title="Garage Door Opener">GDO</abbr></a>
and so Hammond ordered the iris to be opened.</p>

4.5.9 The abbr element

Element/abbr

Support in all current engines.

Firefox1+SafariYesChrome2+
OperaYesEdge79+
Edge (Legacy)12+Internet Explorer7+
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Also, the title attribute has special semantics on this element: Full term or expansion of abbreviation.
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The abbr element represents an abbreviation or acronym, optionally with its expansion. The title attribute may be used to provide an expansion of the abbreviation. The attribute, if specified, must contain an expansion of the abbreviation, and nothing else.

The paragraph below contains an abbreviation marked up with the abbr element. This paragraph defines the term "Web Hypertext Application Technology Working Group".

<p>The <dfn id=whatwg><abbr
title="Web Hypertext Application Technology Working Group">WHATWG</abbr></dfn>
is a loose unofficial collaboration of web browser manufacturers and
interested parties who wish to develop new technologies designed to
allow authors to write and deploy Applications over the World Wide
Web.</p>

An alternative way to write this would be:

<p>The <dfn id=whatwg>Web Hypertext Application Technology
Working Group</dfn> (<abbr
title="Web Hypertext Application Technology Working Group">WHATWG</abbr>)
is a loose unofficial collaboration of web browser manufacturers and
interested parties who wish to develop new technologies designed to
allow authors to write and deploy Applications over the World Wide
Web.</p>

This paragraph has two abbreviations. Notice how only one is defined; the other, with no expansion associated with it, does not use the abbr element.

<p>The
<abbr title="Web Hypertext Application Technology Working Group">WHATWG</abbr>
started working on HTML5 in 2004.</p>

This paragraph links an abbreviation to its definition.

<p>The <a href="#whatwg"><abbr
title="Web Hypertext Application Technology Working Group">WHATWG</abbr></a>
community does not have much representation from Asia.</p>

This paragraph marks up an abbreviation without giving an expansion, possibly as a hook to apply styles for abbreviations (e.g. smallcaps).

<p>Philip` and Dashiva both denied that they were going to
get the issue counts from past revisions of the specification to
backfill the <abbr>WHATWG</abbr> issue graph.</p>

If an abbreviation is pluralized, the expansion's grammatical number (plural vs singular) must match the grammatical number of the contents of the element.

Here the plural is outside the element, so the expansion is in the singular:

<p>Two <abbr title="Working Group">WG</abbr>s worked on
this specification: the <abbr>WHATWG</abbr> and the
<abbr>HTMLWG</abbr>.</p>

Here the plural is inside the element, so the expansion is in the plural:

<p>Two <abbr title="Working Groups">WGs</abbr> worked on
this specification: the <abbr>WHATWG</abbr> and the
<abbr>HTMLWG</abbr>.</p>

Abbreviations do not have to be marked up using this element. It is expected to be useful in the following cases:

Providing an expansion in a title attribute once will not necessarily cause other abbr elements in the same document with the same contents but without a title attribute to behave as if they had the same expansion. Every abbr element is independent.

4.5.10 The ruby element

Element/ruby

Support in all current engines.

Firefox38+Safari5+Chrome5+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android38+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android14+
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
See prose.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The ruby element allows one or more spans of phrasing content to be marked with ruby annotations. Ruby annotations are short runs of text presented alongside base text, primarily used in East Asian typography as a guide for pronunciation or to include other annotations. In Japanese, this form of typography is also known as furigana.

The content model of ruby elements consists of one or more of the following sequences:

  1. One or the other of the following:
  2. One or the other of the following:

The ruby and rt elements can be used for a variety of kinds of annotations, including in particular (though by no means limited to) those described below. For more details on Japanese Ruby in particular, and how to render Ruby for Japanese, see Requirements for Japanese Text Layout. [JLREQ]

At the time of writing, CSS does not yet provide a way to fully control the rendering of the HTML ruby element. It is hoped that CSS will be extended to support the styles described below in due course.

Mono-ruby for individual base characters in Japanese

One or more hiragana or katakana characters (the ruby annotation) are placed with each ideographic character (the base text). This is used to provide readings of kanji characters.

<ruby>B<rt>annotation</ruby>

In this example, notice how each annotation corresponds to a single base character.

<ruby>君<rt>くん</ruby><ruby>子<rt>し</ruby>は<ruby>和<rt>わ</ruby>して<ruby>同<rt>どう</ruby>ぜず。

くんしてどうぜず。

This example can also be written as follows, using one ruby element with two segments of base text and two annotations (one for each) rather than two back-to-back ruby elements each with one base text segment and annotation (as in the markup above):

<ruby>君<rt>くん</rt>子<rt>し</ruby>は<ruby>和<rt>わ</ruby>して<ruby>同<rt>どう</ruby>ぜず。
Mono-ruby for compound words (jukugo)

This is similar to the previous case: each ideographic character in the compound word (the base text) has its reading given in hiragana or katakana characters (the ruby annotation). The difference is that the base text segments form a compound word rather than being separate from each other.

<ruby>B<rt>annotation</rt>B<rt>annotation</ruby>

In this example, notice again how each annotation corresponds to a single base character. In this example, each compound word (jukugo) corresponds to a single ruby element.

The rendering here is expected to be that each annotation be placed over (or next to, in vertical text) the corresponding base character, with the annotations not overhanging any of the adjacent characters.

<ruby>鬼<rt>き</rt>門<rt>もん</rt></ruby>の<ruby>方<rt>ほう</rt>角<rt>がく</rt></ruby>を<ruby>凝<rt>ぎょう</rt>視<rt>し</rt></ruby>する

もんほうがくぎょうする

Jukugo-ruby

This is semantically identical to the previous case (each individual ideographic character in the base compound word has its reading given in an annotation in hiragana or katakana characters), but the rendering is the more complicated Jukugo Ruby rendering.

This is the same example as above for mono-ruby for compound words. The different rendering is expected to be achieved using different styling (e.g. in CSS), and is not shown here.

<ruby>鬼<rt>き</rt>門<rt>もん</rt></ruby>の<ruby>方<rt>ほう</rt>角<rt>がく</rt></ruby>を<ruby>凝<rt>ぎょう</rt>視<rt>し</rt></ruby>する

For more details on Jukugo Ruby rendering, see Appendix F in the Requirements for Japanese Text Layout. [JLREQ]

Group ruby for describing meanings

The annotation describes the meaning of the base text, rather than (or in addition to) the pronunciation. As such, both the base text and the annotation can be multiple characters long.

<ruby>BASE<rt>annotation</ruby>

Here a compound ideographic word has its corresponding katakana given as an annotation.

<ruby>境界面<rt>インターフェース</ruby>

境界面インターフェース

Here a compound ideographic word has its translation in English provided as an annotation.

<ruby lang="ja">編集者<rt lang="en">editor</ruby>

編集者editor

Group ruby for Jukuji readings

A phonetic reading that corresponds to multiple base characters, because a one-to-one mapping would be difficult. (In English, the words "Colonel" and "Lieutenant" are examples of words where a direct mapping of pronunciation to individual letters is, in some dialects, rather unclear.)

In this example, the name of a species of flowers has a phonetic reading provided using group ruby:

<ruby>紫陽花<rt>あじさい</ruby>

紫陽花あじさい

Text with both phonetic and semantic annotations (double-sided ruby)

Sometimes, ruby styles described above are combined.

If this results in two annotations covering the same single base segment, then the annotations can just be placed back to back.

<ruby>BASE<rt>annotation 1<rt>annotation 2</ruby>
<ruby>B<rt>a<rt>a</ruby><ruby>A<rt>a<rt>a</ruby><ruby>S<rt>a<rt>a</ruby><ruby>E<rt>a<rt>a</ruby>

In this contrived example, some symbols are given names in English and French.

<ruby>
 ♥ <rt> Heart <rt lang=fr> Cœur </rt>
 ☘ <rt> Shamrock <rt lang=fr> Trèfle </rt>
 ✶ <rt> Star <rt lang=fr> Étoile </rt>
</ruby>

In more complication situations such as following examples, a nested ruby element is used to give the inner annotations, and then that whole ruby is then given an annotation at the "outer" level.

<ruby><ruby>B<rt>a</rt>A<rt>n</rt>S<rt>t</rt>E<rt>n</rt></ruby><rt>annotation</ruby>

Here both a phonetic reading and the meaning are given in ruby annotations. The annotation on the nested ruby element gives a mono-ruby phonetic annotation for each base character, while the annotation in the rt element that is a child of the outer ruby element gives the meaning using hiragana.

<ruby><ruby>東<rt>とう</rt>南<rt>なん</rt></ruby><rt>たつみ</rt></ruby>の方角

とうなんたつみの方角

This is the same example, but the meaning is given in English instead of Japanese:

<ruby><ruby>東<rt>とう</rt>南<rt>なん</rt></ruby><rt lang=en>Southeast</rt></ruby>の方角

とうなんSoutheastの方角


Within a ruby element that does not have a ruby element ancestor, content is segmented and segments are placed into three categories: base text segments, annotation segments, and ignored segments. Ignored segments do not form part of the document's semantics (they consist of some inter-element whitespace and rp elements, the latter of which are used for legacy user agents that do not support ruby at all). Base text segments can overlap (with a limit of two segments overlapping any one position in the DOM, and with any segment having an earlier start point than an overlapping segment also having an equal or later end point, and any segment have a later end point than an overlapping segment also having an equal or earlier start point). Annotation segments correspond to rt elements. Each annotation segment can be associated with a base text segment, and each base text segment can have annotation segments associated with it. (In a conforming document, each base text segment is associated with at least one annotation segment, and each annotation segment is associated with one base text segment.) A ruby element represents the union of the segments of base text it contains, along with the mapping from those base text segments to annotation segments. Segments are described in terms of DOM ranges; annotation segment ranges always consist of exactly one element. [DOM]

At any particular time, the segmentation and categorization of content of a ruby element is the result that would be obtained from running the following algorithm:

  1. Let base text segments be an empty list of base text segments, each potentially with a list of base text subsegments.

  2. Let annotation segments be an empty list of annotation segments, each potentially being associated with a base text segment or subsegment.

  3. Let root be the ruby element for which the algorithm is being run.

  4. If root has a ruby element ancestor, then jump to the step labeled end.

  5. Let current parent be root.

  6. Let index be 0.

  7. Let start index be null.

  8. Let parent start index be null.

  9. Let current base text be null.

  10. Start mode: If index is equal to or greater than the number of child nodes in current parent, then jump to the step labeled end mode.

  11. If the indexth node in current parent is an rt or rp element, jump to the step labeled annotation mode.

  12. Set start index to the value of index.

  13. Base mode: If the indexth node in current parent is a ruby element, and if current parent is the same element as root, then push a ruby level and then jump to the step labeled start mode.

  14. If the indexth node in current parent is an rt or rp element, then set the current base text and then jump to the step labeled annotation mode.

  15. Increment index by one.

  16. Base mode post-increment: If index is equal to or greater than the number of child nodes in current parent, then jump to the step labeled end mode.

  17. Jump back to the step labeled base mode.

  18. Annotation mode: If the indexth node in current parent is an rt element, then push a ruby annotation and jump to the step labeled annotation mode increment.

  19. If the indexth node in current parent is an rp element, jump to the step labeled annotation mode increment.

  20. If the indexth node in current parent is not a Text node, or is a Text node that is not inter-element whitespace, then jump to the step labeled base mode.

  21. Annotation mode increment: Let lookahead index be index plus one.

  22. Annotation mode white-space skipper: If lookahead index is equal to the number of child nodes in current parent then jump to the step labeled end mode.

  23. If the lookahead indexth node in current parent is an rt element or an rp element, then set index to lookahead index and jump to the step labeled annotation mode.

  24. If the lookahead indexth node in current parent is not a Text node, or is a Text node that is not inter-element whitespace, then jump to the step labeled base mode (without further incrementing index, so the inter-element whitespace seen so far becomes part of the next base text segment).

  25. Increment lookahead index by one.

  26. Jump to the step labeled annotation mode white-space skipper.

  27. End mode: If current parent is not the same element as root, then pop a ruby level and jump to the step labeled base mode post-increment.

  28. End: Return base text segments and annotation segments. Any content of the ruby element not described by segments in either of those lists is implicitly in an ignored segment.

When the steps above say to set the current base text, it means to run the following steps at that point in the algorithm:

  1. Let text range be a DOM range whose start is the boundary point (current parent, start index) and whose end is the boundary point (current parent, index).

  2. Let new text segment be a base text segment described by the range annotation range.

  3. Add new text segment to base text segments.

  4. Let current base text be new text segment.

  5. Let start index be null.

When the steps above say to push a ruby level, it means to run the following steps at that point in the algorithm:

  1. Let current parent be the indexth node in current parent.

  2. Let index be 0.

  3. Set saved start index to the value of start index.

  4. Let start index be null.

When the steps above say to pop a ruby level, it means to run the following steps at that point in the algorithm:

  1. Let index be the position of current parent in root.

  2. Let current parent be root.

  3. Increment index by one.

  4. Set start index to the value of saved start index.

  5. Let saved start index be null.

When the steps above say to push a ruby annotation, it means to run the following steps at that point in the algorithm:

  1. Let rt be the rt element that is the indexth node of current parent.

  2. Let annotation range be a DOM range whose start is the boundary point (current parent, index) and whose end is the boundary point (current parent, index plus one) (i.e. that contains only rt).

  3. Let new annotation segment be an annotation segment described by the range annotation range.

  4. If current base text is not null, associate new annotation segment with current base text.

  5. Add new annotation segment to annotation segments.

In this example, each ideograph in the Japanese text 漢字 is annotated with its reading in hiragana.

...
<ruby>漢<rt>かん</rt>字<rt>じ</rt></ruby>
...

This might be rendered as:

The two main ideographs, each with its annotation in hiragana rendered in a smaller font above it.

In this example, each ideograph in the traditional Chinese text 漢字 is annotated with its bopomofo reading.

<ruby>漢<rt>ㄏㄢˋ</rt>字<rt>ㄗˋ</rt></ruby>

This might be rendered as:

The two main ideographs, each with its bopomofo annotation rendered in a smaller font next to it.

In this example, each ideograph in the simplified Chinese text 汉字 is annotated with its pinyin reading.

...<ruby>汉<rt>hàn</rt>字<rt>zì</rt></ruby>...

This might be rendered as:

The two main ideographs, each with its pinyin annotation rendered in a smaller font above it.

In this more contrived example, the acronym "HTML" has four annotations: one for the whole acronym, briefly describing what it is, one for the letters "HT" expanding them to "Hypertext", one for the letter "M" expanding it to "Markup", and one for the letter "L" expanding it to "Language".

<ruby>
 <ruby>HT<rt>Hypertext</rt>M<rt>Markup</rt>L<rt>Language</rt></ruby>
 <rt>An abstract language for describing documents and applications
</ruby>

4.5.11 The rt element

Element/rt

Support in all current engines.

Firefox38+Safari5+Chrome5+
Opera15+Edge79+
Edge (Legacy)NoInternet Explorer5+
Firefox Android38+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android14+
Categories:
None.
Contexts in which this element can be used:
As a child of a ruby element.
Content model:
Phrasing content.
text/html 中的标签省略
An rt element's end tag can be omitted if the rt element is immediately followed by an rt or rp element, or if there is no more content in the parent element.
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The rt element marks the ruby text component of a ruby annotation. When it is the child of a ruby element, it doesn't represent anything itself, but the ruby element uses it as part of determining what it represents.

An rt element that is not a child of a ruby element represents the same thing as its children.

4.5.12 The rp element

Element/rp

Support in all current engines.

Firefox38+Safari5+Chrome5+
Opera15+Edge79+
Edge (Legacy)NoInternet Explorer5+
Firefox Android38+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android14+
Categories:
None.
Contexts in which this element can be used:
As a child of a ruby element, either immediately before or immediately after an rt element.
Content model:
Text.
text/html 中的标签省略
An rp element's end tag can be omitted if the rp element is immediately followed by an rt or rp element, or if there is no more content in the parent element.
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The rp element can be used to provide parentheses or other content around a ruby text component of a ruby annotation, to be shown by user agents that don't support ruby annotations.

An rp element that is a child of a ruby element represents nothing. An rp element whose parent element is not a ruby element represents its children.

The example above, in which each ideograph in the text 漢字 is annotated with its phonetic reading, could be expanded to use rp so that in legacy user agents the readings are in parentheses:

...
<ruby>漢<rp>(</rp><rt>かん</rt><rp>)</rp>字<rp>(</rp><rt>じ</rt><rp>)</rp></ruby>
...

In conforming user agents the rendering would be as above, but in user agents that do not support ruby, the rendering would be:

... 漢(かん)字(じ)...

When there are multiple annotations for a segment, rp elements can also be placed between the annotations. Here is another copy of an earlier contrived example showing some symbols with names given in English and French, but this time with rp elements as well:

<ruby>
♥<rp>: </rp><rt>Heart</rt><rp>, </rp><rt lang=fr>Cœur</rt><rp>.</rp>
☘<rp>: </rp><rt>Shamrock</rt><rp>, </rp><rt lang=fr>Trèfle</rt><rp>.</rp>
✶<rp>: </rp><rt>Star</rt><rp>, </rp><rt lang=fr>Étoile</rt><rp>.</rp>
</ruby>

This would make the example render as follows in non-ruby-capable user agents:

♥: Heart, Cœur. ☘: Shamrock, Trèfle. ✶: Star, Étoile.

4.5.13 The data element

Element/data

Support in all current engines.

Firefox22+Safari10+Chrome62+
Opera49+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android22+Safari iOS10+Chrome Android62+WebView Android62+Samsung Internet8.0+Opera Android46+

HTMLDataElement

Support in all current engines.

Firefox22+Safari10+Chrome62+
Opera49+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android22+Safari iOS10+Chrome Android62+WebView Android62+Samsung Internet8.0+Opera Android46+
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
value — Machine-readable value
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLDataElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString value;
};

The data element represents its contents, along with a machine-readable form of those contents in the value attribute.

The value attribute must be present. Its value must be a representation of the element's contents in a machine-readable format.

When the value is date- or time-related, the more specific time element can be used instead.

The element can be used for several purposes.

When combined with microformats or the microdata attributes defined in this specification, the element serves to provide both a machine-readable value for the purposes of data processors, and a human-readable value for the purposes of rendering in a web browser. In this case, the format to be used in the value attribute is determined by the microformats or microdata vocabulary in use.

The element can also, however, be used in conjunction with scripts in the page, for when a script has a literal value to store alongside a human-readable value. In such cases, the format to be used depends only on the needs of the script. (The data-* attributes can also be useful in such situations.)

HTMLDataElement/value

Support in all current engines.

Firefox22+Safari10+Chrome62+
Opera49+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android22+Safari iOS10+Chrome Android62+WebView Android62+Samsung Internet8.0+Opera Android46+

The value IDL attribute must reflect the content attribute of the same name.

Here, a short table has its numeric values encoded using the data element so that the table sorting JavaScript library can provide a sorting mechanism on each column despite the numbers being presented in textual form in one column and in a decomposed form in another.

<script src="sortable.js"></script>
<table class="sortable">
 <thead> <tr> <th> Game <th> Corporations <th> Map Size
 <tbody>
  <tr> <td> 1830 <td> <data value="8">Eight</data> <td> <data value="93">19+74 hexes (93 total)</data>
  <tr> <td> 1856 <td> <data value="11">Eleven</data> <td> <data value="99">12+87 hexes (99 total)</data>
  <tr> <td> 1870 <td> <data value="10">Ten</data> <td> <data value="149">4+145 hexes (149 total)</data>
</table>

4.5.14 The time element

Element/time

Support in all current engines.

Firefox22+Safari7+Chrome62+
Opera49+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android22+Safari iOS4+Chrome Android62+WebView Android62+Samsung Internet8.0+Opera Android46+

HTMLTimeElement

Support in all current engines.

Firefox22+Safari10+Chrome62+
Opera49+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android22+Safari iOS10+Chrome Android62+WebView Android62+Samsung Internet8.0+Opera Android46+
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
If the element has a datetime attribute: Phrasing content.
Otherwise: Text, but must match requirements described in prose below.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
datetime — Machine-readable value
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLTimeElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString dateTime;
};

The time element represents its contents, along with a machine-readable form of those contents in the datetime attribute. The kind of content is limited to various kinds of dates, times, time-zone offsets, and durations, as described below.

The datetime attribute may be present. If present, its value must be a representation of the element's contents in a machine-readable format.

A time element that does not have a datetime content attribute must not have any element descendants.

The datetime value of a time element is the value of the element's datetime content attribute, if it has one, otherwise the child text content of the time element.

The datetime value of a time element must match one of the following syntaxes.

A valid month string
<time>2011-11</time>
A valid date string
<time>2011-11-18</time>
A valid yearless date string
<time>11-18</time>
A valid time string
<time>14:54</time>
<time>14:54:39</time>
<time>14:54:39.929</time>
A valid local date and time string
<time>2011-11-18T14:54</time>
<time>2011-11-18T14:54:39</time>
<time>2011-11-18T14:54:39.929</time>
<time>2011-11-18 14:54</time>
<time>2011-11-18 14:54:39</time>
<time>2011-11-18 14:54:39.929</time>

Times with dates but without a time zone offset are useful for specifying events that are observed at the same specific time in each time zone, throughout a day. For example, the 2020 new year is celebrated at 2020-01-01 00:00 in each time zone, not at the same precise moment across all time zones. For events that occur at the same time across all time zones, for example a videoconference meeting, a valid global date and time string is likely more useful.

A valid time-zone offset string
<time>Z</time>
<time>+0000</time>
<time>+00:00</time>
<time>-0800</time>
<time>-08:00</time>

For times without dates (or times referring to events that recur on multiple dates), specifying the geographic location that controls the time is usually more useful than specifying a time zone offset, because geographic locations change time zone offsets with daylight saving time. In some cases, geographic locations even change time zone, e.g. when the boundaries of those time zones are redrawn, as happened with Samoa at the end of 2011. There exists a time zone database that describes the boundaries of time zones and what rules apply within each such zone, known as the time zone database. [TZDATABASE]

A valid global date and time string
<time>2011-11-18T14:54Z</time>
<time>2011-11-18T14:54:39Z</time>
<time>2011-11-18T14:54:39.929Z</time>
<time>2011-11-18T14:54+0000</time>
<time>2011-11-18T14:54:39+0000</time>
<time>2011-11-18T14:54:39.929+0000</time>
<time>2011-11-18T14:54+00:00</time>
<time>2011-11-18T14:54:39+00:00</time>
<time>2011-11-18T14:54:39.929+00:00</time>
<time>2011-11-18T06:54-0800</time>
<time>2011-11-18T06:54:39-0800</time>
<time>2011-11-18T06:54:39.929-0800</time>
<time>2011-11-18T06:54-08:00</time>
<time>2011-11-18T06:54:39-08:00</time>
<time>2011-11-18T06:54:39.929-08:00</time>
<time>2011-11-18 14:54Z</time>
<time>2011-11-18 14:54:39Z</time>
<time>2011-11-18 14:54:39.929Z</time>
<time>2011-11-18 14:54+0000</time>
<time>2011-11-18 14:54:39+0000</time>
<time>2011-11-18 14:54:39.929+0000</time>
<time>2011-11-18 14:54+00:00</time>
<time>2011-11-18 14:54:39+00:00</time>
<time>2011-11-18 14:54:39.929+00:00</time>
<time>2011-11-18 06:54-0800</time>
<time>2011-11-18 06:54:39-0800</time>
<time>2011-11-18 06:54:39.929-0800</time>
<time>2011-11-18 06:54-08:00</time>
<time>2011-11-18 06:54:39-08:00</time>
<time>2011-11-18 06:54:39.929-08:00</time>

Times with dates and a time zone offset are useful for specifying specific events, or recurring virtual events where the time is not anchored to a specific geographic location. For example, the precise time of an asteroid impact, or a particular meeting in a series of meetings held at 1400 UTC every day, regardless of whether any particular part of the world is observing daylight saving time or not. For events where the precise time varies by the local time zone offset of a specific geographic location, a valid local date and time string combined with that geographic location is likely more useful.

A valid week string
<time>2011-W47</time>
Four or more ASCII digits, at least one of which is not U+0030 DIGIT ZERO (0)
<time>2011</time>
<time>0001</time>
A valid duration string
<time>PT4H18M3S</time>
<time>4h 18m 3s</time>

The machine-readable equivalent of the element's contents must be obtained from the element's datetime value by using the following algorithm:

  1. If parsing a month string from the element's datetime value returns a month, that is the machine-readable equivalent; return.

  2. If parsing a date string from the element's datetime value returns a date, that is the machine-readable equivalent; return.

  3. If parsing a yearless date string from the element's datetime value returns a yearless date, that is the machine-readable equivalent; return.

  4. If parsing a time string from the element's datetime value returns a time, that is the machine-readable equivalent; return.

  5. If parsing a local date and time string from the element's datetime value returns a local date and time, that is the machine-readable equivalent; return.

  6. If parsing a time-zone offset string from the element's datetime value returns a time-zone offset, that is the machine-readable equivalent; return.

  7. If parsing a global date and time string from the element's datetime value returns a global date and time, that is the machine-readable equivalent; return.

  8. If parsing a week string from the element's datetime value returns a week, that is the machine-readable equivalent; return.

  9. If the element's datetime value consists of only ASCII digits, at least one of which is not U+0030 DIGIT ZERO (0), then the machine-readable equivalent is the base-ten interpretation of those digits, representing a year; return.

  10. If parsing a duration string from the element's datetime value returns a duration, that is the machine-readable equivalent; return.

  11. There is no machine-readable equivalent.

The algorithms referenced above are intended to be designed such that for any arbitrary string s, only one of the algorithms returns a value. A more efficient approach might be to create a single algorithm that parses all these data types in one pass; developing such an algorithm is left as an exercise to the reader.

HTMLTimeElement/dateTime

Support in all current engines.

Firefox22+Safari10+Chrome62+
Opera49+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android22+Safari iOS10+Chrome Android62+WebView Android62+Samsung Internet8.0+Opera Android46+

The dateTime IDL attribute must reflect the element's datetime content attribute.

The time element can be used to encode dates, for example in microformats. The following shows a hypothetical way of encoding an event using a variant on hCalendar that uses the time element:

<div class="vevent">
 <a class="url" href="http://www.web2con.com/">http://www.web2con.com/</a>
 <span class="summary">Web 2.0 Conference</span>:
 <time class="dtstart" datetime="2005-10-05">October 5</time> -
 <time class="dtend" datetime="2005-10-07">7</time>,
 at the <span class="location">Argent Hotel, San Francisco, CA</span>
</div>

Here, a fictional microdata vocabulary based on the Atom vocabulary is used with the time element to mark up a blog post's publication date.

<article itemscope itemtype="https://n.example.org/rfc4287">
 <h1 itemprop="title">Big tasks</h1>
 <footer>Published <time itemprop="published" datetime="2009-08-29">two days ago</time>.</footer>
 <p itemprop="content">Today, I went out and bought a bike for my kid.</p>
</article>

In this example, another article's publication date is marked up using time, this time using the schema.org microdata vocabulary:

<article itemscope itemtype="http://schema.org/BlogPosting">
 <h1 itemprop="headline">Small tasks</h1>
 <footer>Published <time itemprop="datePublished" datetime="2009-08-30">yesterday</time>.</footer>
 <p itemprop="articleBody">I put a bike bell on her bike.</p>
</article>

In the following snippet, the time element is used to encode a date in the ISO8601 format, for later processing by a script:

<p>Our first date was <time datetime="2006-09-23">a Saturday</time>.</p>

In this second snippet, the value includes a time:

<p>We stopped talking at <time datetime="2006-09-24T05:00-07:00">5am the next morning</time>.</p>

A script loaded by the page (and thus privy to the page's internal convention of marking up dates and times using the time element) could scan through the page and look at all the time elements therein to create an index of dates and times.

For example, this element conveys the string "Friday" with the additional semantic that the 18th of November 2011 is the meaning that corresponds to "Friday":

Today is <time datetime="2011-11-18">Friday</time>.

In this example, a specific time in the Pacific Standard Time timezone is specified:

Your next meeting is at <time datetime="2011-11-18T15:00-08:00">3pm</time>.

4.5.15 The code element

Element/code

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The code element represents a fragment of computer code. This could be an XML element name, a file name, a computer program, or any other string that a computer would recognize.

There is no formal way to indicate the language of computer code being marked up. Authors who wish to mark code elements with the language used, e.g. so that syntax highlighting scripts can use the right rules, can use the class attribute, e.g. by adding a class prefixed with "language-" to the element.

The following example shows how the element can be used in a paragraph to mark up element names and computer code, including punctuation.

<p>The <code>code</code> element represents a fragment of computer
code.</p>

<p>When you call the <code>activate()</code> method on the
<code>robotSnowman</code> object, the eyes glow.</p>

<p>The example below uses the <code>begin</code> keyword to indicate
the start of a statement block. It is paired with an <code>end</code>
keyword, which is followed by the <code>.</code> punctuation character
(full stop) to indicate the end of the program.</p>

The following example shows how a block of code could be marked up using the pre and code elements.

<pre><code class="language-pascal">var i: Integer;
begin
   i := 1;
end.</code></pre>

A class is used in that example to indicate the language used.

See the pre element for more details.

4.5.16 The var element

Element/var

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The var element represents a variable. This could be an actual variable in a mathematical expression or programming context, an identifier representing a constant, a symbol identifying a physical quantity, a function parameter, or just be a term used as a placeholder in prose.

In the paragraph below, the letter "n" is being used as a variable in prose:

<p>If there are <var>n</var> pipes leading to the ice
cream factory then I expect at <em>least</em> <var>n</var>
flavors of ice cream to be available for purchase!</p>

For mathematics, in particular for anything beyond the simplest of expressions, MathML is more appropriate. However, the var element can still be used to refer to specific variables that are then mentioned in MathML expressions.

In this example, an equation is shown, with a legend that references the variables in the equation. The expression itself is marked up with MathML, but the variables are mentioned in the figure's legend using var.

<figure>
 <math>
  <mi>a</mi>
  <mo>=</mo>
  <msqrt>
   <msup><mi>b</mi><mn>2</mn></msup>
   <mi>+</mi>
   <msup><mi>c</mi><mn>2</mn></msup>
  </msqrt>
 </math>
 <figcaption>
  Using Pythagoras' theorem to solve for the hypotenuse <var>a</var> of
  a triangle with sides <var>b</var> and <var>c</var>
 </figcaption>
</figure>

Here, the equation describing mass-energy equivalence is used in a sentence, and the var element is used to mark the variables and constants in that equation:

<p>Then she turned to the blackboard and picked up the chalk. After a few moment's
thought, she wrote <var>E</var> = <var>m</var> <var>c</var><sup>2</sup>. The teacher
looked pleased.</p>

4.5.17 The samp element

Element/samp

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The samp element represents sample or quoted output from another program or computing system.

See the pre and kbd elements for more details.

This element can be contrasted with the output element, which can be used to provide immediate output in a web application.

This example shows the samp element being used inline:

<p>The computer said <samp>Too much cheese in tray
two</samp> but I didn't know what that meant.</p>

This second example shows a block of sample output from a console program. Nested samp and kbd elements allow for the styling of specific elements of the sample output using a style sheet. There's also a few parts of the samp that are annotated with even more detailed markup, to enable very precise styling. To achieve this, span elements are used.

<pre><samp><span class="prompt">jdoe@mowmow:~$</span> <kbd>ssh demo.example.com</kbd>
Last login: Tue Apr 12 09:10:17 2005 from mowmow.example.com on pts/1
Linux demo 2.6.10-grsec+gg3+e+fhs6b+nfs+gr0501+++p3+c4a+gr2b-reslog-v6.189 #1 SMP Tue Feb 1 11:22:36 PST 2005 i686 unknown

<span class="prompt">jdoe@demo:~$</span> <span class="cursor">_</span></samp></pre>

This third example shows a block of input and its respective output. The example uses both code and samp elements.

<pre>
<code class="language-javascript">console.log(2.3 + 2.4)</code>
<samp>4.699999999999999</samp>
</pre>

4.5.18 The kbd element

Element/kbd

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The kbd element represents user input (typically keyboard input, although it may also be used to represent other input, such as voice commands).

When the kbd element is nested inside a samp element, it represents the input as it was echoed by the system.

When the kbd element contains a samp element, it represents input based on system output, for example invoking a menu item.

When the kbd element is nested inside another kbd element, it represents an actual key or other single unit of input as appropriate for the input mechanism.

Here the kbd element is used to indicate keys to press:

<p>To make George eat an apple, press <kbd><kbd>Shift</kbd>+<kbd>F3</kbd></kbd></p>

In this second example, the user is told to pick a particular menu item. The outer kbd element marks up a block of input, with the inner kbd elements representing each individual step of the input, and the samp elements inside them indicating that the steps are input based on something being displayed by the system, in this case menu labels:

<p>To make George eat an apple, select
    <kbd><kbd><samp>File</samp></kbd>|<kbd><samp>Eat Apple...</samp></kbd></kbd>
</p>

Such precision isn't necessary; the following is equally fine:

<p>To make George eat an apple, select <kbd>File | Eat Apple...</kbd></p>

4.5.19 The sub and sup elements

Element/sub

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Element/sup

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
The sub element: for authors; for implementers.
The sup element: for authors; for implementers.
DOM interface:
Use HTMLElement.

The sup element represents a superscript and the sub element represents a subscript.

These elements must be used only to mark up typographical conventions with specific meanings, not for typographical presentation for presentation's sake. For example, it would be inappropriate for the sub and sup elements to be used in the name of the LaTeX document preparation system. In general, authors should use these elements only if the absence of those elements would change the meaning of the content.

In certain languages, superscripts are part of the typographical conventions for some abbreviations.

<p>Their names are
<span lang="fr"><abbr>M<sup>lle</sup></abbr> Gwendoline</span> and
<span lang="fr"><abbr>M<sup>me</sup></abbr> Denise</span>.</p>

The sub element can be used inside a var element, for variables that have subscripts.

Here, the sub element is used to represent the subscript that identifies the variable in a family of variables:

<p>The coordinate of the <var>i</var>th point is
(<var>x<sub><var>i</var></sub></var>, <var>y<sub><var>i</var></sub></var>).
For example, the 10th point has coordinate
(<var>x<sub>10</sub></var>, <var>y<sub>10</sub></var>).</p>

Mathematical expressions often use subscripts and superscripts. Authors are encouraged to use MathML for marking up mathematics, but authors may opt to use sub and sup if detailed mathematical markup is not desired. [MATHML]

<var>E</var>=<var>m</var><var>c</var><sup>2</sup>
f(<var>x</var>, <var>n</var>) = log<sub>4</sub><var>x</var><sup><var>n</var></sup>

4.5.20 The i element

Element/i

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The i element represents a span of text in an alternate voice or mood, or otherwise offset from the normal prose in a manner indicating a different quality of text, such as a taxonomic designation, a technical term, an idiomatic phrase from another language, transliteration, a thought, or a ship name in Western texts.

Terms in languages different from the main text should be annotated with lang attributes (or, in XML, lang attributes in the XML namespace).

The examples below show uses of the i element:

<p>The <i class="taxonomy">Felis silvestris catus</i> is cute.</p>
<p>The term <i>prose content</i> is defined above.</p>
<p>There is a certain <i lang="fr">je ne sais quoi</i> in the air.</p>

In the following example, a dream sequence is marked up using i elements.

<p>Raymond tried to sleep.</p>
<p><i>The ship sailed away on Thursday</i>, he
dreamt. <i>The ship had many people aboard, including a beautiful
princess called Carey. He watched her, day-in, day-out, hoping she
would notice him, but she never did.</i></p>
<p><i>Finally one night he picked up the courage to speak with
her—</i></p>
<p>Raymond woke with a start as the fire alarm rang out.</p>

Authors can use the class attribute on the i element to identify why the element is being used, so that if the style of a particular use (e.g. dream sequences as opposed to taxonomic terms) is to be changed at a later date, the author doesn't have to go through the entire document (or series of related documents) annotating each use.

Authors are encouraged to consider whether other elements might be more applicable than the i element, for instance the em element for marking up stress emphasis, or the dfn element to mark up the defining instance of a term.

Style sheets can be used to format i elements, just like any other element can be restyled. Thus, it is not the case that content in i elements will necessarily be italicized.

4.5.21 The b element

Element/b

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The b element represents a span of text to which attention is being drawn for utilitarian purposes without conveying any extra importance and with no implication of an alternate voice or mood, such as key words in a document abstract, product names in a review, actionable words in interactive text-driven software, or an article lede.

The following example shows a use of the b element to highlight key words without marking them up as important:

<p>The <b>frobonitor</b> and <b>barbinator</b> components are fried.</p>

In the following example, objects in a text adventure are highlighted as being special by use of the b element.

<p>You enter a small room. Your <b>sword</b> glows
brighter. A <b>rat</b> scurries past the corner wall.</p>

Another case where the b element is appropriate is in marking up the lede (or lead) sentence or paragraph. The following example shows how a BBC article about kittens adopting a rabbit as their own could be marked up:

<article>
 <h2>Kittens 'adopted' by pet rabbit</h2>
 <p><b class="lede">Six abandoned kittens have found an
 unexpected new mother figure — a pet rabbit.</b></p>
 <p>Veterinary nurse Melanie Humble took the three-week-old
 kittens to her Aberdeen home.</p>
[...]

As with the i element, authors can use the class attribute on the b element to identify why the element is being used, so that if the style of a particular use is to be changed at a later date, the author doesn't have to go through annotating each use.

The b element should be used as a last resort when no other element is more appropriate. In particular, headings should use the h1 to h6 elements, stress emphasis should use the em element, importance should be denoted with the strong element, and text marked or highlighted should use the mark element.

The following would be incorrect usage:

<p><b>WARNING!</b> Do not frob the barbinator!</p>

In the previous example, the correct element to use would have been strong, not b.

Style sheets can be used to format b elements, just like any other element can be restyled. Thus, it is not the case that content in b elements will necessarily be boldened.

4.5.22 The u element

Element/u

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The u element represents a span of text with an unarticulated, though explicitly rendered, non-textual annotation, such as labeling the text as being a proper name in Chinese text (a Chinese proper name mark), or labeling the text as being misspelt.

In most cases, another element is likely to be more appropriate: for marking stress emphasis, the em element should be used; for marking key words or phrases either the b element or the mark element should be used, depending on the context; for marking book titles, the cite element should be used; for labeling text with explicit textual annotations, the ruby element should be used; for technical terms, taxonomic designation, transliteration, a thought, or for labeling ship names in Western texts, the i element should be used.

The default rendering of the u element in visual presentations clashes with the conventional rendering of hyperlinks (underlining). Authors are encouraged to avoid using the u element where it could be confused for a hyperlink.

In this example, a u element is used to mark a word as misspelt:

<p>The <u>see</u> is full of fish.</p>

4.5.23 The mark element

Element/mark

Support in all current engines.

Firefox4+SafariYesChromeYes
Opera11+EdgeYes
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The mark element represents a run of text in one document marked or highlighted for reference purposes, due to its relevance in another context. When used in a quotation or other block of text referred to from the prose, it indicates a highlight that was not originally present but which has been added to bring the reader's attention to a part of the text that might not have been considered important by the original author when the block was originally written, but which is now under previously unexpected scrutiny. When used in the main prose of a document, it indicates a part of the document that has been highlighted due to its likely relevance to the user's current activity.

This example shows how the mark element can be used to bring attention to a particular part of a quotation:

<p lang="en-US">Consider the following quote:</p>
<blockquote lang="en-GB">
 <p>Look around and you will find, no-one's really
 <mark>colour</mark> blind.</p>
</blockquote>
<p lang="en-US">As we can tell from the <em>spelling</em> of the word,
the person writing this quote is clearly not American.</p>

(If the goal was to mark the element as misspelt, however, the u element, possibly with a class, would be more appropriate.)

Another example of the mark element is highlighting parts of a document that are matching some search string. If someone looked at a document, and the server knew that the user was searching for the word "kitten", then the server might return the document with one paragraph modified as follows:

<p>I also have some <mark>kitten</mark>s who are visiting me
these days. They're really cute. I think they like my garden! Maybe I
should adopt a <mark>kitten</mark>.</p>

In the following snippet, a paragraph of text refers to a specific part of a code fragment.

<p>The highlighted part below is where the error lies:</p>
<pre><code>var i: Integer;
begin
   i := <mark>1.1</mark>;
end.</code></pre>

This is separate from syntax highlighting, for which span is more appropriate. Combining both, one would get:

<p>The highlighted part below is where the error lies:</p>
<pre><code><span class=keyword>var</span> <span class=ident>i</span>: <span class=type>Integer</span>;
<span class=keyword>begin</span>
   <span class=ident>i</span> := <span class=literal><mark>1.1</mark></span>;
<span class=keyword>end</span>.</code></pre>

This is another example showing the use of mark to highlight a part of quoted text that was originally not emphasized. In this example, common typographic conventions have led the author to explicitly style mark elements in quotes to render in italics.

<style>
 blockquote mark, q mark {
   font: inherit; font-style: italic;
   text-decoration: none;
   background: transparent; color: inherit;
 }
 .bubble em {
   font: inherit; font-size: larger;
   text-decoration: underline;
 }
</style>
<article>
 <h1>She knew</h1>
 <p>Did you notice the subtle joke in the joke on panel 4?</p>
 <blockquote>
  <p class="bubble">I didn't <em>want</em> to believe. <mark>Of course
  on some level I realized it was a known-plaintext attack.</mark> But I
  couldn't admit it until I saw for myself.</p>
 </blockquote>
 <p>(Emphasis mine.) I thought that was great. It's so pedantic, yet it
 explains everything neatly.</p>
</article>

Note, incidentally, the distinction between the em element in this example, which is part of the original text being quoted, and the mark element, which is highlighting a part for comment.

The following example shows the difference between denoting the importance of a span of text (strong) as opposed to denoting the relevance of a span of text (mark). It is an extract from a textbook, where the extract has had the parts relevant to the exam highlighted. The safety warnings, important though they may be, are apparently not relevant to the exam.

<h3>Wormhole Physics Introduction</h3>

<p><mark>A wormhole in normal conditions can be held open for a
maximum of just under 39 minutes.</mark> Conditions that can increase
the time include a powerful energy source coupled to one or both of
the gates connecting the wormhole, and a large gravity well (such as a
black hole).</p>

<p><mark>Momentum is preserved across the wormhole. Electromagnetic
radiation can travel in both directions through a wormhole,
but matter cannot.</mark></p>

<p>When a wormhole is created, a vortex normally forms.
<strong>Warning: The vortex caused by the wormhole opening will
annihilate anything in its path.</strong> Vortexes can be avoided when
using sufficiently advanced dialing technology.</p>

<p><mark>An obstruction in a gate will prevent it from accepting a
wormhole connection.</mark></p>

4.5.24 The bdi element

Element/bdi

Support in all current engines.

Firefox10+Safari6+Chrome16+
Opera15+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android10+Safari iOS6+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Also, the dir global attribute has special semantics on this element.
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The bdi element represents a span of text that is to be isolated from its surroundings for the purposes of bidirectional text formatting. [BIDI]

The dir global attribute defaults to auto on this element (it never inherits from the parent element like with other elements).

This element has rendering requirements involving the bidirectional algorithm.

This element is especially useful when embedding user-generated content with an unknown directionality.

In this example, usernames are shown along with the number of posts that the user has submitted. If the bdi element were not used, the username of the Arabic user would end up confusing the text (the bidirectional algorithm would put the colon and the number "3" next to the word "User" rather than next to the word "posts").

<ul>
 <li>User <bdi>jcranmer</bdi>: 12 posts.
 <li>User <bdi>hober</bdi>: 5 posts.
 <li>User <bdi>إيان</bdi>: 3 posts.
</ul>
When using the bdi element, the username acts as expected.
If the bdi element were to be replaced by a b element, the username would confuse the bidirectional algorithm and the third bullet would end up saying "User 3 :", followed by the Arabic name (right-to-left), followed by "posts" and a period.

4.5.25 The bdo element

Element/bdo

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Also, the dir global attribute has special semantics on this element.
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The bdo element represents explicit text directionality formatting control for its children. It allows authors to override the Unicode bidirectional algorithm by explicitly specifying a direction override. [BIDI]

Authors must specify the dir attribute on this element, with the value ltr to specify a left-to-right override and with the value rtl to specify a right-to-left override. The auto value must not be specified.

This element has rendering requirements involving the bidirectional algorithm.

4.5.26 The span element

Element/span

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLSpanElement

Support in all current engines.

Firefox1+Safari6+Chrome15+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android14+
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLSpanElement : HTMLElement {
  [HTMLConstructor] constructor();
};

The span element doesn't mean anything on its own, but can be useful when used together with the global attributes, e.g. class, lang, or dir. It represents its children.

In this example, a code fragment is marked up using span elements and class attributes so that its keywords and identifiers can be color-coded from CSS:

<pre><code class="lang-c"><span class="keyword">for</span> (<span class="ident">j</span> = 0; <span class="ident">j</span> &lt; 256; <span class="ident">j</span>++) {
  <span class="ident">i_t3</span> = (<span class="ident">i_t3</span> & 0x1ffff) | (<span class="ident">j</span> &lt;&lt; 17);
  <span class="ident">i_t6</span> = (((((((<span class="ident">i_t3</span> >> 3) ^ <span class="ident">i_t3</span>) >> 1) ^ <span class="ident">i_t3</span>) >> 8) ^ <span class="ident">i_t3</span>) >> 5) & 0xff;
  <span class="keyword">if</span> (<span class="ident">i_t6</span> == <span class="ident">i_t1</span>)
    <span class="keyword">break</span>;
}</code></pre>

4.5.27 The br element

Element/br

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLBRElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Phrasing content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Nothing.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLBRElement : HTMLElement {
  [HTMLConstructor] constructor();

  // also has obsolete members
};

The br element represents a line break.

While line breaks are usually represented in visual media by physically moving subsequent text to a new line, a style sheet or user agent would be equally justified in causing line breaks to be rendered in a different manner, for instance as green dots, or as extra spacing.

br elements must be used only for line breaks that are actually part of the content, as in poems or addresses.

The following example is correct usage of the br element:

<p>P. Sherman<br>
42 Wallaby Way<br>
Sydney</p>

br elements must not be used for separating thematic groups in a paragraph.

The following examples are non-conforming, as they abuse the br element:

<p><a ...>34 comments.</a><br>
<a ...>Add a comment.</a></p>
<p><label>Name: <input name="name"></label><br>
<label>Address: <input name="address"></label></p>

Here are alternatives to the above, which are correct:

<p><a ...>34 comments.</a></p>
<p><a ...>Add a comment.</a></p>
<p><label>Name: <input name="name"></label></p>
<p><label>Address: <input name="address"></label></p>

If a paragraph consists of nothing but a single br element, it represents a placeholder blank line (e.g. as in a template). Such blank lines must not be used for presentation purposes.

Any content inside br elements must not be considered part of the surrounding text.

This element has rendering requirements involving the bidirectional algorithm.

4.5.28 The wbr element

Element/wbr

Support in all current engines.

Firefox1+Safari4+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)NoInternet Explorer5.5–7
Firefox Android4+Safari iOS?Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android?
Categories:
Flow content.
Phrasing content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Nothing.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The wbr element represents a line break opportunity.

In the following example, someone is quoted as saying something which, for effect, is written as one long word. However, to ensure that the text can be wrapped in a readable fashion, the individual words in the quote are separated using a wbr element.

<p>So then she pointed at the tiger and screamed
"there<wbr>is<wbr>no<wbr>way<wbr>you<wbr>are<wbr>ever<wbr>going<wbr>to<wbr>catch<wbr>me"!</p>

Any content inside wbr elements must not be considered part of the surrounding text.

var wbr = document.createElement("wbr");
wbr.textContent = "This is wrong";
document.body.appendChild(wbr);

This element has rendering requirements involving the bidirectional algorithm.

4.5.29 Usage summary

This section is non-normative.

Element Purpose Example
a Hyperlinks
Visit my <a href="drinks.html">drinks</a> page.
em Stress emphasis
I must say I <em>adore</em> lemonade.
strong Importance
This tea is <strong>very hot</strong>.
small Side comments
These grapes are made into wine. <small>Alcohol is addictive.</small>
s Inaccurate text
Price: <s>£4.50</s> £2.00!
cite Titles of works
The case <cite>Hugo v. Danielle</cite> is relevant here.
q Quotations
The judge said <q>You can drink water from the fish tank</q> but advised against it.
dfn Defining instance
The term <dfn>organic food</dfn> refers to food produced without synthetic chemicals.
abbr Abbreviations
Organic food in Ireland is certified by the <abbr title="Irish Organic Farmers and Growers Association">IOFGA</abbr>.
ruby, rt, rp Ruby annotations
<ruby> OJ <rp>(<rt>Orange Juice<rp>)</ruby>
data Machine-readable equivalent
Available starting today! <data value="UPC:022014640201">North Coast Organic Apple Cider</data>
time Machine-readable equivalent of date- or time-related data
Available starting on <time datetime="2011-11-18">November 18th</time>!
code Computer code
The <code>fruitdb</code> program can be used for tracking fruit production.
var Variables
If there are <var>n</var> fruit in the bowl, at least <var>n</var>÷2 will be ripe.
samp Computer output
The computer said <samp>Unknown error -3</samp>.
kbd User input
Hit <kbd>F1</kbd> to continue.
sub Subscripts
Water is H<sub>2</sub>O.
sup Superscripts
The Hydrogen in heavy water is usually <sup>2</sup>H.
i Alternative voice
Lemonade consists primarily of <i>Citrus limon</i>.
b Keywords
Take a <b>lemon</b> and squeeze it with a <b>juicer</b>.
u Annotations
The mixture of apple juice and <u class="spelling">eldeflower</u> juice is very pleasant.
mark Highlight
Elderflower cordial, with one <mark>part</mark> cordial to ten <mark>part</mark>s water, stands a<mark>part</mark> from the rest.
bdi Text directionality isolation
The recommended restaurant is <bdi lang="">My Juice Café (At The Beach)</bdi>.
bdo Text directionality formatting
The proposal is to write English, but in reverse order. "Juice" would become "<bdo dir=rtl>Juice</bdo>">
span Other
In French we call it <span lang="fr">sirop de sureau</span>.
br Line break
Simply Orange Juice Company<br>Apopka, FL 32703<br>U.S.A.
wbr Line breaking opportunity
www.simply<wbr>orange<wbr>juice.com

4.6.1 概述

链接是一种概念构造,由 a, arealink 元素创建, 表示 两个资源之间的联系,其中一个是当前 Document。 在 HTML 中有两种链接:

外部资源链接

这些链接指向的资源用于增强当前文档,通常由用户代理自动处理。

超链接

这些指向其他文档的链接通常通过用户代理暴露给用户,这样用户可以让用户代理 导航 到那些资源,例如在浏览器中访问或者下载它们。

对于有 href 属性和 rel 属性的 link 元素, 必须为 rel 属性的关键字按照 链接类型 部分的定义创建一个链接。

类似地,对于有 href 属性和 rel 属性的 aarea 元素, 必须为 rel 属性的关键字按照 链接类型 部分的定义创建一个链接。 与 link 元素不同,对于有 href 属性的 aarea 元素,如果没有 rel 属性或 rel 属性的关键字的定义中没有一个是用来指定 超链接 的,也必须创建一个 超链接。 这个暗示的超链接没有特殊含义(它也没有 链接类型),只是把该元素的 节点文档 链接到了该元素的 href 属性给出的资源。

超链接 可以有一个或更多的 超链接注释,用来修改这个超链接的处理语义。

The href attribute on a and area elements must have a value that is a valid URL potentially surrounded by spaces.

The href attribute on a and area elements is not required; when those elements do not have href attributes they do not create hyperlinks.

The target attribute, if present, must be a valid browsing context name or keyword. It gives the name of the browsing context that will be used. User agents use this name when following hyperlinks.

When an a or area element's activation behavior is invoked, the user agent may allow the user to indicate a preference regarding whether the hyperlink is to be used for navigation or whether the resource it specifies is to be downloaded.

In the absence of a user preference, the default should be navigation if the element has no download attribute, and should be to download the specified resource if it does.

Whether determined by the user's preferences or via the presence or absence of the attribute, if the decision is to use the hyperlink for navigation then the user agent must follow the hyperlink, and if the decision is to use the hyperlink to download a resource, the user agent must download the hyperlink. These terms are defined in subsequent sections below.

The download attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource. The attribute may have a value; the value, if any, specifies the default file name that the author recommends for use in labeling the resource in a local file system. There are no restrictions on allowed values, but authors are cautioned that most file systems have limitations with regard to what punctuation is supported in file names, and user agents are likely to adjust file names accordingly.

Element/a#attr-ping

Support in all current engines.

Firefox🔰 YesSafari6+Chrome12+
Opera15+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox AndroidNoSafari iOS6+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+

The ping attribute, if present, gives the URLs of the resources that are interested in being notified if the user follows the hyperlink. The value must be a set of space-separated tokens, each of which must be a valid non-empty URL whose scheme is an HTTP(S) scheme. The value is used by the user agent for hyperlink auditing.

The rel attribute on a and area elements controls what kinds of links the elements create. The attribute's value must be a unordered set of unique space-separated tokens. The allowed keywords and their meanings are defined below.

rel's supported tokens are the keywords defined in HTML link types which are allowed on a and area elements, impact the processing model, and are supported by the user agent. The possible supported tokens are noreferrer, noopener, and opener. rel's supported tokens must only include the tokens from this list that the user agent implements the processing model for.

The rel attribute has no default value. If the attribute is omitted or if none of the values in the attribute are recognized by the user agent, then the document has no particular relationship with the destination resource other than there being a hyperlink between the two.

The hreflang attribute on a elements that create hyperlinks, if present, gives the language of the linked resource. It is purely advisory. The value must be a valid BCP 47 language tag. [BCP47] User agents must not consider this attribute authoritative — upon fetching the resource, user agents must use only language information associated with the resource to determine its language, not metadata included in the link to the resource.

The type attribute, if present, gives the MIME type of the linked resource. It is purely advisory. The value must be a valid MIME type string. User agents must not consider the type attribute authoritative — upon fetching the resource, user agents must not use metadata included in the link to the resource to determine its type.

The referrerpolicy attribute is a referrer policy attribute. Its purpose is to set the referrer policy used when following hyperlinks. [REFERRERPOLICY]

4.6.3 API for a and area elements

interface mixin HTMLHyperlinkElementUtils {
  [CEReactions] stringifier attribute USVString href;
  readonly attribute USVString origin;
  [CEReactions] attribute USVString protocol;
  [CEReactions] attribute USVString username;
  [CEReactions] attribute USVString password;
  [CEReactions] attribute USVString host;
  [CEReactions] attribute USVString hostname;
  [CEReactions] attribute USVString port;
  [CEReactions] attribute USVString pathname;
  [CEReactions] attribute USVString search;
  [CEReactions] attribute USVString hash;
};
hyperlink . toString()
hyperlink . href

HTMLAnchorElement/href

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLAnchorElement/toString

Support in all current engines.

Firefox22+Safari3+Chrome52+
Opera39+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android22+Safari iOS1+Chrome Android52+WebView Android52+Samsung Internet6.0+Opera Android41+

HTMLAreaElement/href

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLAreaElement/toString

Support in all current engines.

Firefox22+Safari10.1+Chrome52+
Opera39+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android22+Safari iOS10.3+Chrome Android52+WebView Android52+Samsung Internet6.0+Opera Android41+

Returns the hyperlink's URL.

Can be set, to change the URL.

hyperlink . origin

HTMLAnchorElement/origin

Support in all current engines.

Firefox26+Safari5.1+Chrome8+
Opera15+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android26+Safari iOS5+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android14+

HTMLAreaElement/origin

Support in all current engines.

Firefox26+Safari5.1+Chrome8+
Opera15+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android26+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+

Returns the hyperlink's URL's origin.

hyperlink . protocol

HTMLAnchorElement/protocol

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

HTMLAreaElement/protocol

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

Returns the hyperlink's URL's scheme.

Can be set, to change the URL's scheme.

hyperlink . username

HTMLAnchorElement/username

Support in all current engines.

Firefox26+Safari10+Chrome32+
Opera19+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android26+Safari iOS10+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+

HTMLAreaElement/username

Support in all current engines.

Firefox26+Safari10+Chrome32+
Opera19+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android26+Safari iOS10+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+

Returns the hyperlink's URL's username.

Can be set, to change the URL's username.

hyperlink . password

HTMLAnchorElement/password

Support in all current engines.

Firefox26+Safari10+Chrome32+
Opera19+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android26+Safari iOS10+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+

HTMLAreaElement/password

Support in all current engines.

Firefox26+Safari10+Chrome32+
Opera19+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android26+Safari iOS10+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+

Returns the hyperlink's URL's password.

Can be set, to change the URL's password.

hyperlink . host

HTMLAnchorElement/host

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

HTMLAreaElement/host

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

Returns the hyperlink's URL's host and port (if different from the default port for the scheme).

Can be set, to change the URL's host and port.

hyperlink . hostname

HTMLAnchorElement/hostname

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

HTMLAreaElement/hostname

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

Returns the hyperlink's URL's host.

Can be set, to change the URL's host.

hyperlink . port

HTMLAnchorElement/port

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

HTMLAreaElement/port

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

Returns the hyperlink's URL's port.

Can be set, to change the URL's port.

hyperlink . pathname

HTMLAnchorElement/pathname

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

HTMLAreaElement/pathname

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

Returns the hyperlink's URL's path.

Can be set, to change the URL's path.

hyperlink . search

HTMLAnchorElement/search

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

HTMLAreaElement/search

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

Returns the hyperlink's URL's query (includes leading "?" if non-empty).

Can be set, to change the URL's query (ignores leading "?").

hyperlink . hash

HTMLAnchorElement/hash

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

HTMLAreaElement/hash

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

Returns the hyperlink's URL's fragment (includes leading "#" if non-empty).

Can be set, to change the URL's fragment (ignores leading "#").

An element implementing the HTMLHyperlinkElementUtils mixin has an associated url (null or a URL). It is initially null.

An element implementing the HTMLHyperlinkElementUtils mixin has an associated set the url algorithm, which runs these steps:

  1. If this element's href content attribute is absent, set this element's url to null.

  2. Otherwise, parse this element's href content attribute value relative to this element's node document. If parsing is successful, set this element's url to the result; otherwise, set this element's url to null.

When elements implementing the HTMLHyperlinkElementUtils mixin are created, and whenever those elements have their href content attribute set, changed, or removed, the user agent must set the url.

This is only observable for blob: URLs as parsing them involves a Blob URL Store lookup.

An element implementing the HTMLHyperlinkElementUtils mixin has an associated reinitialize url algorithm, which runs these steps:

  1. If element's url is non-null, its scheme is "blob", and its cannot-be-a-base-URL flag is set, terminate these steps.

  2. Set the url.

To update href, set the element's href content attribute's value to the element's url, serialized.


The href attribute's getter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null and this element has no href content attribute, return the empty string.

  4. Otherwise, if url is null, return this element's href content attribute's value.

  5. Return url, serialized.

The href attribute's setter must set this element's href content attribute's value to the given value.

The origin attribute's getter must run these steps:

  1. Reinitialize url.

  2. If this element's url is null, return the empty string.

  3. Return the serialization of this element's url's origin.

The protocol attribute's getter must run these steps:

  1. Reinitialize url.

  2. If this element's url is null, return ":".

  3. Return this element's url's scheme, followed by ":".

The protocol attribute's setter must run these steps:

  1. Reinitialize url.

  2. If this element's url is null, terminate these steps.

  3. Basic URL parse the given value, followed by ":", with this element's url as url and scheme start state as state override.

    Because the URL parser ignores multiple consecutive colons, providing a value of "https:" (or even "https::::") is the same as providing a value of "https".

  4. Update href.

The username attribute's getter must run these steps:

  1. Reinitialize url.

  2. If this element's url is null, return the empty string.

  3. Return this element's url's username.

The username attribute's setter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null or url cannot have a username/password/port, then return.

  4. Set the username, given url and the given value.

  5. Update href.

The password attribute's getter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null, then return the empty string.

  4. Return url's password.

The password attribute's setter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null or url cannot have a username/password/port, then return.

  4. Set the password, given url and the given value.

  5. Update href.

The host attribute's getter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url or url's host is null, return the empty string.

  4. If url's port is null, return url's host, serialized.

  5. Return url's host, serialized, followed by ":" and url's port, serialized.

The host attribute's setter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null or url's cannot-be-a-base-URL flag is set, terminate these steps.

  4. Basic URL parse the given value, with url as url and host state as state override.

  5. Update href.

The hostname attribute's getter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url or url's host is null, return the empty string.

  4. Return url's host, serialized.

The hostname attribute's setter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null or url's cannot-be-a-base-URL flag is set, terminate these steps.

  4. Basic URL parse the given value, with url as url and hostname state as state override.

  5. Update href.

The port attribute's getter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url or url's port is null, return the empty string.

  4. Return url's port, serialized.

The port attribute's setter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null or url cannot have a username/password/port, then return.

  4. If the given value is the empty string, then set url's port to null.

  5. Otherwise, basic URL parse the given value, with url as url and port state as state override.

  6. Update href.

The pathname attribute's getter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null, return the empty string.

  4. If url's cannot-be-a-base-URL flag is set, return the first string in url's path.

  5. If url's path is empty, then return the empty string.

  6. Return "/", followed by the strings in url's path (including empty strings), separated from each other by "/".

The pathname attribute's setter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null or url's cannot-be-a-base-URL flag is set, terminate these steps.

  4. Set url's path to the empty list.

  5. Basic URL parse the given value, with url as url and path start state as state override.

  6. Update href.

The search attribute's getter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null, or url's query is either null or the empty string, return the empty string.

  4. Return "?", followed by url's query.

The search attribute's setter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null, terminate these steps.

  4. If the given value is the empty string, set url's query to null.

  5. Otherwise:

    1. Let input be the given value with a single leading "?" removed, if any.

    2. Set url's query to the empty string.

    3. Basic URL parse input, with url as url and query state as state override, and this element's node document's document's character encoding as encoding override.

  6. Update href.

The hash attribute's getter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null, or url's fragment is either null or the empty string, return the empty string.

  4. Return "#", followed by url's fragment.

The hash attribute's setter must run these steps:

  1. Reinitialize url.

  2. Let url be this element's url.

  3. If url is null, then return.

  4. If the given value is the empty string, set url's fragment to null.

  5. Otherwise:

    1. Let input be the given value with a single leading "#" removed, if any.

    2. Set url's fragment to the empty string.

    3. Basic URL parse input, with url as url and fragment state as state override.

  6. Update href.

An element element cannot navigate if one of the following is true:

This is also used by form submission for the form element. The exception for a elements is for compatibility with web content.

To get an element's noopener, given an a, area, or form element element and a string target, run these steps:

  1. If element's link types include the noopener or noreferrer keyword, then return true.

  2. If element's link types do not include the opener keyword and target is an ASCII case-insensitive match for "_blank", then return true.

  3. Return false.

When a user follows a hyperlink created by an element subject, optionally with a hyperlink suffix, the user agent must run the following steps:

  1. If subject cannot navigate, then return.

  2. Let replace be false.

  3. Let source be subject's node document's browsing context.

  4. Let targetAttributeValue be the empty string.

  5. If subject is an a or area element, then set targetAttributeValue to the result of getting an element's target given subject.

  6. Let noopener be the result of getting an element's noopener with subject and targetAttributeValue.

  7. Let target and windowType be the result of applying the rules for choosing a browsing context given targetAttributeValue, source, and noopener.

  8. If target is null, then return.

  9. Parse the URL given by subject's href attribute, relative to subject's node document.

  10. If that is successful, let URL be the resulting URL string.

    Otherwise, if parsing the URL failed, the user agent may report the error to the user in a user-agent-specific manner, may queue an element task on the DOM manipulation task source given subject to navigate the target browsing context to an error page to report the error, or may ignore the error and do nothing. In any case, the user agent must then return.

  11. If there is a hyperlink suffix, append it to URL.

  12. Let request be a new request whose url is URL and whose referrer policy is the current state of subject's referrerpolicy content attribute.

  13. If subject's link types includes the noreferrer keyword, then set request's referrer to "no-referrer".

  14. Let historyHandling be "replace" if windowType is not "existing or none"; otherwise, "default".

  15. Queue an element task on the DOM manipulation task source given subject to navigate target to request with historyHandling set to historyHandling and the source browsing context set to source.

4.6.5 Downloading resources

HTMLAnchorElement/download

Support in all current engines.

Firefox20+Safari10.1+Chrome15+
Opera15+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android20+Safari iOS10.3+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android14+

In some cases, resources are intended for later use rather than immediate viewing. To indicate that a resource is intended to be downloaded for use later, rather than immediately used, the download attribute can be specified on the a or area element that creates the hyperlink to that resource.

The attribute can furthermore be given a value, to specify the file name that user agents are to use when storing the resource in a file system. This value can be overridden by the `Content-Disposition` HTTP header's filename parameters. [RFC6266]

In cross-origin situations, the download attribute has to be combined with the `Content-Disposition` HTTP header, specifically with the attachment disposition type, to avoid the user being warned of possibly nefarious activity. (This is to protect users from being made to download sensitive personal or confidential information without their full understanding.)


The following allowed to download algorithm takes an initiator browsing context and an instantiator browsing context, and returns a boolean indicating whether or not downloading is allowed:

  1. If the initiator browsing context's sandboxing flags has the sandboxed downloads browsing context flag set, then return false.

  2. If the instantiator browsing context is non-null, and its sandboxing flags has the sandboxed downloads browsing context flag set, then return false.

  3. Optionally, the user agent may return false, if it believes doing so would safeguard the user from a potentially hostile download.

  4. Return true.

When a user downloads a hyperlink created by an element subject, optionally with a hyperlink suffix, the user agent must run the following steps:

  1. If subject cannot navigate, then return.

  2. Run the allowed to download algorithm with the subject's node document's browsing context and null. If the algorithm returns false, then return.

  3. Parse the URL given by subject's href attribute, relative to subject's node document.

  4. If parsing the URL fails, the user agent may report the error to the user in a user-agent-specific manner, may navigate to an error page to report the error, or may ignore the error and do nothing. In either case, the user agent must return.

  5. Otherwise, let URL be the resulting URL string.

  6. If there is a hyperlink suffix, append it to URL.

  7. Run these steps in parallel:

    1. Let request be a new request whose url is URL, client is entry settings object, initiator is "download", destination is the empty string, and whose synchronous flag and use-URL-credentials flag are set.

    2. Handle the result of fetching request as a download.

When a user agent is to handle a resource obtained from a fetch as a download, it should provide the user with a way to save the resource for later use, if a resource is successfully obtained. Otherwise, it should report any problems downloading the file to the user.

If the user agent needs a file name for a resource being handled as a download, it should select one using the following algorithm.

This algorithm is intended to mitigate security dangers involved in downloading files from untrusted sites, and user agents are strongly urged to follow it.

  1. Let filename be the undefined value.

  2. If the resource has a `Content-Disposition` header, that header specifies the attachment disposition type, and the header includes file name information, then let filename have the value specified by the header, and jump to the step labeled sanitize below. [RFC6266]

  3. Let interface origin be the origin of the Document in which the download or navigate action resulting in the download was initiated, if any.

  4. Let resource origin be the origin of the URL of the resource being downloaded, unless that URL's scheme component is data, in which case let resource origin be the same as the interface origin, if any.

  5. If there is no interface origin, then let trusted operation be true. Otherwise, let trusted operation be true if resource origin is the same origin as interface origin, and false otherwise.

  6. If trusted operation is true and the resource has a `Content-Disposition` header and that header includes file name information, then let filename have the value specified by the header, and jump to the step labeled sanitize below. [RFC6266]

  7. If the download was not initiated from a hyperlink created by an a or area element, or if the element of the hyperlink from which it was initiated did not have a download attribute when the download was initiated, or if there was such an attribute but its value when the download was initiated was the empty string, then jump to the step labeled no proposed file name.

  8. Let proposed filename have the value of the download attribute of the element of the hyperlink that initiated the download at the time the download was initiated.

  9. If trusted operation is true, let filename have the value of proposed filename, and jump to the step labeled sanitize below.

  10. If the resource has a `Content-Disposition` header and that header specifies the attachment disposition type, let filename have the value of proposed filename, and jump to the step labeled sanitize below. [RFC6266]

  11. No proposed file name: If trusted operation is true, or if the user indicated a preference for having the resource in question downloaded, let filename have a value derived from the URL of the resource in an implementation-defined manner, and jump to the step labeled sanitize below.

  12. Let filename be set to the user's preferred file name or to a file name selected by the user agent, and jump to the step labeled sanitize below.

    If the algorithm reaches this step, then a download was begun from a different origin than the resource being downloaded, and the origin did not mark the file as suitable for downloading, and the download was not initiated by the user. This could be because a download attribute was used to trigger the download, or because the resource in question is not of a type that the user agent supports.

    This could be dangerous, because, for instance, a hostile server could be trying to get a user to unknowingly download private information and then re-upload it to the hostile server, by tricking the user into thinking the data is from the hostile server.

    Thus, it is in the user's interests that the user be somehow notified that the resource in question comes from quite a different source, and to prevent confusion, any suggested file name from the potentially hostile interface origin should be ignored.

  13. Sanitize: Optionally, allow the user to influence filename. For example, a user agent could prompt the user for a file name, potentially providing the value of filename as determined above as a default value.

  14. Adjust filename to be suitable for the local file system.

    For example, this could involve removing characters that are not legal in file names, or trimming leading and trailing whitespace.

  15. If the platform conventions do not in any way use extensions to determine the types of file on the file system, then return filename as the file name.

  16. Let claimed type be the type given by the resource's Content-Type metadata, if any is known. Let named type be the type given by filename's extension, if any is known. For the purposes of this step, a type is a mapping of a MIME type to an extension.

  17. If named type is consistent with the user's preferences (e.g. because the value of filename was determined by prompting the user), then return filename as the file name.

  18. If claimed type and named type are the same type (i.e. the type given by the resource's Content-Type metadata is consistent with the type given by filename's extension), then return filename as the file name.

  19. If the claimed type is known, then alter filename to add an extension corresponding to claimed type.

    Otherwise, if named type is known to be potentially dangerous (e.g. it will be treated by the platform conventions as a native executable, shell script, HTML application, or executable-macro-capable document) then optionally alter filename to add a known-safe extension (e.g. ".txt").

    This last step would make it impossible to download executables, which might not be desirable. As always, implementers are forced to balance security and usability in this matter.

  20. Return filename as the file name.

For the purposes of this algorithm, a file extension consists of any part of the file name that platform conventions dictate will be used for identifying the type of the file. For example, many operating systems use the part of the file name following the last dot (".") in the file name to determine the type of the file, and from that the manner in which the file is to be opened or executed.

User agents should ignore any directory or path information provided by the resource itself, its URL, and any download attribute, in deciding where to store the resulting file in the user's file system.

If a hyperlink created by an a or area element has a ping attribute, and the user follows the hyperlink, and the value of the element's href attribute can be parsed, relative to the element's node document, without failure, then the user agent must take the ping attribute's value, split that string on ASCII whitespace, parse each resulting token relative to the element's node document, and then run these steps for each resulting URL record ping URL, ignoring tokens that fail to parse:

  1. If ping URL's scheme is not an HTTP(S) scheme, then return.

  2. Optionally, return. (For example, the user agent might wish to ignore any or all ping URLs in accordance with the user's expressed preferences.)

  3. Let request be a new request whose url is ping URL, method is `POST`, body is `PING`, client is the environment settings object of the Document containing the hyperlink, destination is the empty string, credentials mode is "include", referrer is "no-referrer", and whose use-URL-credentials flag is set.

  4. Let target URL be the resulting URL string obtained from parsing the value of the element's href attribute and then:

    If the URL of the Document object containing the hyperlink being audited and ping URL have the same origin
    If the origins are different, but the scheme of the URL of the Document containing the hyperlink being audited is not "https"
    request must include a `Ping-From` header with, as its value, the URL of the document containing the hyperlink, and a `Ping-To` HTTP header with, as its value, the target URL.
    Otherwise
    request must include a `Ping-To` HTTP header with, as its value, target URL. request does not include a `Ping-From` header.
  5. Fetch request.

This may be done in parallel with the primary fetch, and is independent of the result of that fetch.

User agents should allow the user to adjust this behavior, for example in conjunction with a setting that disables the sending of HTTP `Referer` (sic) headers. Based on the user's preferences, UAs may either ignore the ping attribute altogether, or selectively ignore URLs in the list (e.g. ignoring any third-party URLs); this is explicitly accounted for in the steps above.

User agents must ignore any entity bodies returned in the responses. User agents may close the connection prematurely once they start receiving a response body.

When the ping attribute is present, user agents should clearly indicate to the user that following the hyperlink will also cause secondary requests to be sent in the background, possibly including listing the actual target URLs.

For example, a visual user agent could include the hostnames of the target ping URLs along with the hyperlink's actual URL in a status bar or tooltip.

The ping attribute is redundant with pre-existing technologies like HTTP redirects and JavaScript in allowing web pages to track which off-site links are most popular or allowing advertisers to track click-through rates.

However, the ping attribute provides these advantages to the user over those alternatives:

Thus, while it is possible to track users without this feature, authors are encouraged to use the ping attribute so that the user agent can make the user experience more transparent.

4.6.6 Link types

Link_types

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Link_types

The following table summarizes the link types that are defined by this specification, by their corresponding keywords. This table is non-normative; the actual definitions for the link types are given in the next few sections.

In this section, the term referenced document refers to the resource identified by the element representing the link, and the term current document refers to the resource within which the element representing the link finds itself.

To determine which link types apply to a link, a, area, or form element, the element's rel attribute must be split on ASCII whitespace. The resulting tokens are the keywords for the link types that apply to that element.

Except where otherwise specified, a keyword must not be specified more than once per rel attribute.

Some of the sections that follow the table below list synonyms for certain keywords. The indicated synonyms are to be handled as specified by user agents, but must not be used in documents (for example, the keyword "copyright").

Keywords are always ASCII case-insensitive, and must be compared as such.

Thus, rel="next" is the same as rel="NEXT".

Keywords that are body-ok affect whether link elements are allowed in the body. The body-ok keywords are dns-prefetch, modulepreload, pingback, preconnect, prefetch, preload, prerender, and stylesheet.

New link types that are to be implemented by web browsers are to be added to this standard. The remainder can be registered as extensions.

Link typeEffect on...body-okBrief description
linka and areaform
alternateHyperlinknot allowed · Gives alternate representations of the current document.
canonicalHyperlinknot allowed · Gives the preferred URL for the current document.
authorHyperlinknot allowed · Gives a link to the author of the current document or article.
bookmarknot allowedHyperlinknot allowed · Gives the permalink for the nearest ancestor section.
dns-prefetchExternal Resourcenot allowed Yes Specifies that the user agent should preemptively perform DNS resolution for the target resource's origin.
externalnot allowedAnnotation · Indicates that the referenced document is not part of the same site as the current document.
helpHyperlink · Provides a link to context-sensitive help.
iconExternal Resourcenot allowed · Imports an icon to represent the current document.
manifestExternal Resourcenot allowed · Imports or links to an application manifest. [MANIFEST]
modulepreloadExternal Resourcenot allowed Yes Specifies that the user agent must preemptively fetch the module script and store it in the document's module map for later evaluation. Optionally, the module's dependencies can be fetched as well.
licenseHyperlink · Indicates that the main content of the current document is covered by the copyright license described by the referenced document.
nextHyperlink · Indicates that the current document is a part of a series, and that the next document in the series is the referenced document.
nofollownot allowedAnnotation · Indicates that the current document's original author or publisher does not endorse the referenced document.
noopenernot allowedAnnotation · Creates a top-level browsing context that is not an auxiliary browsing context if the hyperlink would create either of those to begin with (i.e., has an appropriate target attribute value).
noreferrernot allowedAnnotation · No `Referer` (sic) header will be included. Additionally, has the same effect as noopener.
openernot allowedAnnotation · Creates an auxiliary browsing context if the hyperlink would otherwise create a top-level browsing context that is not an auxiliary browsing context (i.e., has "_blank" as target attribute value).
pingbackExternal Resourcenot allowed Yes Gives the address of the pingback server that handles pingbacks to the current document.
preconnectExternal Resourcenot allowed Yes Specifies that the user agent should preemptively connect to the target resource's origin.
prefetchExternal Resourcenot allowed Yes Specifies that the user agent should preemptively fetch and cache the target resource as it is likely to be required for a followup navigation.
preloadExternal Resourcenot allowed Yes Specifies that the user agent must preemptively fetch and cache the target resource for current navigation according to the potential destination given by the as attribute (and the priority associated with the corresponding destination).
prerenderExternal Resourcenot allowed Yes Specifies that the user agent should preemptively fetch the target resource and process it in a way that helps deliver a faster response in the future.
prevHyperlink · Indicates that the current document is a part of a series, and that the previous document in the series is the referenced document.
searchHyperlink · Gives a link to a resource that can be used to search through the current document and its related pages.
stylesheetExternal Resourcenot allowed Yes Imports a style sheet.
tagnot allowedHyperlinknot allowed · Gives a tag (identified by the given address) that applies to the current document.
4.6.6.1 Link type "alternate"

Alternative_style_sheets

Support in one engine only.

Firefox3+Safari?Chrome1–48
OperaYesEdgeNo
Edge (Legacy)?Internet Explorer8+
Firefox Android4+Safari iOS?Chrome Android?WebView Android?Samsung Internet?Opera Android?

alternate 关键字可用于 link, aarea 元素。

该关键的含义取决于其他属性的值。

如果是一个 link 元素且 rel 属性包含关键字 stylesheet

alternate 关键字会更改 stylesheet 关键字的含义(见它的说明)。 alternate 关键字自己不会创建链接。

下面的这些 link 元素提供了一些样式表:

<!-- a persistent style sheet -->
<link rel="stylesheet" href="default.css">

<!-- the preferred alternate style sheet -->
<link rel="stylesheet" href="green.css" title="Green styles">

<!-- some alternate style sheets -->
<link rel="alternate stylesheet" href="contrast.css" title="High contrast">
<link rel="alternate stylesheet" href="big.css" title="Big fonts">
<link rel="alternate stylesheet" href="wide.css" title="Wide screen">
如果 alternate 关键字用于 type 属性值为 application/rss+xmlapplication/atom+xml

该关键字创建了一个 超链接 指向聚合 feed(不一定需要发布和当前页面同样的内容)。

为了 feed 自动发现,用户代理应该考虑文档里所有使用了 alternate 关键字, 并且 type 属性值为 application/rss+xmlapplication/atom+xmllink 元素。 如果用户代理有默认 feed 聚合的概念,应该默认使用(按照树序)第一个这样的元素。

下面的 link 元素给出了一个博客的 feed 聚合:

<link rel="alternate" type="application/atom+xml" href="posts.xml" title="Cool Stuff Blog">
<link rel="alternate" type="application/atom+xml" href="posts.xml?category=robots" title="Cool Stuff Blog: robots category">
<link rel="alternate" type="application/atom+xml" href="comments.xml" title="Cool Stuff Blog: Comments">

这样的 link 元素应该用于用户代理自动发现 feed,且第一个(如果可用的话)为默认值。

下面的例子使用 a 元素给用户提供了多种不同的 feed 聚合:

<p>You can access the planets database using Atom feeds:</p>
<ul>
 <li><a href="recently-visited-planets.xml" rel="alternate" type="application/atom+xml">Recently Visited Planets</a></li>
 <li><a href="known-bad-planets.xml" rel="alternate" type="application/atom+xml">Known Bad Planets</a></li>
 <li><a href="unexplored-planets.xml" rel="alternate" type="application/atom+xml">Unexplored Planets</a></li>
</ul>

这些链接不会被用于 feed 自动发现。

否则

该关键字将创建一个 超链接 指向当前文档的另一种表示。

被引用文档的特征由 hreflangtype 属性给出。

如果 alternate 关键字和 hreflang 属性一起使用, 且该属性的值与 文档元素语言 不同, 它表示被引用文档是一个翻译版本。

如果 alternate 关键字和 type 属性一起使用,它表示被引用文档是当前文档的另一种格式的版本。

hreflangtype 属性可以和 alternate 关键字一起使用。

下面的例子展示了如何指定当前页面的其他格式版本,其他语言版本,以及为其他媒体准备的版本:

<link rel=alternate href="/en/html" hreflang=en type=text/html title="English HTML">
<link rel=alternate href="/fr/html" hreflang=fr type=text/html title="French HTML">
<link rel=alternate href="/en/html/print" hreflang=en type=text/html media=print title="English HTML (for printing)">
<link rel=alternate href="/fr/html/print" hreflang=fr type=text/html media=print title="French HTML (for printing)">
<link rel=alternate href="/en/pdf" hreflang=en type=application/pdf title="English PDF">
<link rel=alternate href="/fr/pdf" hreflang=fr type=application/pdf title="French PDF">

这一关系具有传递性 — 也就是说如果一篇文档使用 "alternate" 链接到另外两篇文档, 那么意味着那两篇文档是第一篇文档的替代表示,也意味着那两篇文档互相为替代表示。

author 关键字可用于 linkaarea 元素。该关键字会创建一个 超链接

对于 aarea 元素,author 关键字表示被引用的文档提供了离定义该超链接的元素最近的祖先 article 元素的作者的更多信息, 如果没有这样的祖先元素,就是指整个页面的作者。

对于 link 元素,author 关键字表示被引用文档提供了 关于整个页面的作者的更多信息。

"被引用文档" 可以是(也经常是)一个 mailto: URL 给出了作者的 e-mail 地址。[MAILTO]

同义词:由于历史原因,用户代理必须把 rev 属性值为 "made" 的 link, a, 和 area 元素也当作有一个 author 关键字来处理。

bookmark 关键字可用于 linkaarea 元素。该关键字会创建一个 超链接

bookmark 关键字给出了这个链接元素最近的祖先 article 元素的永久链接。如果没有祖先 article 元素的话,就是指 这个链接元素关联最紧密的 section

下面的片段有三个永久链接。用户代理通过给出永久链接的位置来确定每个部分对应的永久链接。

 ...
 <body>
  <h1>Example of permalinks</h1>
  <div id="a">
   <h2>First example</h2>
   <p><a href="a.html" rel="bookmark">This permalink applies to
   only the content from the first H2 to the second H2</a>. The DIV isn't
   exactly that section, but it roughly corresponds to it.</p>
  </div>
  <h2>Second example</h2>
  <article id="b">
   <p><a href="b.html" rel="bookmark">This permalink applies to
   the outer ARTICLE element</a> (which could be, e.g., a blog post).</p>
   <article id="c">
    <p><a href="c.html" rel="bookmark">This permalink applies to
    the inner ARTICLE element</a> (which could be, e.g., a blog comment).</p>
   </article>
  </article>
 </body>
 ...

The canonical keyword may be used with link element. This keyword creates a hyperlink.

The canonical keyword indicates that URL given by the href attribute is the preferred URL for the current document. That helps search engines reduce duplicate content, as described in more detail in The Canonical Link Relation. [RFC6596]

Link_types/dns-prefetch

Firefox3+Safari?Chrome46+
Opera33+Edge79+
Edge (Legacy)NoInternet Explorer?
Firefox Android4+Safari iOS?Chrome AndroidYesWebView Android46+Samsung InternetYesOpera Android?

dns-prefetch 关键字可用于 link 元素。该关键字会创建 外部资源链接。 这个关键字是 body-ok 的。

dns-prefetch 关键字表示最好为指定资源的 事先执行 DNS 解析,因为用户很可能会要位于那个 的资源,避免了 DNS 解析相关的延迟会提升用户体验。 用户代理必须实现 Resource Hints 所描述的 dns-prefetch 关键字的处理模型。 [RESOURCEHINTS]

dns-prefetch 关键字没有默认的资源类型。

external 关键字可用于 aarea 元素。该元素不会创建 超链接,但可以 注释 该元素创建的任何其他超链接 (如果其他关键字没有创建超链接的话就是注释暗示的超链接)。

external 关键字表示该链接指向的文档不是当前文档所属站点的一部分。

help 关键字可用于 linkaarea 元素。该关键字会创建一个 超链接

对于 aarea 元素,help 关键字表示被引用文档为定义了该超链接的父元素及其子元素提供了更多帮助信息。

在下面的例子中,表单控件关联了上下文相关的帮助。用户代理可以使用这个信息, 比如用户按下 “Help” 或 “F1” 键时可以显示被引用的文档。

 <p><label> Topic: <input name=topic> <a href="help/topic.html" rel="help">(Help)</a></label></p>

对于 link 元素,这个 help 关键字表示 被引用的文档为整个页面提供了帮助。

对于 aarea 元素,在有些浏览器中 help 关键字会使链接显示不同的光标。

4.6.6.8 Link type "icon"

Link_types#icon

Support in all current engines.

Firefox2+Safari3.1+Chrome4+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android4+Safari iOSNoChrome Android18+WebView Android38+Samsung Internet4.0+Opera AndroidNo
caniuse.com table

The icon keyword may be used with link elements. This keyword creates an external resource link.

The specified resource is an icon representing the page or site, and should be used by the user agent when representing the page in the user interface.

Icons could be auditory icons, visual icons, or other kinds of icons. If multiple icons are provided, the user agent must select the most appropriate icon according to the type, media, and sizes attributes. If there are multiple equally appropriate icons, user agents must use the last one declared in tree order at the time that the user agent collected the list of icons. If the user agent tries to use an icon but that icon is determined, upon closer examination, to in fact be inappropriate (e.g. because it uses an unsupported format), then the user agent must try the next-most-appropriate icon as determined by the attributes.

User agents are not required to update icons when the list of icons changes, but are encouraged to do so.

There is no default type for resources given by the icon keyword. However, for the purposes of determining the type of the resource, user agents must expect the resource to be an image.

The sizes keywords represent icon sizes in raw pixels (as opposed to CSS pixels).

An icon that is 50 CSS pixels wide intended for displays with a device pixel density of two device pixels per CSS pixel (2x, 192dpi) would have a width of 100 raw pixels. This feature does not support indicating that a different resource is to be used for small high-resolution icons vs large low-resolution icons (e.g. 50×50 2x vs 100×100 1x).

To parse and process the attribute's value, the user agent must first split the attribute's value on ASCII whitespace, and must then parse each resulting keyword to determine what it represents.

The any keyword represents that the resource contains a scalable icon, e.g. as provided by an SVG image.

Other keywords must be further parsed as follows to determine what they represent:

The keywords specified on the sizes attribute must not represent icon sizes that are not actually available in the linked resource.

The linked resource fetch setup steps for this type of linked resource, given a link element el and request request, are:

  1. Set request's destination to "image".

  2. Return true.

In the absence of a link with the icon keyword, for Document objects whose URL's scheme is an HTTP(S) scheme, user agents may instead run these steps in parallel:

  1. Let request be a new request whose url is the URL record obtained by resolving the URL "/favicon.ico" against the Document object's URL, client is the Document object's relevant settings object, destination is "image", synchronous flag is set, credentials mode is "include", and whose use-URL-credentials flag is set.

  2. Let response be the result of fetching request.

  3. Use response's unsafe response as an icon as if it had been declared using the icon keyword.

The following snippet shows the top part of an application with several icons.

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>lsForums — Inbox</title>
  <link rel=icon href=favicon.png sizes="16x16" type="image/png">
  <link rel=icon href=windows.ico sizes="32x32 48x48" type="image/vnd.microsoft.icon">
  <link rel=icon href=mac.icns sizes="128x128 512x512 8192x8192 32768x32768">
  <link rel=icon href=iphone.png sizes="57x57" type="image/png">
  <link rel=icon href=gnome.svg sizes="any" type="image/svg+xml">
  <link rel=stylesheet href=lsforums.css>
  <script src=lsforums.js></script>
  <meta name=application-name content="lsForums">
 </head>
 <body>
  ...

For historical reasons, the icon keyword may be preceded by the keyword "shortcut". If the "shortcut" keyword is present, the rel attribute's entire value must be an ASCII case-insensitive match for the string "shortcut icon" (with a single U+0020 SPACE character between the tokens and no other ASCII whitespace).

license 关键字可用于 linkaarea 元素。该关键字会创建一个 超链接

license 关键字表示被引用文档提供了当前文档中主要内容的版权许可条款。

本规范未指定如何区分文档中的主要内容和不被视为该主要内容的部分。 应该让用户能够明确这个区分。

考虑一个相片分享网站。这个站点的一个页面可能会描述并显示一张照片,这个页面可能是这样写的:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Exampl Pictures: Kissat</title>
  <link rel="stylesheet" href="/style/default">
 </head>
 <body>
  <h1>Kissat</h1>
  <nav>
   <a href="../">Return to photo index</a>
  </nav>
  <figure>
   <img src="/pix/39627052_fd8dcd98b5.jpg">
   <figcaption>Kissat</figcaption>
  </figure>
  <p>One of them has six toes!</p>
  <p><small><a rel="license" href="http://www.opensource.org/licenses/mit-license.php">MIT Licensed</a></small></p>
  <footer>
   <a href="/">Home</a> | <a href="../">Photo index</a>
   <p><small>© copyright 2009 Exampl Pictures. All Rights Reserved.</small></p>
  </footer>
 </body>
</html>

这个例子中 license 只适用于这张照片 (该文档的主要内容)而不是整个文档。尤其不是页面的设计本身,它的版权在文档底部给出。 这可以通过样式来表达清楚(例如让许可链接贴着照片,同时把页面的版权以细小的文字放在页底)。

同义词:由于历史原因,用户代理必须把 "copyright" 当作 license 关键字处理。

Link_types/manifest

Support in one engine only.

Firefox?Safari?ChromeNo
OperaNoEdgeNo
Edge (Legacy)NoInternet Explorer?
Firefox Android?Safari iOS?Chrome Android39+WebView Android39+Samsung Internet4.0+Opera Android?

The manifest keyword may be used with link elements. This keyword creates an external resource link.

The manifest keyword indicates the manifest file that provides metadata associated with the current document.

There is no default type for resources given by the manifest keyword.

The appropriate time to fetch and process the linked resource for this link type is when the user agent deems it necessary. For example, when the user chooses to install the web application. In that case, only the first link element in tree order whose rel attribute contains the token manifest may be used.

A user agent must not delay the load event for this link type.

The linked resource fetch setup steps for this type of linked resource, given a link element el and request request, are:

  1. Let context be el's node document's browsing context.

  2. If context is null, then return false.

  3. If context is not a top-level browsing context, then return false.

  4. Set request's initiator to "manifest".

  5. Set request's destination to "manifest".

  6. Set request's mode to "cors".

  7. Set request's credentials mode to the CORS settings attribute credentials mode for el's crossorigin content attribute.

  8. Return true.

To process this type of linked resource given a link element el, boolean success, and response response:

  1. If response's Content-Type metadata is not a JSON MIME type, then set success to false.

  2. If success is true, then process the manifest given el and response. [MANIFEST]

Link_types/modulepreload

Support in one engine only.

Firefox?Safari?Chrome66+
Opera53+Edge79+
Edge (Legacy)NoInternet Explorer?
Firefox Android?Safari iOS?Chrome Android66+WebView Android66+Samsung Internet9.0+Opera Android47+

The modulepreload keyword may be used with link elements. This keyword creates an external resource link. This keyword is body-ok.

The modulepreload keyword is a specialized alternative to the preload keyword, with a processing model geared toward preloading module scripts. In particular, it uses the specific fetch behavior for module scripts (including, e.g., a different interpretation of the crossorigin attribute), and places the result into the appropriate module map for later evaluation. In contrast, a similar external resource link using the preload keyword would place the result in the preload cache, without affecting the document's module map.

Additionally, implementations can take advantage of the fact that module scripts declare their dependencies in order to fetch the specified module's dependency as well. This is intended as an optimization opportunity, since the user agent knows that, in all likelihood, those dependencies will also be needed later. It will not generally be observable without using technology such as service workers, or monitoring on the server side. Notably, the appropriate load or error events will occur after the specified module is fetched, and will not wait for any dependencies.

The appropriate times to fetch and process the linked resource for such a link are:

Unlike some other link relations, changing the relevant attributes (such as as, crossorigin, and referrerpolicy) of such a link does not trigger a new fetch. This is because the document's module map has already been populated by a previous fetch, and so re-fetching would be pointless.

The fetch and process the linked resource algorithm for modulepreload links, given a link element el, is as follows:

  1. If the href attribute's value is the empty string, then return.

  2. Let destination be the current state of the as attribute (a destination), or "script" if it is in no state.

  3. If destination is not script-like, then queue an element task on the networking task source given the link element to fire an event named error at the link element, and return.

  4. Parse the URL given by the href attribute, relative to the element's node document. If that fails, then return. Otherwise, let url be the resulting URL record.

  5. Let settings object be the link element's node document's relevant settings object.

  6. Let credentials mode be the CORS settings attribute credentials mode for the crossorigin attribute.

  7. Let cryptographic nonce be the current value of the element's [[CryptographicNonce]] internal slot.

  8. Let integrity metadata be the value of the integrity attribute, if it is specified, or the empty string otherwise.

  9. Let referrer policy be the current state of the element's referrerpolicy attribute.

  10. Let options be a script fetch options whose cryptographic nonce is cryptographic nonce, integrity metadata is integrity metadata, parser metadata is "not-parser-inserted", credentials mode is credentials mode, and referrer policy is referrer policy.

  11. Fetch a modulepreload module script graph given url, destination, settings object, and options. Wait until the algorithm asynchronously completes with result.

  12. If result is null, then fire an event named error at the link element, and return.

  13. Fire an event named load at the link element.

The following snippet shows the top part of an application with several modules preloaded:

<!DOCTYPE html>
<html lang="en">
<title>IRCFog</title>

<link rel="modulepreload" href="app.mjs">
<link rel="modulepreload" href="helpers.mjs">
<link rel="modulepreload" href="irc.mjs">
<link rel="modulepreload" href="fog-machine.mjs">

<script type="module" src="app.mjs">
...

Assume that the module graph for the application is as follows:

The module graph is rooted at app.mjs, which depends on irc.mjs and fog-machine.mjs. In turn, irc.mjs depends on helpers.mjs.

Here we see the application developer has used modulepreload to declare all of the modules in their module graph, ensuring that the user agent initiates fetches for them all. Without such preloading, the user agent might need to go through multiple network roundtrips before discovering helpers.mjs, if technologies such as HTTP/2 Server Push are not in play. In this way, modulepreload link elements can be used as a sort of "manifest" of the application's modules.

The following code shows how modulepreload links can be used in conjunction with import() to ensure network fetching is done ahead of time, so that when import() is called, the module is already ready (but not evaluated) in the module map:

<link rel="modulepreload" href="awesome-viewer.mjs">

<button onclick="import('./awesome-viewer.mjs').then(m => m.view())">
  View awesome thing
</button>

nofollow 关键字可用于 aarea 元素。这个关键字不会创建 超链接,但是可以 注释 任何其他该元素创建的超链接。 (如果没有其他关键字创建链接,那就注释其隐含的超链接)。

nofollow 关键字表示该链接不被该网页的原始作者或发布者所认可, 或者这个指向被引用文档的链接主要是为了这两个页面的所有者之间的商业关系。

Link_types/noopener

Support in all current engines.

Firefox52+Safari10.1+Chrome49+
Opera36+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android52+Safari iOS10.3+Chrome Android49+WebView Android49+Samsung Internet5.0+Opera Android36+

Link_types/noopener

Support in all current engines.

Firefox52+Safari10.1+Chrome49+
Opera36+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android52+Safari iOS10.3+Chrome Android49+WebView Android49+Samsung Internet5.0+Opera Android36+

The noopener keyword may be used with a, area, and form elements. This keyword does not create a hyperlink, but annotates any other hyperlinks created by the element (the implied hyperlink, if no other keywords create one).

The keyword indicates that any newly created top-level browsing context which results from following the hyperlink will not be an auxiliary browsing context. E.g., its window.opener attribute will be null.

See also the processing model where the branching between an auxiliary browsing context and a top-level browsing context is defined.

This typically creates an auxiliary browsing context (assuming there is no existing browsing context whose browsing context name is "example"):

<a href=help.html target=example>Help!</a>

This creates a top-level browsing context that is not an auxiliary browsing context (assuming the same thing):

<a href=help.html target=example rel=noopener>Help!</a>

These are equivalent and only navigate the parent browsing context:

<a href=index.html target=_parent>Home</a>
<a href=index.html target=_parent rel=noopener>Home</a>

Link_types/noreferrer

Support in all current engines.

Firefox33+Safari5+Chrome16+
Opera15+Edge79+
Edge (Legacy)13+Internet Explorer🔰 11
Firefox Android33+Safari iOS4.2+Chrome Android18+WebView Android3+Samsung Internet1.5+Opera Android14+

Link_types/noreferrer

Support in all current engines.

Firefox33+Safari5+Chrome16+
Opera15+Edge79+
Edge (Legacy)13+Internet Explorer🔰 11
Firefox Android33+Safari iOS4.2+Chrome Android18+WebView Android3+Samsung Internet1.5+Opera Android14+

The noreferrer keyword may be used with a, area, and form elements. This keyword does not create a hyperlink, but annotates any other hyperlinks created by the element (the implied hyperlink, if no other keywords create one).

It indicates that no referrer information is to be leaked when following the link and also implies the noopener keyword behavior under the same conditions.

See also the processing model where referrer is directly manipulated.

<a href="..." rel="noreferrer" target="_blank"> has the same behavior as <a href="..." rel="noreferrer noopener" target="_blank">.

The opener keyword may be used with a, area, and form elements. This keyword does not create a hyperlink, but annotates any other hyperlinks created by the element (the implied hyperlink, if no other keywords create one).

The keyword indicates that any newly created top-level browsing context which results from following the hyperlink will be an auxiliary browsing context.

See also the processing model.

In the following example the opener is used to allow the help page popup to navigate its opener, e.g., in case what the user is looking for can be found elsewhere. An alternative might be to use a named target, rather than _blank, but this has the potential to clash with existing names.

<a href="..." rel=opener target=_blank>Help!</a>

pingback 关键字可以用于 link 元素。该关键字会创建一个 外部资源链接。 这个关键字是 body-ok 的。

关于 pingback 关键字的语义,参考 Pingback 1.0 规范。 [PINGBACK]

Link_types/preconnect

Support in all current engines.

Firefox39+Safari11.1+Chrome46+
Opera33+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android39+Safari iOS11.3+Chrome Android46+WebView Android46+Samsung Internet4.0+Opera Android33+

preconnect 关键字可用于 link 元素。 该关键字会创建一个 外部资源链接。 这个关键字是 body-ok 的。

preconnect 关键字表示最好事先初始化一个到指定资源的 的连接。因为用户很可能会访问处于这个 的资源,这省去了建立连接的延迟,所以会提升用户体验。 用户代理必须实现 Resource Hints 中描述的 preconnect 关键字的处理模型。 [RESOURCEHINTS]

preconnect 关键字给出的资源没有默认类型。

Link_types/prefetch

Firefox2+SafariNoChrome8+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android4+Safari iOSNoChrome Android18+WebView Android4.4+Samsung Internet1.5+Opera Android14+

prefetch 关键字可用于 link 元素。该关键字会创建 外部资源链接。 这个关键在是 body-ok 的。

prefetch 关键字表示最好事先 获取 并缓存指定的资源。 因为用户在将来的导航中很可能会要这个资源。 用户代理必须实现 Resource Hints 所描述的 prefetch 关键字的处理模型。 [RESOURCEHINTS]

prefetch 关键字没有默认的资源类型。

Link_types/preload

Support in one engine only.

Firefox85+Safari?Chrome🔰 50+
Opera37+Edge🔰 79+
Edge (Legacy)NoInternet Explorer?
Firefox Android85+Safari iOS?Chrome Android🔰 50+WebView Android50+Samsung Internet5.0+Opera Android?

The preload keyword may be used with link elements. This keyword creates an external resource link. This keyword is body-ok.

The preload keyword indicates that the user agent must preemptively fetch and cache the specified resource according to the potential destination given by the as attribute (and the priority associated with the corresponding destination), as it is highly likely that the user will require this resource for the current navigation. User agents must implement the processing model of the preload keyword described in Preload, as well as in this specification's fetch and process the linked resource algorithm. [PRELOAD]

There is no default type for resources given by the preload keyword.

The linked resource fetch setup steps for this type of linked resource, given a link element el and request request, are:

  1. Let as be the current state of el's as attribute.

  2. If as does not represent a state, return false.

  3. Set request's destination to the result of translating as.

  4. If as is "image", then:

    1. Let selected source and selected pixel density be the URL and pixel density that results from selecting an image source given el, respectively.

    2. If selected source is null, then return false.

    3. Parse selected source, relative to el's node document. If that fails, then return false. Otherwise, let url be the resulting URL record.

    4. Set request's url to url.

  5. Return true.

Link_types/prerender

Support in one engine only.

FirefoxNoSafariNoChrome13+
Opera15+Edge79+
Edge (Legacy)NoInternet Explorer11
Firefox AndroidNoSafari iOSNoChrome Android18+WebView Android4.4+Samsung Internet1.5+Opera Android14+

prerender 关键字可用于 link 元素。该关键字会创建 外部资源链接。 这个关键在是 body-ok 的。

prerender 关键字表示指定的资源可能在下次导航时用到。 所以最好先去 获取 这个资源并处理它, 比如 获取 它的子资源或执行一些渲染。用户代理必须实现 Resource Hints 中描述的 prerender 关键字的处理模型。 [RESOURCEHINTS]

prerender 关键字没有默认的资源类型。

The search keyword may be used with link, a, area, and form elements. This keyword creates a hyperlink.

The search keyword indicates that the referenced document provides an interface specifically for searching the document and its related resources.

OpenSearch description documents can be used with link elements and the search link type to enable user agents to autodiscover search interfaces. [OPENSEARCH]

The stylesheet keyword may be used with link elements. This keyword creates an external resource link that contributes to the styling processing model. This keyword is body-ok.

The specified resource is a CSS style sheet that describes how to present the document.

If the alternate keyword is also specified on the link element, then the link is an alternative style sheet; in this case, the title attribute must be specified on the link element, with a non-empty value.

The default type for resources given by the stylesheet keyword is text/css.

The appropriate times to fetch and process this type of link are:

Quirk: If the document has been set to quirks mode, has the same origin as the URL of the external resource, and the Content-Type metadata of the external resource is not a supported style sheet type, the user agent must instead assume it to be text/css.

The linked resource fetch setup steps for this type of linked resource, given a link element el (ignoring the request) are:

  1. If el's disabled attribute is set, then return false.

  2. If el contributes a script-blocking style sheet, increment el's node document's script-blocking style sheet counter by 1.

  3. Return true.

See issue #968 for plans to use the CSSOM fetch a CSS style sheet algorithm instead of the default fetch and process the linked resource algorithm.

To process this type of linked resource given a link element el, boolean success, and response response, the user agent must run these steps:

  1. If the resource's Content-Type metadata is not text/css, then set success to false.

  2. If el no longer creates an external resource link that contributes to the styling processing model, or if, since the resource in question was fetched, it has become appropriate to fetch it again, then return.

  3. If el has an associated CSS style sheet, remove the CSS style sheet.

  4. If success is true, then:

    1. Create a CSS style sheet with the following properties:

      type

      text/css

      location

      The resulting URL string determined during the fetch and process the linked resource algorithm.

      This is before any redirects get applied.

      owner node

      element

      media

      The media attribute of element.

      This is a reference to the (possibly absent at this time) attribute, rather than a copy of the attribute's current value. CSSOM defines what happens when the attribute is dynamically set, changed, or removed.

      title

      The title attribute of element, if element is in a document tree, or the empty string otherwise.

      This is similarly a reference to the attribute, rather than a copy of the attribute's current value.

      alternate flag

      Set if the link is an alternative style sheet and element's explicitly enabled is false; unset otherwise.

      origin-clean flag

      Set if the resource is CORS-same-origin; unset otherwise.

      parent CSS style sheet
      owner CSS rule

      null

      disabled flag

      Left at its default value.

      CSS rules

      Left uninitialized.

      This doesn't seem right. Presumably we should be using the response body? Tracked as issue #2997.

      The CSS environment encoding is the result of running the following steps: [CSSSYNTAX]

      1. If the element has a charset attribute, get an encoding from that attribute's value. If that succeeds, return the resulting encoding. [ENCODING]

      2. Otherwise, return the document's character encoding. [DOM]

    2. Fire an event named load at el.

  5. Otherwise, fire an event named error at el.

  6. If el contributes a script-blocking style sheet, then:

    1. Assert: el's node document's script-blocking style sheet counter is greater than 0.

    2. Decrement el's node document's script-blocking style sheet counter by 1.

tag 关键字可用于 aarea 元素。该关键字会创建一个 超链接

tag 关键字表示被引用的文档表示的 tag 适用于当前文档。

由于它表示该 tag 适用于当前文档, 在 tag 云 的标记中用这个关键字是不合适的,因为 tag 云列出了很多页面的 tag。

本文档是关于宝石的,所以它有一个 "https://en.wikipedia.org/wiki/Gemstone" tag 来把它归类到“珠宝”,而不是美国的城镇、Ruby 包格式,或瑞士机车分级:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>My Precious</title>
 </head>
 <body>
  <header><h1>My precious</h1> <p>Summer 2012</p></header>
  <p>Recently I managed to dispose of a red gem that had been
  bothering me. I now have a much nicer blue sapphire.</p>
  <p>The red gem had been found in a bauxite stone while I was digging
  out the office level, but nobody was willing to haul it away. The
  same red gem stayed there for literally years.</p>
  <footer>
   Tags: <a rel=tag href="https://en.wikipedia.org/wiki/Gemstone">Gemstone</a>
  </footer>
 </body>
</html>

文档中有两篇文章。但 "tag" 链接适用于整个页面 (不论它放在了哪里,以及是否在 article 元素中)。

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Gem 4/4</title>
 </head>
 <body>
  <article>
   <h1>801: Steinbock</h1>
   <p>The number 801 Gem 4/4 electro-diesel has an ibex and was rebuilt in 2002.</p>
  </article>
  <article>
   <h1>802: Murmeltier</h1>
   <figure>
    <img src="https://upload.wikimedia.org/wikipedia/commons/b/b0/Trains_de_la_Bernina_en_hiver_2.jpg"
         alt="The 802 was red with pantographs and tall vents on the side.">
    <figcaption>The 802 in the 1980s, above Lago Bianco.</figcaption>
   </figure>
   <p>The number 802 Gem 4/4 electro-diesel has a marmot and was rebuilt in 2003.</p>
  </article>
  <p class="topic"><a rel=tag href="https://en.wikipedia.org/wiki/Rhaetian_Railway_Gem_4/4">Gem 4/4</a></p>
 </body>
</html>

有些文档会组成一个文档序列。

文档序列是指,每个文档可以有一个 前驱 和一个 后继。 没有前驱的文档是其所在序列的开始文档, 没有后继的文档是其所在序列的结束文档。

一个文档可能属于多个序列。

next 关键字可用于 link, aarea 元素。该关键字会创建 超链接

next 关键字表示该文档是一个文档序列的一部分, 而且该链接指向逻辑上位于当前文档之后的那个文档。

next 关键字用于 link 元素时, 用户代理应该实现一个 Resource Hints 中描述的处理模型, 也就是说这样的链接应该被当做使用了 dns-prefetch, preconnect, prefetchprerender 关键字来处理。用户代理希望使用哪个资源暗示是实现相关的; 例如用户代理为了节省数据、电池或计算量可能会希望使用代价较小的 preconnect 暗示, 或者希望基于对类似场景中以前的用户行为的启发式分析来选取一个资源暗示。[RESOURCEHINTS]

prev 关键字可用于 link, aarea 元素。该关键字会创建 超链接

prev 关键字表示该文档是一个文档序列的一部分, 而且该链接指向逻辑上位于当前文档之前的那个文档。

同义词:由于历史原因,用户代理必须把 "previous" 关键字当作 prev 关键字处理。

预定义链接类型的扩展 可以注册在 microformats Wiki 已有的 rel 值页面[MFREL]

任何人在任何时候都可以编辑 microformats Wiki 已有的 rel 值页面 来增加一个类型。扩展类型必须指定以下信息:

关键字

要定义的实际关键字。这个值不应与其他已定义的值相似以避免混淆。 (例如只有大小写不同)

如果值包含 U+003A COLON 字符(:),它就必须是一个 绝对 URL

作用于... link

下面之一:

不允许
该关键字不得在 link 元素上指定。
超链接
该关键字可以在 link 元素上指定;它会创建一个 超链接
外部资源
该关键字可以在 link 元素上指定,它会创建一个 外部资源链接
作用于... aarea

下面之一:

不允许
该关键字不得在 aarea 元素上指定。
超链接
该关键字可以在 aarea 元素上指定;它会创建一个 超链接
外部资源
该关键字可以在 aarea 元素上指定;它会创建一个 外部资源链接
超链接注释
该关键字可以在 aarea 元素上指定;它用来 注释 该元素创建的其他 超链接
简要描述

对这个关键字的含义进行简短的非形式化的描述。

规范

指向对该关键字的语义和要求的更细节的描述的链接。 它可以是 Wiki 上的另一个页面,或者一个外部页面。

同义词

有着同样处理要求的其他关键字值的列表。 作者不应该使用已经定义为同义词的值,它们只是为了让用户代理支持旧的内容。 任何人都可以移除一个实践中已经不再使用的同义词 只有用于兼容旧内容的同义词才应该注册在这里。

状态

以下之一:

已提出
该名称还没有接受广泛的 peer review 和 approval。有人提出了它并且正在用或者马上就要使用。
已批准
该名称已经接受了广泛的 peer review 和 approval。并且有一个标准明确地定义了如何处理使用了这个名称的页面,包括哪些使用方式是错误的。
已终止
该名称已经接受了广泛的peer review 并且被认为是有用的。现存的页面已经在使用这个名称, 但新的页面应该避免使用。 "简要说明" 和 "规范" 入口会给出作者应该用哪些替代品,如果有的话。

如果一个关键字与其他现存的值冗余,那么应该把它移除并列为那个现存值的同义词。

如果一个关键字已经添加到 “已提议” 状态经过一个多月的时间并未被使用或标准化, 那么应该把它从注册中移除。

如果一个关键字已经添加到 “已提议” 状态但却与现存的值冗余, 就应该把它移除并列为该现存值的同义词。 如果一个名称被添加到 “已提议” 状态但被发现有害,则应该把它改为 “已终止” 状态。

任何人都可以随时更新状态,但应该根据上述定义进行。

一致性检查工具必须使用 microformats wiki 已有的 rel 值页面 给出的信息来决定值是否被允许: 对于本规范中定义的值或标记为 “已提议” 或 “已批准” 的值,当用于 “作用于...” 字段描述的元素时, 工具必须接受它,但标记为 “已终止” 的值,或者本标准和上述页面都没有列出的值,就必须视为不合法并拒绝它。 一致性检查工具可以缓存这个信息(例如,为了性能原因或为了避免使用不可靠的网络连接)。

当作者使用本规范和 Wiki 页面没有定义的新类型时,一致性检查工具应该可以提示把这个值添加到 Wiki, 使用上面描述的细节,并设为 “已提议” 状态。

microformats wiki 已有 rel 值页面 中定义为扩展的类型, 如果状态是 “已提议” 或 “已批准” 就可以根据 “作用于...” 字段用于 linkrel 属性, a, 和 area 元素。[MFREL]

4.7 Edits

The ins and del elements represent edits to the document.

4.7.1 The ins element

Element/ins

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Transparent.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
cite — Link to the source of the quotation or more information about the edit
datetime — Date and (optionally) time of the change
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLModElement.

The ins element represents an addition to the document.

The following represents the addition of a single paragraph:

<aside>
 <ins>
  <p> I like fruit. </p>
 </ins>
</aside>

As does the following, because everything in the aside element here counts as phrasing content and therefore there is just one paragraph:

<aside>
 <ins>
  Apples are <em>tasty</em>.
 </ins>
 <ins>
  So are pears.
 </ins>
</aside>

ins elements should not cross implied paragraph boundaries.

The following example represents the addition of two paragraphs, the second of which was inserted in two parts. The first ins element in this example thus crosses a paragraph boundary, which is considered poor form.

<aside>
 <!-- don't do this -->
 <ins datetime="2005-03-16 00:00Z">
  <p> I like fruit. </p>
  Apples are <em>tasty</em>.
 </ins>
 <ins datetime="2007-12-19 00:00Z">
  So are pears.
 </ins>
</aside>

Here is a better way of marking this up. It uses more elements, but none of the elements cross implied paragraph boundaries.

<aside>
 <ins datetime="2005-03-16 00:00Z">
  <p> I like fruit. </p>
 </ins>
 <ins datetime="2005-03-16 00:00Z">
  Apples are <em>tasty</em>.
 </ins>
 <ins datetime="2007-12-19 00:00Z">
  So are pears.
 </ins>
</aside>

4.7.2 The del element

Element/del

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Flow content.
Phrasing content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Transparent.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
cite — Link to the source of the quotation or more information about the edit
datetime — Date and (optionally) time of the change
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLModElement.

The del element represents a removal from the document.

del elements should not cross implied paragraph boundaries.

The following shows a "to do" list where items that have been done are crossed-off with the date and time of their completion.

<h1>To Do</h1>
<ul>
 <li>Empty the dishwasher</li>
 <li><del datetime="2009-10-11T01:25-07:00">Watch Walter Lewin's lectures</del></li>
 <li><del datetime="2009-10-10T23:38-07:00">Download more tracks</del></li>
 <li>Buy a printer</li>
</ul>

4.7.3 Attributes common to ins and del elements

The cite attribute may be used to specify the URL of a document that explains the change. When that document is long, for instance the minutes of a meeting, authors are encouraged to include a fragment pointing to the specific part of that document that discusses the change.

If the cite attribute is present, it must be a valid URL potentially surrounded by spaces that explains the change. To obtain the corresponding citation link, the value of the attribute must be parsed relative to the element's node document. User agents may allow users to follow such citation links, but they are primarily intended for private use (e.g., by server-side scripts collecting statistics about a site's edits), not for readers.

The datetime attribute may be used to specify the time and date of the change.

If present, the datetime attribute's value must be a valid date string with optional time.

User agents must parse the datetime attribute according to the parse a date or time string algorithm. If that doesn't return a date or a global date and time, then the modification has no associated timestamp (the value is non-conforming; it is not a valid date string with optional time). Otherwise, the modification is marked as having been made at the given date or global date and time. If the given value is a global date and time then user agents should use the associated time-zone offset information to determine which time zone to present the given datetime in.

This value may be shown to the user, but it is primarily intended for private use.

The ins and del elements must implement the HTMLModElement interface:

HTMLModElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
[Exposed=Window]
interface HTMLModElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString cite;
  [CEReactions] attribute DOMString dateTime;
};

The cite IDL attribute must reflect the element's cite content attribute. The dateTime IDL attribute must reflect the element's datetime content attribute.

4.7.4 编辑与段落

This section is non-normative.

由于 insdel 元素不影响 分段,在一些情况下段落可能是 隐式的 (没有显式的 p 元素),这样 insdel 元素就可以跨越一整个段落和其他非 短语内容 元素, 以及另一个段落的一部分。例如:

<section>
 <ins>
  <p>
   This is a paragraph that was inserted.
  </p>
  This is another paragraph whose first sentence was inserted
  at the same time as the paragraph above.
 </ins>
 This is a second sentence, which was there all along.
</section>

通过只包含 p 元素的一部分内容,还可以把一个段落的尾部,加一整个段落,再加第三个段落的开始, 包含到同一个 insdel 元素中(但这很费解,也不是最佳实践):

<section>
 This is the first paragraph. <ins>This sentence was
 inserted.
 <p>This second paragraph was inserted.</p>
 This sentence was inserted too.</ins> This is the
 third paragraph in this example.
 <!-- (don't do this) -->
</section>

但是根据 隐式段落 的定义, 不可能用同一个 insdel 元素包含一个段落尾加紧接着的段落开始部分。 你必须使用一个(或两个)p 元素和两个 insdel 元素, 例如:

<section>
 <p>This is the first paragraph. <del>This sentence was
 deleted.</del></p>
 <p><del>This sentence was deleted too.</del> That
 sentence needed a separate &lt;del&gt; element.</p>
</section>

由于上面提到的困惑,强烈建议作者总是把所有段落标记为 p 元素, 而不是让 insdel 元素穿越 隐式段落 的边界。

4.7.5 编辑与列表

This section is non-normative.

olul 元素的内容模型不允许 insdel 元素作为子节点。 列表总是表示它的所有列表项,包括应该被标记为删除的列表项。

为了表示一项被插入或删除,可以用 insdel 元素包含 li 元素的内容。为了表示一个元素被替换, 一个 li 元素可以有一个或更多的 del 元素, 再加一个或更多的 ins 元素。

在以下示例中,开始为空的列表随着时间的推移添加或删除了项目。 示例中强调了列表中属于“当前”状态的部分。尽管如此,列表项目编号并未考虑编辑。

<h1>Stop-ship bugs</h1>
<ol>
 <li><ins datetime="2008-02-12T15:20Z">Bug 225:
 Rain detector doesn't work in snow</ins></li>
 <li><del datetime="2008-03-01T20:22Z"><ins datetime="2008-02-14T12:02Z">Bug 228:
 Water buffer overflows in April</ins></del></li>
 <li><ins datetime="2008-02-16T13:50Z">Bug 230:
 Water heater doesn't use renewable fuels</ins></li>
 <li><del datetime="2008-02-20T21:15Z"><ins datetime="2008-02-16T14:25Z">Bug 232:
 Carbon dioxide emissions detected after startup</ins></del></li>
</ol>

下面的示例中,一个开始只包含水果的列表被替换为只包含颜色的列表。

<h1>List of <del>fruits</del><ins>colors</ins></h1>
<ul>
 <li><del>Lime</del><ins>Green</ins></li>
 <li><del>Apple</del></li>
 <li>Orange</li>
 <li><del>Pear</del></li>
 <li><ins>Teal</ins></li>
 <li><del>Lemon</del><ins>Yellow</ins></li>
 <li>Olive</li>
 <li><ins>Purple</ins></li>
</ul>

4.7.6 编辑与表格

This section is non-normative.

组成表格模型的元素有着复杂的内容模型要求,不允许使用 insdel 元素, 所以很难表示对图片的编辑。

为了表示整行的添加和移除,可以(分别)用 insdel 元素包含该行的每个单元格的整个内容。

这个表格中有一整行的添加:

<table>
 <thead>
  <tr> <th> Game name           <th> Game publisher   <th> Verdict
 <tbody>
  <tr> <td> Diablo 2            <td> Blizzard         <td> 8/10
  <tr> <td> Portal              <td> Valve            <td> 10/10
  <tr> <td> <ins>Portal 2</ins> <td> <ins>Valve</ins> <td> <ins>10/10</ins>
</table>

这里有一列被移除(移除时间也给出了,还给了一个页面的链接来解释原因):

<table>
 <thead>
  <tr> <th> Game name           <th> Game publisher   <th> <del cite="/edits/r192" datetime="2011-05-02 14:23Z">Verdict</del>
 <tbody>
  <tr> <td> Diablo 2            <td> Blizzard         <td> <del cite="/edits/r192" datetime="2011-05-02 14:23Z">8/10</del>
  <tr> <td> Portal              <td> Valve            <td> <del cite="/edits/r192" datetime="2011-05-02 14:23Z">10/10</del>
  <tr> <td> Portal 2            <td> Valve            <td> <del cite="/edits/r192" datetime="2011-05-02 14:23Z">10/10</del>
</table>

通常不应该表示更复杂的编辑(例如删除了一个单元格,把后续所有单元格上移或左移)。

4.8 嵌入内容

4.8.1 The picture element

Element/picture

Support in all current engines.

Firefox38+Safari9.1+Chrome38+
Opera25+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android38+Safari iOS9.3+Chrome Android38+WebView Android38+Samsung Internet3.0+Opera Android25+

HTMLPictureElement

Support in all current engines.

Firefox38+Safari9.1+Chrome38+
Opera25+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android38+Safari iOS9.3+Chrome Android38+WebView Android38+Samsung Internet3.0+Opera Android25+
Categories:
Flow content.
Phrasing content.
Embedded content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
Zero or more source elements, followed by one img element, optionally intermixed with script-supporting elements.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLPictureElement : HTMLElement {
  [HTMLConstructor] constructor();
};

The picture element is a container which provides multiple sources to its contained img element to allow authors to declaratively control or give hints to the user agent about which image resource to use, based on the screen pixel density, viewport size, image format, and other factors. It represents its children.

The picture element is somewhat different from the similar-looking video and audio elements. While all of them contain source elements, the source element's src attribute has no meaning when the element is nested within a picture element, and the resource selection algorithm is different. Also, the picture element itself does not display anything; it merely provides a context for its contained img element that enables it to choose from multiple URLs.

4.8.2 The source element

Element/source

Support in all current engines.

Firefox3.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLSourceElement

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
Categories:
None.
Contexts in which this element can be used:
As a child of a picture element, before the img element.
As a child of a media element, before any flow content or track elements.
Content model:
Nothing.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
src — Address of the resource
type — Type of embedded resource
srcset — Images to use in different situations, e.g., high-resolution displays, small monitors, etc.
sizes — Image sizes for different page layouts
media — Applicable media
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLSourceElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute USVString srcset;
  [CEReactions] attribute DOMString sizes;
  [CEReactions] attribute DOMString media;
};

The source element allows authors to specify multiple alternative source sets for img elements or multiple alternative media resources for media elements. It does not represent anything on its own.

The type attribute may be present. If present, the value must be a valid MIME type string.

The remainder of the requirements depend on whether the parent is a picture element or a media element:

source element's parent is a picture element

The srcset attribute must be present, and is a srcset attribute.

The srcset attribute contributes the image sources to the source set, if the source element is selected.

If the srcset attribute has any image candidate strings using a width descriptor, the sizes attribute must also be present, and is a sizes attribute. The sizes attribute contributes the source size to the source set, if the source element is selected.

The media attributes may also be present. If present, the value must contain a valid media query list. The user agent will skip to the next source element if the value does not match the environment.

The type attribute gives the type of the images in the source set, to allow the user agent to skip to the next source element if it does not support the given type.

If the type attribute is not specified, the user agent will not select a different source element if it finds that it does not support the image format after fetching it.

When a source element has a following sibling source element or img element with a srcset attribute specified, it must have at least one of the following:

The src attribute must not be present.

source element's parent is a media element

The src attribute gives the URL of the media resource. The value must be a valid non-empty URL potentially surrounded by spaces. This attribute must be present.

Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unnecessarily complicated approach.

The type attribute gives the type of the media resource, to help the user agent determine if it can play this media resource before fetching it. The codecs parameter, which certain MIME types define, might be necessary to specify exactly how the resource is encoded. [RFC6381]

The following list shows some examples of how to use the codecs= MIME parameter in the type attribute.

H.264 Constrained baseline profile video (main and extended video compatible) level 3 and Low-Complexity AAC audio in MP4 container
<source src='video.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
H.264 Extended profile video (baseline-compatible) level 3 and Low-Complexity AAC audio in MP4 container
<source src='video.mp4' type='video/mp4; codecs="avc1.58A01E, mp4a.40.2"'>
H.264 Main profile video level 3 and Low-Complexity AAC audio in MP4 container
<source src='video.mp4' type='video/mp4; codecs="avc1.4D401E, mp4a.40.2"'>
H.264 'High' profile video (incompatible with main, baseline, or extended profiles) level 3 and Low-Complexity AAC audio in MP4 container
<source src='video.mp4' type='video/mp4; codecs="avc1.64001E, mp4a.40.2"'>
MPEG-4 Visual Simple Profile Level 0 video and Low-Complexity AAC audio in MP4 container
<source src='video.mp4' type='video/mp4; codecs="mp4v.20.8, mp4a.40.2"'>
MPEG-4 Advanced Simple Profile Level 0 video and Low-Complexity AAC audio in MP4 container
<source src='video.mp4' type='video/mp4; codecs="mp4v.20.240, mp4a.40.2"'>
MPEG-4 Visual Simple Profile Level 0 video and AMR audio in 3GPP container
<source src='video.3gp' type='video/3gpp; codecs="mp4v.20.8, samr"'>
Theora video and Vorbis audio in Ogg container
<source src='video.ogv' type='video/ogg; codecs="theora, vorbis"'>
Theora video and Speex audio in Ogg container
<source src='video.ogv' type='video/ogg; codecs="theora, speex"'>
Vorbis audio alone in Ogg container
<source src='audio.ogg' type='audio/ogg; codecs=vorbis'>
Speex audio alone in Ogg container
<source src='audio.spx' type='audio/ogg; codecs=speex'>
FLAC audio alone in Ogg container
<source src='audio.oga' type='audio/ogg; codecs=flac'>
Dirac video and Vorbis audio in Ogg container
<source src='video.ogv' type='video/ogg; codecs="dirac, vorbis"'>

The srcset, sizes, and media attributes must not be present.

If a source element is inserted as a child of a media element that has no src attribute and whose networkState has the value NETWORK_EMPTY, the user agent must invoke the media element's resource selection algorithm.

The IDL attributes src, type, srcset, sizes and media must reflect the respective content attributes of the same name.

If the author isn't sure if user agents will all be able to render the media resources provided, the author can listen to the error event on the last source element and trigger fallback behavior:

<script>
 function fallback(video) {
   // replace <video> with its contents
   while (video.hasChildNodes()) {
     if (video.firstChild instanceof HTMLSourceElement)
       video.removeChild(video.firstChild);
     else
       video.parentNode.insertBefore(video.firstChild, video);
   }
   video.parentNode.removeChild(video);
 }
</script>
<video controls autoplay>
 <source src='video.mp4' type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
 <source src='video.ogv' type='video/ogg; codecs="theora, vorbis"'
         onerror="fallback(parentNode)">
 ...
</video>

4.8.3 The img element

Element/img

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLImageElement

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
Categories:
Flow content.
Phrasing content.
Embedded content.
Form-associated element.
If the element has a usemap attribute: Interactive content.
Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
Nothing.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
alt — Replacement text for use when images are not available
src — Address of the resource
srcset — Images to use in different situations, e.g., high-resolution displays, small monitors, etc.
sizes — Image sizes for different page layouts
crossorigin — How the element handles crossorigin requests
usemap — Name of image map to use
ismap — Whether the image is a server-side image map
width — Horizontal dimension
height — Vertical dimension
referrerpolicyReferrer policy for fetches initiated by the element
decoding — Decoding hint to use when processing this image for presentation
loading — Used when determining loading deferral
Accessibility considerations:
If the element has a non-empty alt attribute: for authors; for implementers.
Otherwise: for authors; for implementers.
DOM interface:
[Exposed=Window,
 LegacyFactoryFunction=Image(optional unsigned long width, optional unsigned long height)]
interface HTMLImageElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString alt;
  [CEReactions] attribute USVString src;
  [CEReactions] attribute USVString srcset;
  [CEReactions] attribute DOMString sizes;
  [CEReactions] attribute DOMString? crossOrigin;
  [CEReactions] attribute DOMString useMap;
  [CEReactions] attribute boolean isMap;
  [CEReactions] attribute unsigned long width;
  [CEReactions] attribute unsigned long height;
  readonly attribute unsigned long naturalWidth;
  readonly attribute unsigned long naturalHeight;
  readonly attribute boolean complete;
  readonly attribute USVString currentSrc;
  [CEReactions] attribute DOMString referrerPolicy;
  [CEReactions] attribute DOMString decoding;
  [CEReactions] attribute DOMString loading;

  Promise<undefined> decode();

  // also has obsolete members
};

An img element represents an image.

Element/img#attr-srcset

Support in all current engines.

Firefox38+Safari8+Chrome34+
Opera21+Edge79+
Edge (Legacy)≤18+Internet ExplorerNo
Firefox Android38+Safari iOS8+Chrome Android34+WebView Android37+Samsung Internet2.0+Opera Android21+

The image given by the src and srcset attributes, and any previous sibling source elements' srcset attributes if the parent is a picture element, is the embedded content; the value of the alt attribute provides equivalent content for those who cannot process images or who have image loading disabled (i.e. it is the img element's fallback content).

The requirements on the alt attribute's value are described in a separate section.

The src attribute must be present, and must contain a valid non-empty URL potentially surrounded by spaces referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted.

The requirements above imply that images can be static bitmaps (e.g. PNGs, GIFs, JPEGs), single-page vector documents (single-page PDFs, XML files with an SVG document element), animated bitmaps (APNGs, animated GIFs), animated vector graphics (XML files with an SVG document element that use declarative SMIL animation), and so forth. However, these definitions preclude SVG files with script, multipage PDF files, interactive MNG files, HTML documents, plain text documents, and so forth. [PNG] [GIF] [JPEG] [PDF] [XML] [APNG] [SVG] [MNG]

The srcset attribute may also be present, and is a srcset attribute.

The srcset attribute and the src attribute (if width descriptors are not used) contribute the image sources to the source set (if no source element was selected).

If the srcset attribute is present and has any image candidate strings using a width descriptor, the sizes attribute must also be present, and is a sizes attribute. The sizes attribute contributes the source size to the source set (if no source element was selected).

Attributes/crossorigin

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

The crossorigin attribute is a CORS settings attribute. Its purpose is to allow images from third-party sites that allow cross-origin access to be used with canvas.

The referrerpolicy attribute is a referrer policy attribute. Its purpose is to set the referrer policy used when fetching the image. [REFERRERPOLICY]

The decoding attribute indicates the preferred method to decode this image. The attribute, if present, must be an image decoding hint. This attribute's missing value default and invalid value default are both the auto state.

The loading attribute is a lazy loading attribute. Its purpose is to indicate the policy for loading images that are outside the viewport.

When the loading attribute's state is changed to the Eager state, the user agent must run these steps:

  1. Let resumptionSteps be the img element's lazy load resumption steps.

  2. If resumptionSteps is null, then return.

  3. Set the img's lazy load resumption steps to null.

  4. Invoke resumptionSteps.

<img src="1.jpeg" alt="1">
<img src="2.jpeg" loading=eager alt="2">
<img src="3.jpeg" loading=lazy alt="3">
<div id=very-large></div> <!-- Everything after this div is below the viewport -->
<img src="4.jpeg" alt="4">
<img src="5.jpeg" loading=lazy alt="5">

In the example above, the images load as follows:

1.jpeg, 2.jpeg, 4.jpeg

The images load eagerly and delay the window's load event.

3.jpeg

The image loads when layout is known, due to being in the viewport, however it does not delay the window's load event.

5.jpeg

The image loads only once scrolled into the viewport, and does not delay the window's load event.

Developers are encouraged to specify an intrinsic aspect ratio via width and height attributes on lazy loaded images, even if CSS sets the image's width and height properties, to prevent the page layout from shifting around after the image loads.


The img element must not be used as a layout tool. In particular, img elements should not be used to display transparent images, as such images rarely convey meaning and rarely add anything useful to the document.


What an img element represents depends on the src attribute and the alt attribute.

If the src attribute is set and the alt attribute is set to the empty string

The image is either decorative or supplemental to the rest of the content, redundant with some other information in the document.

If the image is available and the user agent is configured to display that image, then the element represents the element's image data.

Otherwise, the element represents nothing, and may be omitted completely from the rendering. User agents may provide the user with a notification that an image is present but has been omitted from the rendering.

If the src attribute is set and the alt attribute is set to a value that isn't empty

The image is a key part of the content; the alt attribute gives a textual equivalent or replacement for the image.

If the image is available and the user agent is configured to display that image, then the element represents the element's image data.

Otherwise, the element represents the text given by the alt attribute. User agents may provide the user with a notification that an image is present but has been omitted from the rendering.

If the src attribute is set and the alt attribute is not

The image might be a key part of the content, and there is no textual equivalent of the image available.

In a conforming document, the absence of the alt attribute indicates that the image is a key part of the content but that a textual replacement for the image was not available when the image was generated.

If the image is available and the user agent is configured to display that image, then the element represents the element's image data.

If the image has a src attribute whose value is the empty string, then the element represents nothing.

Otherwise, the user agent should display some sort of indicator that there is an image that is not being rendered, and may, if requested by the user, or if so configured, or when required to provide contextual information in response to navigation, provide caption information for the image, derived as follows:

  1. If the image has a title attribute whose value is not the empty string, then return the value of that attribute.

  2. If the image is a descendant of a figure element that has a child figcaption element, and, ignoring the figcaption element and its descendants, the figure element has no flow content descendants other than inter-element whitespace and the img element, then return the contents of the first such figcaption element.

  3. Return nothing. (There is no caption information.)

If the src attribute is not set and either the alt attribute is set to the empty string or the alt attribute is not set at all

The element represents nothing.

Otherwise

The element represents the text given by the alt attribute.

The alt attribute does not represent advisory information. User agents must not present the contents of the alt attribute in the same way as content of the title attribute.

User agents may always provide the user with the option to display any image, or to prevent any image from being displayed. User agents may also apply heuristics to help the user make use of the image when the user is unable to see it, e.g. due to a visual disability or because they are using a text terminal with no graphics capabilities. Such heuristics could include, for instance, optical character recognition (OCR) of text found within the image.

While user agents are encouraged to repair cases of missing alt attributes, authors must not rely on such behavior. Requirements for providing text to act as an alternative for images are described in detail below.

The contents of img elements, if any, are ignored for the purposes of rendering.


The usemap attribute, if present, can indicate that the image has an associated image map.

The ismap attribute, when used on an element that is a descendant of an a element with an href attribute, indicates by its presence that the element provides access to a server-side image map. This affects how events are handled on the corresponding a element.

The ismap attribute is a boolean attribute. The attribute must not be specified on an element that does not have an ancestor a element with an href attribute.

The usemap and ismap attributes can result in confusing behavior when used together with source elements with the media attribute specified in a picture element.

The img element supports dimension attributes.

HTMLImageElement/alt

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLImageElement/src

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLImageElement/srcset

Support in all current engines.

Firefox38+Safari8+Chrome34+
Opera21+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android38+Safari iOS8+Chrome Android34+WebView Android37+Samsung Internet2.0+Opera Android21+

HTMLImageElement/sizes

Support in all current engines.

Firefox38+Safari9+Chrome38+
Opera25+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android38+Safari iOS9+Chrome Android38+WebView Android38+Samsung Internet3.0+Opera Android25+

The alt, src, srcset and sizes IDL attributes must reflect the respective content attributes of the same name.

HTMLImageElement/crossOrigin

Support in all current engines.

Firefox8+Safari6+Chrome13+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android8+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The crossOrigin IDL attribute must reflect the crossorigin content attribute, limited to only known values.

HTMLImageElement/useMap

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The useMap IDL attribute must reflect the usemap content attribute.

HTMLImageElement/isMap

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The isMap IDL attribute must reflect the ismap content attribute.

HTMLImageElement/referrerPolicy

Support in all current engines.

Firefox50+Safari14+Chrome53+
Opera40+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android50+Safari iOS14+Chrome Android53+WebView Android53+Samsung Internet6.0+Opera Android41+

The referrerPolicy IDL attribute must reflect the referrerpolicy content attribute, limited to only known values.

HTMLImageElement/decoding

Support in all current engines.

Firefox63+Safari11.1+Chrome65+
Opera52+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS11.3+Chrome Android65+WebView Android65+Samsung Internet9.0+Opera Android47+

SVGImageElement/decoding

Firefox63+SafariNoChrome65+
Opera52+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOSNoChrome Android65+WebView Android65+Samsung Internet9.0+Opera Android47+

The decoding IDL attribute must reflect the decoding content attribute, limited to only known values.

HTMLImageElement/loading

Support in all current engines.

Firefox75+Safari15.4+Chrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS15.4+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

The loading IDL attribute must reflect the loading content attribute, limited to only known values.

image . width [ = value ]

HTMLImageElement/width

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
image . height [ = value ]

HTMLImageElement/height

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

These attributes return the actual rendered dimensions of the image, or zero if the dimensions are not known.

They can be set, to change the corresponding content attributes.

image . naturalWidth

HTMLImageElement/naturalWidth

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
image . naturalHeight

HTMLImageElement/naturalHeight

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

These attributes return the intrinsic dimensions of the image, or zero if the dimensions are not known.

image . complete

HTMLImageElement/complete

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns true if the image has been completely downloaded or if no image is specified; otherwise, returns false.

image . currentSrc

HTMLImageElement/currentSrc

Support in all current engines.

Firefox38+Safari9+Chrome38+
Opera25+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android38+Safari iOS9+Chrome Android38+WebView Android38+Samsung Internet3.0+Opera Android25+

Returns the image's absolute URL.

image . decode()

HTMLImageElement/decode

Support in all current engines.

Firefox68+Safari11.1+Chrome64+
Opera51+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android68+Safari iOS11.3+Chrome Android64+WebView Android64+Samsung Internet9.0+Opera Android47+

SVGImageElement/decode

Firefox68+SafariNoChrome65+
Opera52+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android68+Safari iOSNoChrome Android65+WebView Android65+Samsung Internet9.0+Opera Android47+

This method causes the user agent to decode the image in parallel, returning a promise that fulfills when decoding is complete.

The promise will be rejected with an "EncodingError" DOMException if the image cannot be decoded.

image = new Image( [ width [, height ] ] )

HTMLImageElement/Image

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Returns a new img element, with the width and height attributes set to the values passed in the relevant arguments, if applicable.

The IDL attributes width and height must return the rendered width and height of the image, in CSS pixels, if the image is being rendered, and is being rendered to a visual medium; or else the density-corrected intrinsic width and height of the image, in CSS pixels, if the image has intrinsic dimensions and is available but not being rendered to a visual medium; or else 0, if the image is not available or does not have intrinsic dimensions. [CSS]

On setting, they must act as if they reflected the respective content attributes of the same name.

The IDL attributes naturalWidth and naturalHeight must return the density-corrected intrinsic width and height of the image, in CSS pixels, if the image has intrinsic dimensions and is available, or else 0. [CSS]

Since the intrinsic dimensions of an image take into account any orientation specified in its metadata, naturalWidth and naturalHeight reflect the dimensions after applying any rotation needed to correctly orient the image, regardless of the value of the 'image-orientation' property.

The IDL attribute complete must return true if any of the following conditions is true:

Otherwise, the attribute must return false.

The currentSrc IDL attribute must return the img element's current request's current URL.

The decode() method, when invoked, must perform the following steps:

  1. Let promise be a new promise.

  2. Queue a microtask to perform the following steps:

    This is done because updating the image data takes place in a microtask as well. Thus, to make code such as

    img.src = "stars.jpg";
    img.decode();

    properly decode stars.jpg, we need to delay any processing by one microtask.

    1. If any of the following conditions are true about this img element:

      then reject promise with an "EncodingError" DOMException.

    2. Otherwise, in parallel, wait for one of the following cases to occur, and perform the corresponding actions:

      This img element's node document stops being an active document
      This img element's current request changes or is mutated
      This img element's current request's state becomes broken

      Reject promise with an "EncodingError" DOMException.

      This img element's current request's state becomes completely available

      Decode the image.

      If decoding does not need to be performed for this image (for example because it is a vector graphic), resolve promise with undefined.

      If decoding fails (for example due to invalid image data), reject promise with an "EncodingError" DOMException.

      If the decoding process completes successfully, resolve promise with undefined.

      User agents should ensure that the decoded media data stays readily available until at least the end of the next successful update the rendering step in the event loop. This is an important part of the API contract, and should not be broken if at all possible. (Typically, this would only be violated in low-memory situations that require evicting decoded image data, or when the image is too large to keep in decoded form for this period of time.)

      Animated images will become completely available only after all their frames are loaded. Thus, even though an implementation could decode the first frame before that point, the above steps will not do so, instead waiting until all frames are available.

  3. Return promise.

Without the decode() method, the process of loading an img element and then displaying it might look like the following:

const img = new Image();
img.src = "nebula.jpg";
img.onload = () => {
    document.body.appendChild(img);
};
img.onerror = () => {
    document.body.appendChild(new Text("Could not load the nebula :("));
};

However, this can cause notable dropped frames, as the paint that occurs after inserting the image into the DOM causes a synchronous decode on the main thread.

This can instead be rewritten using the decode() method:

const img = new Image();
img.src = "nebula.jpg";
img.decode().then(() => {
    document.body.appendChild(img);
}).catch(() => {
    document.body.appendChild(new Text("Could not load the nebula :("));
});

This latter form avoids the dropped frames of the original, by allowing the user agent to decode the image in parallel, and only inserting it into the DOM (and thus causing it to be painted) once the decoding process is complete.

Because the decode() method attempts to ensure that the decoded image data is available for at least one frame, it can be combined with the requestAnimationFrame() API. This means it can be used with coding styles or frameworks that ensure that all DOM modifications are batched together as animation frame callbacks:

const container = document.querySelector("#container");

const { containerWidth, containerHeight } = computeDesiredSize();
requestAnimationFrame(() => {
 container.style.width = containerWidth;
 container.style.height = containerHeight;
});

// ...

const img = new Image();
img.src = "supernova.jpg";
img.decode().then(() => {
    requestAnimationFrame(() => container.appendChild(img));
});

A legacy factory function is provided for creating HTMLImageElement objects (in addition to the factory methods from DOM such as createElement()): Image(width, height). When invoked, the legacy factory function must perform the following steps:

  1. Let document be the current global object's associated Document.

  2. Let img be the result of creating an element given document, img, and the HTML namespace.

  3. If width is given, then set an attribute value for img using "width" and width.

  4. If height is given, then set an attribute value for img using "height" and height.

  5. Return img.

A single image can have different appropriate alternative text depending on the context.

In each of the following cases, the same image is used, yet the alt text is different each time. The image is the coat of arms of the Carouge municipality in the canton Geneva in Switzerland.

Here it is used as a supplementary icon:

<p>I lived in <img src="carouge.svg" alt=""> Carouge.</p>

Here it is used as an icon representing the town:

<p>Home town: <img src="carouge.svg" alt="Carouge"></p>

Here it is used as part of a text on the town:

<p>Carouge has a coat of arms.</p>
<p><img src="carouge.svg" alt="The coat of arms depicts a lion, sitting in front of a tree."></p>
<p>It is used as decoration all over the town.</p>

Here it is used as a way to support a similar text where the description is given as well as, instead of as an alternative to, the image:

<p>Carouge has a coat of arms.</p>
<p><img src="carouge.svg" alt=""></p>
<p>The coat of arms depicts a lion, sitting in front of a tree.
It is used as decoration all over the town.</p>

Here it is used as part of a story:

<p>She picked up the folder and a piece of paper fell out.</p>
<p><img src="carouge.svg" alt="Shaped like a shield, the paper had a
red background, a green tree, and a yellow lion with its tongue
hanging out and whose tail was shaped like an S."></p>
<p>She stared at the folder. S! The answer she had been looking for all
this time was simply the letter S! How had she not seen that before? It all
came together now. The phone call where Hector had referred to a lion's tail,
the time Maria had stuck her tongue out...</p>

Here it is not known at the time of publication what the image will be, only that it will be a coat of arms of some kind, and thus no replacement text can be provided, and instead only a brief caption for the image is provided, in the title attribute:

<p>The last user to have uploaded a coat of arms uploaded this one:</p>
<p><img src="last-uploaded-coat-of-arms.cgi" title="User-uploaded coat of arms."></p>

Ideally, the author would find a way to provide real replacement text even in this case, e.g. by asking the previous user. Not providing replacement text makes the document more difficult to use for people who are unable to view images, e.g. blind users, or users or very low-bandwidth connections or who pay by the byte, or users who are forced to use a text-only web browser.

Here are some more examples showing the same picture used in different contexts, with different appropriate alternate texts each time.

<article>
 <h1>My cats</h1>
 <h2>Fluffy</h2>
 <p>Fluffy is my favorite.</p>
 <img src="fluffy.jpg" alt="She likes playing with a ball of yarn.">
 <p>She's just too cute.</p>
 <h2>Miles</h2>
 <p>My other cat, Miles just eats and sleeps.</p>
</article>
<article>
 <h1>Photography</h1>
 <h2>Shooting moving targets indoors</h2>
 <p>The trick here is to know how to anticipate; to know at what speed and
 what distance the subject will pass by.</p>
 <img src="fluffy.jpg" alt="A cat flying by, chasing a ball of yarn, can be
 photographed quite nicely using this technique.">
 <h2>Nature by night</h2>
 <p>To achieve this, you'll need either an extremely sensitive film, or
 immense flash lights.</p>
</article>
<article>
 <h1>About me</h1>
 <h2>My pets</h2>
 <p>I've got a cat named Fluffy and a dog named Miles.</p>
 <img src="fluffy.jpg" alt="Fluffy, my cat, tends to keep itself busy.">
 <p>My dog Miles and I like go on long walks together.</p>
 <h2>music</h2>
 <p>After our walks, having emptied my mind, I like listening to Bach.</p>
</article>
<article>
 <h1>Fluffy and the Yarn</h1>
 <p>Fluffy was a cat who liked to play with yarn. She also liked to jump.</p>
 <aside><img src="fluffy.jpg" alt="" title="Fluffy"></aside>
 <p>She would play in the morning, she would play in the evening.</p>
</article>

4.8.4 图片

4.8.4.1 概述

This section is non-normative.

在 HTML 中嵌入图片时,如果只有一个图片资源,就使用 img 元素和它的 src 属性。

<h2>From today's featured article</h2>
<img src="/uploads/100-marie-lloyd.jpg" alt="" width="100" height="150">
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

但是有些情况下作者希望提供多张图片让用户代理选择:

上述各种情形不是互斥的。例如,结合不同的 设备像素比 和不同的 美术设计 来提供不同的资源也是合理的。

虽然可以使用脚本来解决这些问题,但这样会引起一些其他问题:

考虑到这些,本规范引入了一些功能,以声明的方式解决上述问题。

当图片的渲染大小固定的情况下,基于 设备像素比 选择

img 元素上可以使用 srcsrcset 属性, 使用 x 描述符来提供多个只有大小不同的图片(小图是大图的缩略版)。

当图片的渲染大小依赖于 viewport 宽度时 (基于视口的选择), 使用 x 描述符不合适, 但该描述符可以与 美术设计 一起使用。

<h2>From today's featured article</h2>
<img src="/uploads/100-marie-lloyd.jpg"
     srcset="/uploads/150-marie-lloyd.jpg 1.5x, /uploads/200-marie-lloyd.jpg 2x"
     alt="" width="100" height="150">
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

用户代理可以根据用户屏幕像素密度、缩放级别,以及可能的其他因素比如用户的网络条件选择任何一个给出的资源。

为了向后兼容其他老的不知道 srcset 属性的用户代理 , 其中一个 URL 在 img 元素的 src 属性上也有指定。 这样即使在老的用户代理中也能显示一些有用的(虽然可能比用户预期的分辨率低)东西。 对于新的用户代理,src 属性也会参与资源选择,就像它被写在 srcset 中并有一个 1x 描述符一样。

图片的渲染大小由 widthheight 属性给出,使得用户代理可以在它下载完之前分配空间。

基于视口的选择

可以使用 srcsetsizes 属性,使用 w 描述符来提供多个只有大小不同的图片 (小图是大图的缩略版)。

在这个例子中,有一个横幅(使用适当的 CSS)横跨整个 视口 宽度。

<h1><img sizes="100vw" srcset="wolf-400.jpg 400w, wolf-800.jpg 800w, wolf-1600.jpg 1600w"
     src="wolf-400.jpg" alt="The rad wolf"></h1>

用户代理将会根据指定的 w 描述符和 sizes 属性指定的渲染大小为每个图片计算等效像素密度。 然后它可以根据用户屏幕的像素密度、缩放级别和任何可能的其他因素(比如用户网络状态)选择任何一个资源。

如果用户屏幕是 320 CSS 像素 宽,这等价于指定 wolf-400.jpg 1.25x, wolf-800.jpg 2.5x, wolf-1600.jpg 5x。 另一方面,如果用户屏幕是 1200 CSS 像素 宽,这等价于指定 wolf-400.jpg 0.33x, wolf-800.jpg 0.67x, wolf-1600.jpg 1.33x.。 通过使用 w 描述符和 sizes 属性, 不论用户设备有多大用户代理都可以选择下载正确的图片资源。

为了向后兼容,其中一个 URL 也指定在 img 元素的 src 属性上。在新的用户代理中,当 srcset 属性使用 w 描述符时, src 属性会被忽略。

在这个例子中,网页基于 视口 宽度有三个布局。 窄的布局有一列图片(每个图片宽度大约是 100%), 中等布局有两列图片(每个图片宽度大约是 50%), 最宽的布局有三列图片和一些页面边距(每个图片大约是 33%)。 在 视口 宽度为 30em50em 时会切换布局。

<img sizes="(max-width: 30em) 100vw, (max-width: 50em) 50vw, calc(33vw - 100px)"
     srcset="swing-200.jpg 200w, swing-400.jpg 400w, swing-800.jpg 800w, swing-1600.jpg 1600w"
     src="swing-400.jpg" alt="Kettlebell Swing">

sizes 属性设置了布局的切换点为 30em50em,也声明了在这些切换点之间图片大小为 100vw, 50vw, 或 calc(33vw - 100px)。 这些大小不一定要精确匹配 CSS 中指定的真正的图片宽度。

用户代理会从 sizes 属性中选一个宽度, 使用第一个 <media-condition> (括号中的部分)结果为真的大小, 如果所有结果都为假就使用最后一项(calc(33vw - 100px))。

例如,如果 视口 宽度为 29em,那么 (max-width: 30em) 计算为真,就会使用 100vw, 所以资源选择后的图片大小就是 29em。如果 视口 宽度是 32em,那么 (max-width: 30em) 计算为假,但 (max-width: 50em) 计算为真,就会使用 50vw,所以资源选择后图片大小就是 16em(半个 视口 宽度)。 注意更宽一点的 视口 因为布局不同而导致图片更小。

用户代理可以计算等效像素密度并选择合适的资源,类似上一个例子那样。

美术设计

可以使用 picture 元素和 source 元素和 media 属性提供多张内容不同的图片 (例如小的图片是大图的裁剪版)。

<picture>
  <source media="(min-width: 45em)" srcset="large.jpg">
  <source media="(min-width: 32em)" srcset="med.jpg">
  <img src="small.jpg" alt="The wolf runs through the snow.">
</picture>

用户代理会选择 media 属性中的媒体查询匹配的第一个 source 元素,然后从它的 srcset 属性中选择一个合适的 URL。

图片的渲染大小取决于选择了哪张图片。可以使用 CSS 来指定用户代理下载图片之前使用的宽高。

img { width: 300px; height: 300px }
@media (min-width: 32em) { img { width: 500px; height:300px } }
@media (min-width: 45em) { img { width: 700px; height:400px } }

这个例子结合了 美术设计 和 基于 设备像素比 的选择。 这个占半个 视口 的横幅提供了两个版本,一个用于宽屏一个用于窄屏。

<h1>
 <picture>
  <source media="(max-width: 500px)" srcset="banner-phone.jpeg, banner-phone-HD.jpeg 2x">
  <img src="banner.jpeg" srcset="banner-HD.jpeg 2x" alt="The Breakfast Combo">
 </picture>
</h1>
基于图片格式的选择

可以使用 source 元素上的 type 属性来提供多种格式的图片。

<h2>From today's featured article</h2>
<picture>
 <source srcset="/uploads/100-marie-lloyd.webp" type="image/webp">
 <source srcset="/uploads/100-marie-lloyd.jxr" type="image/vnd.ms-photo">
 <img src="/uploads/100-marie-lloyd.jpg" alt="" width="100" height="150">
</picture>
<p><b><a href="/wiki/Marie_Lloyd">Marie Lloyd</a></b> (1870–1922)
was an English <a href="/wiki/Music_hall">music hall</a> singer, ...

在这个例子中,用户代理会选择第一个 type 属性为支持的 MIME 类型的源。 如果用户代理支持 WebP 就会选择第一个 source 元素。 如果不支持 WebP,但支持 JPEG XR 就会选择第二个 source 元素。 如果这两种都不支持,就会选择 img 元素。

4.8.4.1.1 自适应图片

This section is non-normative.

可以使用 CSS 和媒体查询来构造动态适应用户环境的页面布局, 特别是对不同的 视口 宽高和像素密度。 但 CSS 无法操作内容;这时可以使用 img 元素的 srcset 属性和 picture 元素。 本节将介绍一个示例案例,演示如何使用这些功能。

考虑一个场景,在宽屏(宽于 600 CSS 像素)上要使用一个 300×150 的图片 a-rectangle.png, 但在小一点的屏幕上(不大于 600 CSS 像素)要使用一个 100×100 的图片 a-square.png。这样的标记可能像这样:

<figure>
 <picture>
  <source srcset="a-square.png" media="(max-width: 600px)">
  <img src="a-rectangle.png" alt="Barney Frank wears a suit and glasses.">
 </picture>
 <figcaption>Barney Frank, 2011</figcaption>
</figure>

alt 属性中放什么内容,参考 图片替代文本的要求 一节。

问题在于用户代理在图片加载时不知道使用什么样的宽高。 为了避免页面加载中布局被重排很多次,可以使用 CSS 和 CSS 媒体查询来提供宽高:

<style>
 #a { width: 300px; height: 150px; }
 @media (max-width: 600px) { #a { width: 100px; height: 100px; } }
</style>
<figure>
 <picture>
  <source srcset="a-square.png" media="(max-width: 600px)">
  <img src="a-rectangle.png" alt="Barney Frank wears a suit and glasses." id="a">
 </picture>
 <figcaption>Barney Frank, 2011</figcaption>
</figure>

也可以使用 widthheight 使用来为提供旧的用户代理提供宽高, CSS 只用于支持 picture 的用户代理:

<style media="(max-width: 600px)">
 #a { width: 100px; height: 100px; }
</style>
<figure>
 <picture>
  <source srcset="a-square.png" media="(max-width: 600px)">
  <img src="a-rectangle.png" width="300" height="150"
  alt="Barney Frank wears a suit and glasses." id="a">
 </picture>
 <figcaption>Barney Frank, 2011</figcaption>
</figure>

img 元素指定了 src 属性, 它为不支持 picture 的旧的用户代理给出了图片的 URL。 这就要讨论 src 属性应该提供哪个图片的问题了。

如果作者在旧的用户代理中想要最大的图片,标记可以这样写:

<picture>
 <source srcset="pear-mobile.jpeg" media="(max-width: 720px)">
 <source srcset="pear-tablet.jpeg" media="(max-width: 1280px)">
 <img src="pear-desktop.jpeg" alt="The pear is juicy.">
</picture>

但如果旧的用户代理更重要,就可以把所有三个图片都列在 source 元素中,完全重写掉 src 属性。

<picture>
 <source srcset="pear-mobile.jpeg" media="(max-width: 720px)">
 <source srcset="pear-tablet.jpeg" media="(max-width: 1280px)">
 <source srcset="pear-desktop.jpeg">
 <img src="pear-mobile.jpeg" alt="The pear is juicy.">
</picture>

因为在这里 src 属性在支持 picture 的用户代理下会被完全忽略,src 属性可以默认写成任何图片, 包括既不是最大的也不是最小的那个:

<picture>
 <source srcset="pear-mobile.jpeg" media="(max-width: 720px)">
 <source srcset="pear-tablet.jpeg" media="(max-width: 1280px)">
 <source srcset="pear-desktop.jpeg">
 <img src="pear-tablet.jpeg" alt="The pear is juicy.">
</picture>

上面用到了 max-width 媒体特性,给出了该图片适用的最大 (视口)大小。也可以使用 min-width

<picture>
 <source srcset="pear-desktop.jpeg" media="(min-width: 1281px)">
 <source srcset="pear-tablet.jpeg" media="(min-width: 721px)">
 <img src="pear-mobile.jpeg" alt="The pear is juicy.">
</picture>
4.8.4.2 Attributes common to source, img, and link elements
4.8.4.2.1 Srcset attributes

A srcset attribute is an attribute with requirements defined in this section.

If present, its value must consist of one or more image candidate strings, each separated from the next by a U+002C COMMA character (,). If an image candidate string contains no descriptors and no ASCII whitespace after the URL, the following image candidate string, if there is one, must begin with one or more ASCII whitespace.

An image candidate string consists of the following components, in order, with the further restrictions described below this list:

  1. Zero or more ASCII whitespace.

  2. A valid non-empty URL that does not start or end with a U+002C COMMA character (,), referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted.

  3. Zero or more ASCII whitespace.

  4. Zero or one of the following:

  5. Zero or more ASCII whitespace.

There must not be an image candidate string for an element that has the same width descriptor value as another image candidate string's width descriptor value for the same element.

There must not be an image candidate string for an element that has the same pixel density descriptor value as another image candidate string's pixel density descriptor value for the same element. For the purpose of this requirement, an image candidate string with no descriptors is equivalent to an image candidate string with a 1x descriptor.

If an image candidate string for an element has the width descriptor specified, all other image candidate strings for that element must also have the width descriptor specified.

The specified width in an image candidate string's width descriptor must match the intrinsic width in the resource given by the image candidate string's URL, if it has an intrinsic width.

If an element has a sizes attribute present, all image candidate strings for that element must have the width descriptor specified.

4.8.4.2.2 Sizes attributes

A sizes attribute is an attribute with requirements defined in this section.

If present, the value must be a valid source size list.

A valid source size list is a string that matches the following grammar: [CSSVALUES] [MQ]

<source-size-list> = [ <source-size># , ]? <source-size-value>
<source-size> = <media-condition> <source-size-value>
<source-size-value> = <length>

A <source-size-value> must not be negative, and must not use CSS functions other than the math functions.

The <source-size-value> gives the intended layout width of the image. The author can specify different widths for different environments with <media-condition>s.

Percentages are not allowed in a <source-size-value>, to avoid confusion about what it would be relative to. The 'vw' unit can be used for sizes relative to the viewport width.

4.8.4.3 Processing model

An img element has a current request and a pending request. The current request is initially set to a new image request. The pending request is initially set to null.

An image request has a state, current URL, and image data.

An image request's state is one of the following:

Unavailable
The user agent hasn't obtained any image data, or has obtained some or all of the image data but hasn't yet decoded enough of the image to get the image dimensions.
Partially available
The user agent has obtained some of the image data and at least the image dimensions are available.
Completely available
The user agent has obtained all of the image data and at least the image dimensions are available.
Broken
The user agent has obtained all of the image data that it can, but it cannot even decode the image enough to get the image dimensions (e.g. the image is corrupted, or the format is not supported, or no data could be obtained).

An image request's current URL is initially the empty string.

An image request's image data is the decoded image data.

When an image request's state is either partially available or completely available, the image request is said to be available.

When an img element's current request's state is completely available and the user agent can decode the media data without errors, then the img element is said to be fully decodable.

An image request's state is initially unavailable.

When an img element's current request is available, the img element provides a paint source whose width is the image's density-corrected intrinsic width (if any), whose height is the image's density-corrected intrinsic height (if any), and whose appearance is the intrinsic appearance of the image.


An img element is said to use srcset or picture if it has a srcset attribute specified or if it has a parent that is a picture element.


Each img element has a last selected source, which must initially be null.

Each image request has a current pixel density, which must initially be undefined.

When an img element has a current pixel density that is not 1.0, the element's image data must be treated as if its resolution, in device pixels per CSS pixels, was the current pixel density. The image's density-corrected intrinsic width and height are the intrinsic width and height after taking into account the current pixel density.

For example, if the current pixel density is 3.125, that means that there are 300 device pixels per CSS inch, and thus if the image data is 300x600, it has intrinsic dimensions of 96 CSS pixels by 192 CSS pixels.

All img and link elements are associated with a source set.

A source set is an ordered set of zero or more image sources and a source size.

An image source is a URL, and optionally either a pixel density descriptor, or a width descriptor.

A source size is a <source-size-value>. When a source size has a unit relative to the viewport, it must be interpreted relative to the img element's node document's viewport. Other units must be interpreted the same as in Media Queries. [MQ]


A parse error for algorithms in this section indicates a non-fatal mismatch between input and requirements. User agents are encouraged to expose parse errors somehow.


Whether the image is fetched successfully or not (e.g. whether the response status was an ok status) must be ignored when determining the image's type and whether it is a valid image.

This allows servers to return images with error responses, and have them displayed.

The user agent should apply the image sniffing rules to determine the type of the image, with the image's associated Content-Type headers giving the official type. If these rules are not applied, then the type of the image must be the type given by the image's associated Content-Type headers.

User agents must not support non-image resources with the img element (e.g. XML files whose document element is an HTML element). User agents must not run executable code (e.g. scripts) embedded in the image resource. User agents must only display the first page of a multipage resource (e.g. a PDF file). User agents must not allow the resource to act in an interactive fashion, but should honour any animation in the resource.

This specification does not specify which image types are to be supported.

4.8.4.3.1 When to obtain images

By default, images are obtained immediately. User agents may provide users with the option to instead obtain them on-demand. (The on-demand option might be used by bandwidth-constrained users, for example.)

When obtaining images immediately, the user agent must synchronously update the image data of the img element, with the restart animation flag set if so stated, whenever that element is created or has experienced relevant mutations.

When obtaining images on demand, the user agent must update the image data of an img element whenever it needs the image data (i.e., on demand), but only if the img element's current request's state is unavailable. When an img element has experienced relevant mutations, if the user agent only obtains images on demand, the img element's current request's state must return to unavailable.

4.8.4.3.2 响应 DOM 变化

img 元素 相关的变化 包括:

4.8.4.3.3 The list of available images

Each Document object must have a list of available images. Each image in this list is identified by a tuple consisting of an absolute URL, a CORS settings attribute mode, and, if the mode is not No CORS, an origin. Each image furthermore has an ignore higher-layer caching flag. User agents may copy entries from one Document object's list of available images to another at any time (e.g. when the Document is created, user agents can add to it all the images that are loaded in other Documents), but must not change the keys of entries copied in this way when doing so, and must unset the ignore higher-layer caching flag for the copied entry. User agents may also remove images from such lists at any time (e.g. to save memory). User agents must remove entries in the list of available images as appropriate given higher-layer caching semantics for the resource (e.g. the HTTP `Cache-Control` response header) when the ignore higher-layer caching flag is unset.

The list of available images is intended to enable synchronous switching when changing the src attribute to a URL that has previously been loaded, and to avoid re-downloading images in the same document even when they don't allow caching per HTTP. It is not used to avoid re-downloading the same image while the previous image is still loading.

The user agent can also store the image data separately from the list of available images.

For example, if a resource has the HTTP response header `Cache-Control: must-revalidate`, and its ignore higher-layer caching flag is unset, the user agent would remove it from the list of available images but could keep the image data separately, and use that if the server responds with a 304 Not Modified status.

4.8.4.3.4 Decoding images

Image data is usually encoded in order to reduce file size. This means that in order for the user agent to present the image to the screen, the data needs to be decoded. Decoding is the process which converts an image's media data into a bitmap form, suitable for presentation to the screen. Note that this process can be slow relative to other processes involved in presenting content. Thus, the user agent can choose when to perform decoding, in order to create the best user experience.

Image decoding is said to be synchronous if it prevents presentation of other content until it is finished. Typically, this has an effect of atomically presenting the image and any other content at the same time. However, this presentation is delayed by the amount of time it takes to perform the decode.

Image decoding is said to be asynchronous if it does not prevent presentation of other content. This has an effect of presenting non-image content faster. However, the image content is missing on screen until the decode finishes. Once the decode is finished, the screen is updated with the image.

In both synchronous and asynchronous decoding modes, the final content is presented to screen after the same amount of time has elapsed. The main difference is whether the user agent presents non-image content ahead of presenting the final content.

In order to aid the user agent in deciding whether to perform synchronous or asynchronous decode, the decoding attribute can be set on img elements. The possible values of the decoding attribute are the following image decoding hint keywords:

Keyword State Description
sync Sync Indicates a preference to decode this image synchronously for atomic presentation with other content.
async Async Indicates a preference to decode this image asynchronously to avoid delaying presentation of other content.
auto Auto Indicates no preference in decoding mode (the default).

When decoding an image, the user agent should respect the preference indicated by the decoding attribute's state. If the state indicated is auto, then the user agent is free to choose any decoding behavior.

It is also possible to control the decoding behavior using the decode() method. Since the decode() method performs decoding independently from the process responsible for presenting content to screen, it is unaffected by the decoding attribute.

4.8.4.3.5 Updating the image data

This algorithm cannot be called from steps running in parallel. If a user agent needs to call this algorithm from steps running in parallel, it needs to queue a task to do so.

When the user agent is to update the image data of an img element, optionally with the restart animations flag set, it must run the following steps:

  1. If the element's node document is not the active document, then:

    1. Continue running this algorithm in parallel.

    2. Wait until the element's node document is the active document.

    3. If another instance of this algorithm for this img element was started after this instance (even if it aborted and is no longer running), then return.

    4. Queue a microtask to continue this algorithm.

  2. If the user agent cannot support images, or its support for images has been disabled, then abort the image request for the current request and the pending request, set current request's state to unavailable, set pending request to null, and return.

  3. Let selected source be null and selected pixel density be undefined.

  4. If the element does not use srcset or picture and it has a src attribute specified whose value is not the empty string, then set selected source to the value of the element's src attribute and set selected pixel density to 1.0.

  5. Set the element's last selected source to selected source.

  6. If selected source is not null, then:

    1. Parse selected source, relative to the element's node document. If that is not successful, then abort this inner set of steps. Otherwise, let urlString be the resulting URL string.

    2. Let key be a tuple consisting of urlString, the img element's crossorigin attribute's mode, and, if that mode is not No CORS, the node document's origin.

    3. If the list of available images contains an entry for key, then:

      1. Set the ignore higher-layer caching flag for that entry.

      2. Abort the image request for the current request and the pending request.

      3. Set pending request to null.

      4. Let current request be a new image request whose image data is that of the entry and whose state is completely available.

      5. Update the presentation of the image appropriately.

      6. Set current request's current pixel density to selected pixel density.

      7. Queue an element task on the DOM manipulation task source given the img element and following steps:

        1. If restart animation is set, then restart the animation.

        2. Set current request's current URL to urlString.

        3. Fire an event named load at the img element.

      8. Abort the update the image data algorithm.

  7. Queue a microtask to perform the rest of this algorithm, allowing the task that invoked this algorithm to continue.

  8. If another instance of this algorithm for this img element was started after this instance (even if it aborted and is no longer running), then return.

    Only the last instance takes effect, to avoid multiple requests when, for example, the src, srcset, and crossorigin attributes are all set in succession.

  9. Let selected source and selected pixel density be the URL and pixel density that results from selecting an image source, respectively.

  10. If selected source is null, then:

    1. Set the current request's state to broken, abort the image request for the current request and the pending request, and set pending request to null.

    2. Queue an element task on the DOM manipulation task source given the img element and the following steps:

      1. Change the current request's current URL to the empty string.

      2. If the element has a src attribute or it uses srcset or picture, fire an event named error at the img element.

    3. Return.

  11. Parse selected source, relative to the element's node document, and let urlString be the resulting URL string. If that is not successful, then:

    1. Abort the image request for the current request and the pending request.

    2. Set the current request's state to broken.

    3. Set pending request to null.

    4. Queue an element task on the DOM manipulation task source given the img element and the following steps:

      1. Change the current request's current URL to selected source.

      2. Fire an event named error at the img element.

    5. Return.

  12. If the pending request is not null and urlString is the same as the pending request's current URL, then return.

  13. If urlString is the same as the current request's current URL and current request's state is partially available, then abort the image request for the pending request, queue an element task on the DOM manipulation task source given the img element to restart the animation if restart animation is set, and return.

  14. If the pending request is not null, then abort the image request for the pending request.

  15. Set image request to a new image request whose current URL is urlString.

  16. If current request's state is unavailable or broken, then set the current request to image request. Otherwise, set the pending request to image request.

  17. Let request be the result of creating a potential-CORS request given urlString, "image", and the current state of the element's crossorigin content attribute.

  18. Set request's client to the element's node document's relevant settings object.

  19. If the element uses srcset or picture, set request's initiator to "imageset".

  20. Set request's referrer policy to the current state of the element's referrerpolicy attribute.

  21. Let delay load event be true if the img's lazy loading attribute is in the Eager state, or if scripting is disabled for the img, and false otherwise.

  22. If the will lazy load element steps given the img return true, then:

    1. Set the img's lazy load resumption steps to the rest of this algorithm starting with the step labeled fetch the image.

    2. Start intersection-observing a lazy loading element for the img element.

    3. Return.

  23. Fetch the image: Fetch request. Let this instance of the fetching algorithm be associated with image request.

    The resource obtained in this fashion, if any, is image request's image data. It can be either CORS-same-origin or CORS-cross-origin; this affects the origin of the image itself (e.g. when used on a canvas).

    When delay load event is true, fetching the image must delay the load event of the element's node document until the task that is queued by the networking task source once the resource has been fetched (defined below) has been run.

    This, unfortunately, can be used to perform a rudimentary port scan of the user's local network (especially in conjunction with scripting, though scripting isn't actually necessary to carry out such an attack). User agents may implement cross-origin access control policies that are stricter than those described above to mitigate this attack, but unfortunately such policies are typically not compatible with existing web content.

  24. Continue the remaining steps in parallel, but without missing any data from fetching.

  25. As soon as possible, jump to the first applicable entry from the following list:

    If the resource type is multipart/x-mixed-replace

    The next task that is queued by the networking task source while the image is being fetched must run the following steps:

    1. If image request is the pending request and at least one body part has been completely decoded, abort the image request for the current request, upgrade the pending request to the current request.

    2. Otherwise, if image request is the pending request and the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, abort the image request for the current request, upgrade the pending request to the current request, and set the current request's state to broken.

    3. Otherwise, if image request is the current request, its state is unavailable, and the user agent is able to determine image request's image's width and height, set the current request's state to partially available.

    4. Otherwise, if image request is the current request, its state is unavailable, and the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, set the current request's state to broken.

    Each task that is queued by the networking task source while the image is being fetched must update the presentation of the image, but as each new body part comes in, it must replace the previous image. Once one body part has been completely decoded, the user agent must set the img element's current request's state to completely available and queue an element task on the DOM manipulation task source given the img element to fire an event named load at the img element.

    If the resource type and data corresponds to a supported image format, as described below

    The next task that is queued by the networking task source while the image is being fetched must run the following steps:

    1. If the user agent is able to determine image request's image's width and height, and image request is pending request, set image request's state to partially available.

    2. Otherwise, if the user agent is able to determine image request's image's width and height, and image request is current request, update the img element's presentation appropriately and set image request's state to partially available.

    3. Otherwise, if the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, and image request is pending request, abort the image request for the current request and the pending request, upgrade the pending request to the current request, set current request's state to broken, and fire an event named error at the img element.

    4. Otherwise, if the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, and image request is current request, abort the image request for image request and fire an event named error at the img element.

    That task, and each subsequent task, that is queued by the networking task source while the image is being fetched, if image request is the current request, must update the presentation of the image appropriately (e.g., if the image is a progressive JPEG, each packet can improve the resolution of the image).

    Furthermore, the last task that is queued by the networking task source once the resource has been fetched must additionally run these steps:

    1. If image request is the pending request, abort the image request for the current request, upgrade the pending request to the current request and update the img element's presentation appropriately.

    2. Set image request to the completely available state.

    3. Add the image to the list of available images using the key key, with the ignore higher-layer caching flag set.

    4. Fire an event named load at the img element.

    Otherwise

    The image data is not in a supported file format; the user agent must set image request's state to broken, abort the image request for the current request and the pending request, upgrade the pending request to the current request if image request is the pending request, and then queue an element task on the DOM manipulation task source given the img element to fire an event named error at the img element.

While a user agent is running the above algorithm for an element x, there must be a strong reference from the element's node document to the element x, even if that element is not connected.

To abort the image request for an image request image request means to run the following steps:

  1. Forget image request's image data, if any.

  2. Abort any instance of the fetching algorithm for image request, discarding any pending tasks generated by that algorithm.

To upgrade the pending request to the current request for an img element means to run the following steps:

  1. Let the img element's current request be the pending request.

  2. Let the img element's pending request be null.

4.8.4.3.6 Selecting an image source

When asked to select an image source for a given img or link element el, user agents must do the following:

  1. Update the source set for el.

  2. If el's source set is empty, return null as the URL and undefined as the pixel density.

  3. Otherwise, take el's source set and let it be source set.

  4. If an entry b in source set has the same associated pixel density descriptor as an earlier entry a in source set, then remove entry b. Repeat this step until none of the entries in source set have the same associated pixel density descriptor as an earlier entry.

  5. In a user agent-specific manner, choose one image source from source set. Let this be selected source.

  6. Return selected source and its associated pixel density.

4.8.4.3.7 Updating the source set

When asked to update the source set for a given img or link element el, user agents must do the following:

  1. Set el's source set to an empty source set.

  2. Let elements be « el ».

  3. If el is an img element whose parent node is a picture element, then replace the contents of elements with el's parent node's child elements, retaining relative order.

  4. For each child in elements:

    1. If child is el:

      1. Let source set be an empty source set.

      2. If child has a srcset or imagesrcset attribute, parse child's srcset attribute and set source set to the returned source set.

      3. Parse child's sizes attribute, and let source set's source size be the returned value.

      4. If child has a src or href attribute whose value is not the empty string and source set does not contain an image source with a pixel density descriptor value of 1, and no image source with a width descriptor, append child's src or href attribute value to source set.

      5. Normalize the source densities of source set.

      6. Let el's source set be source set.

      7. Return.

        If el is a link element, then elements contains only el, so this step will be reached immediately and the rest of the algorithm will not run.

    2. Assert: child is not a link element.

    3. If child is not a source element, continue to the next child. Otherwise, child is a source element.

    4. If child does not have a srcset attribute, continue to the next child.

    5. Parse child's srcset attribute and let the returned source set be source set.

    6. If source set has zero image sources, continue to the next child.

    7. If child has a media attribute, and its value does not match the environment, continue to the next child.

    8. Parse child's sizes attribute with the fallback width width, and let source set's source size be the returned value.

    9. If child has a type attribute, and its value is an unknown or unsupported MIME type, continue to the next child.

    10. Normalize the source densities of source set.

    11. Let el's source set be source set.

    12. Return.

Each img element independently considers its previous sibling source elements plus the img element itself for selecting an image source, ignoring any other (invalid) elements, including other img elements in the same picture element, or source elements that are following siblings of the relevant img element.

4.8.4.3.8 Parsing a srcset attribute

When asked to parse a srcset attribute from an element, parse the value of the element's srcset attribute as follows:

  1. Let input be the value passed to this algorithm.

  2. Let position be a pointer into input, initially pointing at the start of the string.

  3. Let candidates be an initially empty source set.

  4. Splitting loop: Collect a sequence of code points that are ASCII whitespace or U+002C COMMA characters from input given position. If any U+002C COMMA characters were collected, that is a parse error.

  5. If position is past the end of input, return candidates.

  6. Collect a sequence of code points that are not ASCII whitespace from input given position, and let that be url.

  7. Let descriptors be a new empty list.

  8. If url ends with U+002C (,), then:

    1. Remove all trailing U+002C COMMA characters from url. If this removed more than one character, that is a parse error.

    Otherwise:

    1. Descriptor tokenizer: Skip ASCII whitespace within input given position.

    2. Let current descriptor be the empty string.

    3. Let state be in descriptor.

    4. Let c be the character at position. Do the following depending on the value of state. For the purpose of this step, "EOF" is a special character representing that position is past the end of input.

      In descriptor

      Do the following, depending on the value of c:

      ASCII whitespace

      If current descriptor is not empty, append current descriptor to descriptors and let current descriptor be the empty string. Set state to after descriptor.

      U+002C COMMA (,)

      Advance position to the next character in input. If current descriptor is not empty, append current descriptor to descriptors. Jump to the step labeled descriptor parser.

      U+0028 LEFT PARENTHESIS (()

      Append c to current descriptor. Set state to in parens.

      EOF

      If current descriptor is not empty, append current descriptor to descriptors. Jump to the step labeled descriptor parser.

      Anything else

      Append c to current descriptor.

      In parens

      Do the following, depending on the value of c:

      U+0029 RIGHT PARENTHESIS ())

      Append c to current descriptor. Set state to in descriptor.

      EOF

      Append current descriptor to descriptors. Jump to the step labeled descriptor parser.

      Anything else

      Append c to current descriptor.

      After descriptor

      Do the following, depending on the value of c:

      ASCII whitespace

      Stay in this state.

      EOF

      Jump to the step labeled descriptor parser.

      Anything else

      Set state to in descriptor. Set position to the previous character in input.

      Advance position to the next character in input. Repeat this step.

      In order to be compatible with future additions, this algorithm supports multiple descriptors and descriptors with parens.

  9. Descriptor parser: Let error be no.

  10. Let width be absent.

  11. Let density be absent.

  12. Let future-compat-h be absent.

  13. For each descriptor in descriptors, run the appropriate set of steps from the following list:

    If the descriptor consists of a valid non-negative integer followed by a U+0077 LATIN SMALL LETTER W character
    1. If the user agent does not support the sizes attribute, let error be yes.

      A conforming user agent will support the sizes attribute. However, user agents typically implement and ship features in an incremental manner in practice.

    2. If width and density are not both absent, then let error be yes.

    3. Apply the rules for parsing non-negative integers to the descriptor. If the result is zero, let error be yes. Otherwise, let width be the result.

    If the descriptor consists of a valid floating-point number followed by a U+0078 LATIN SMALL LETTER X character
    1. If width, density and future-compat-h are not all absent, then let error be yes.

    2. Apply the rules for parsing floating-point number values to the descriptor. If the result is less than zero, let error be yes. Otherwise, let density be the result.

      If density is zero, the intrinsic dimensions will be infinite. User agents are expected to have limits in how big images can be rendered, which is allowed by the hardware limitations clause.

    If the descriptor consists of a valid non-negative integer followed by a U+0068 LATIN SMALL LETTER H character

    This is a parse error.

    1. If future-compat-h and density are not both absent, then let error be yes.

    2. Apply the rules for parsing non-negative integers to the descriptor. If the result is zero, let error be yes. Otherwise, let future-compat-h be the result.

    Anything else

    Let error be yes.

  14. If future-compat-h is not absent and width is absent, let error be yes.

  15. If error is still no, then append a new image source to candidates whose URL is url, associated with a width width if not absent and a pixel density density if not absent. Otherwise, there is a parse error.

  16. Return to the step labeled splitting loop.

4.8.4.3.9 Parsing a sizes attribute

When asked to parse a sizes attribute from an element, parse a comma-separated list of component values from the value of the element's sizes attribute (or the empty string, if the attribute is absent), and let unparsed sizes list be the result. [CSSSYNTAX]

For each unparsed size in unparsed sizes list:

  1. Remove all consecutive <whitespace-token>s from the end of unparsed size. If unparsed size is now empty, that is a parse error; continue to the next iteration of this algorithm.

  2. If the last component value in unparsed size is a valid non-negative <source-size-value>, let size be its value and remove the component value from unparsed size. Any CSS function other than the math functions is invalid. Otherwise, there is a parse error; continue to the next iteration of this algorithm.

  3. Remove all consecutive <whitespace-token>s from the end of unparsed size. If unparsed size is now empty, return size and exit this algorithm. If this was not the last item in unparsed sizes list, that is a parse error.

  4. Parse the remaining component values in unparsed size as a <media-condition>. If it does not parse correctly, or it does parse correctly but the <media-condition> evaluates to false, continue to the next iteration of this algorithm. [MQ]

  5. Return size and exit this algorithm.

If the above algorithm exhausts unparsed sizes list without returning a size value, then return 100vw.

While a valid source size list only contains a bare <source-size-value> (without an accompanying <media-condition>) as the last entry in the <source-size-list>, the parsing algorithm technically allows such at any point in the list, and will accept it immediately as the size if the preceding entries in the list weren't used. This is to enable future extensions, and protect against simple author errors such as a final trailing comma.

4.8.4.3.10 源像素密度规范化

image source 除 URL 之外可以有一个 像素密度描述符, 一个 宽度描述符 或者什么描述符都没有。 source set 规范化后会给每个 image source 一个 像素密度描述符

当要求 规范化 source set source set 的源像素密度时, 用户代理必须执行以下操作:

  1. source sizesource setsource size

  2. source set 中的每个 image source

    1. 如果 image source 有一个 像素密度描述符, 继续下一个 image source

    2. 否则,如果 image source 有一个 宽度描述符, 把 宽度描述符 替换为 像素密度描述符,其 宽度描述符的值 除以 源大小,单位是 x

      如果 源大小 是零,像素密度会是无穷大, 这会导致 固有尺寸 为 0 乘以 0。

    3. 否则,给出 image source像素密度描述符1x

4.8.4.3.11 Reacting to environment changes

The user agent may at any time run the following algorithm to update an img element's image in order to react to changes in the environment. (User agents are not required to ever run this algorithm; for example, if the user is not looking at the page any more, the user agent might want to wait until the user has returned to the page before determining which image to use, in case the environment changes again in the meantime.)

User agents are encouraged to run this algorithm in particular when the user changes the viewport's size (e.g. by resizing the window or changing the page zoom), and when an img element is inserted into a document, so that the density-corrected intrinsic width and height match the new viewport, and so that the correct image is chosen when art direction is involved.

  1. Await a stable state. The synchronous section consists of all the remaining steps of this algorithm until the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)

  2. ⌛ If the img element does not use srcset or picture, its node document is not the active document, has image data whose resource type is multipart/x-mixed-replace, or the pending request is not null, then return.

  3. ⌛ Let selected source and selected pixel density be the URL and pixel density that results from selecting an image source, respectively.

  4. ⌛ If selected source is null, then return.

  5. ⌛ If selected source and selected pixel density are the same as the element's last selected source and current pixel density, then return.

  6. Parse selected source, relative to the element's node document, and let urlString be the resulting URL string. If that is not successful, then return.

  7. ⌛ Let corsAttributeState be the state of the element's crossorigin content attribute.

  8. ⌛ Let origin be the origin of the img element's node document.

  9. ⌛ Let client be the img element's node document's relevant settings object.

  10. ⌛ Let key be a tuple consisting of urlString, corsAttributeState, and, if corsAttributeState is not No CORS, origin.

  11. ⌛ Let image request be a new image request whose current URL is urlString

  12. ⌛ Let the element's pending request be image request.

  13. End the synchronous section, continuing the remaining steps in parallel.

  14. If the list of available images contains an entry for key, then set image request's image data to that of the entry. Continue to the next step.

    Otherwise:

    1. Let request be the result of creating a potential-CORS request given urlString, "image", and corsAttributeState.

    2. Set request's client to client, initiator to "imageset", and set request's synchronous flag.

    3. Set request's referrer policy to the current state of the element's referrerpolicy attribute.

    4. Let response be the result of fetching request.

    5. If response's unsafe response is a network error or if the image format is unsupported (as determined by applying the image sniffing rules, again as mentioned earlier), or if the user agent is able to determine that image request's image is corrupted in some fatal way such that the image dimensions cannot be obtained, or if the resource type is multipart/x-mixed-replace, then let pending request be null and abort these steps.

    6. Otherwise, response's unsafe response is image request's image data. It can be either CORS-same-origin or CORS-cross-origin; this affects the origin of the image itself (e.g., when used on a canvas).

  15. Queue an element task on the DOM manipulation task source given the img element and the following steps:

    1. If the img element has experienced relevant mutations since this algorithm started, then let pending request be null and abort these steps.

    2. Let the img element's last selected source be selected source and the img element's current pixel density be selected pixel density.

    3. Set the image request's state to completely available.

    4. Add the image to the list of available images using the key key, with the ignore higher-layer caching flag set.

    5. Upgrade the pending request to the current request.

    6. Update the img element's presentation appropriately.

    7. Fire an event named load at the img element.

4.8.4.4 为图片提供替代文字的要求
4.8.4.4.1 通用指引

除非另有说明,必须指定 alt 属性且它的值不能为空,且必须适合替代图片。 对 alt 属性具体的要求取决于它要表示什么图片,在下面给出描述。

编写替代文本时要考虑的最一般规则如下: 其目的是用其 alt 属性的文本替换每个图像不会改变页面的含义

所以,通常在编写替代文本时,考虑如果不能包含一个图片时会怎样写。

基于此的一个推论是 alt 属性的值不应该包含 图片的 caption, titlelegend 文本。 应该包含的替代文本是用于替代图片的;而不是图片的补充。 用 title 属性可以提供补充信息。

另一个推论是 alt 属性的值不应该重复已经由后面的文字提供的信息。

考虑替代文字的一种方式是,假设你在跟某人打电话, 这时如何直接读出这个包含图片的页面,而不用提这里有一张图片。 无论你说什么来替代图像,这通常都是编写替代文本的良好开端。

当创建 超链接a 元素或 button 元素 没有文本内容只包含一个或更多图片时,alt 属性必须包含一些文字来传达链接或按钮的用途。

在这个例子中,要求用户从三个颜色中选择一个喜欢的颜色。 每个颜色由图片给出,但对于用户代理配置为不显示图片的用户会用颜色名来替代:

<h1>Pick your color</h1>
<ul>
 <li><a href="green.html"><img src="green.jpeg" alt="Green"></a></li>
 <li><a href="blue.html"><img src="blue.jpeg" alt="Blue"></a></li>
 <li><a href="red.html"><img src="red.jpeg" alt="Red"></a></li>
</ul>

在这个例子中,每个按钮有很多图片来表示用户想要输出的颜色类型。 每种情况都用第一个图片提供替代文本。

<button name="rgb"><img src="red" alt="RGB"><img src="green" alt=""><img src="blue" alt=""></button>
<button name="cmyk"><img src="cyan" alt="CMYK"><img src="magenta" alt=""><img src="yellow" alt=""><img src="black" alt=""></button>

由于每个图片表示文字的一部分,也可以写成这样:

<button name="rgb"><img src="red" alt="R"><img src="green" alt="G"><img src="blue" alt="B"></button>
<button name="cmyk"><img src="cyan" alt="C"><img src="magenta" alt="M"><img src="yellow" alt="Y"><img src="black" alt="K"></button>

但是对于其他的替代文本,可能不能这样写,把所有替代文本放到每种情况的一张图片中可能更合理:

<button name="rgb"><img src="red" alt="sRGB profile"><img src="green" alt=""><img src="blue" alt=""></button>
<button name="cmyk"><img src="cyan" alt="CMYK profile"><img src="magenta" alt=""><img src="yellow" alt=""><img src="black" alt=""></button>
4.8.4.4.3 A phrase or paragraph with an alternative graphical representation: charts, diagrams, graphs, maps, illustrations

Sometimes something can be more clearly stated in graphical form, for example as a flowchart, a diagram, a graph, or a simple map showing directions. In such cases, an image can be given using the img element, but the lesser textual version must still be given, so that users who are unable to view the image (e.g. because they have a very slow connection, or because they are using a text-only browser, or because they are listening to the page being read out by a hands-free automobile voice web browser, or simply because they are blind) are still able to understand the message being conveyed.

The text must be given in the alt attribute, and must convey the same message as the image specified in the src attribute.

It is important to realize that the alternative text is a replacement for the image, not a description of the image.

In the following example we have a flowchart in image form, with text in the alt attribute rephrasing the flowchart in prose form:

<p>In the common case, the data handled by the tokenization stage
comes from the network, but it can also come from script.</p>
<p><img src="images/parsing-model-overview.svg" alt="The Network
passes data to the Input Stream Preprocessor, which passes it to the
Tokenizer, which passes it to the Tree Construction stage. From there,
data goes to both the DOM and to Script Execution. Script Execution is
linked to the DOM, and, using document.write(), passes data to the
Tokenizer."></p>

Here's another example, showing a good solution and a bad solution to the problem of including an image in a description.

First, here's the good solution. This sample shows how the alternative text should just be what you would have put in the prose if the image had never existed.

<!-- This is the correct way to do things. -->
<p>
 You are standing in an open field west of a house.
 <img src="house.jpeg" alt="The house is white, with a boarded front door.">
 There is a small mailbox here.
</p>

Second, here's the bad solution. In this incorrect way of doing things, the alternative text is simply a description of the image, instead of a textual replacement for the image. It's bad because when the image isn't shown, the text doesn't flow as well as in the first example.

<!-- This is the wrong way to do things. -->
<p>
 You are standing in an open field west of a house.
 <img src="house.jpeg" alt="A white house, with a boarded front door.">
 There is a small mailbox here.
</p>

Text such as "Photo of white house with boarded door" would be equally bad alternative text (though it could be suitable for the title attribute or in the figcaption element of a figure with this image).

4.8.4.4.4 带有替代图形表示的短语或标签:图标,徽标

一个文档可以包含图标信息,图标是为了帮助视觉浏览器的用户一目了然地识别功能。

有些情况下,图标是文本标签的补充,它们传达同样的含义。 那些情况下,alt 属性必须存在且为空。

下面的图标在文本旁边表达同样的含义,所以它们的 alt 属性为空:

<nav>
 <p><a href="/help/"><img src="/icons/help.png" alt=""> Help</a></p>
 <p><a href="/configure/"><img src="/icons/configuration.png" alt="">
 Configuration Tools</a></p>
</nav>

另外一些情况下,图标旁边没有文字来描述它的含义;这样的图标就应该解释自己的含义。 那些情况下,同等的文本标签必须通过alt 属性给出。

下面是一个新闻站点,每个文章用一个图标来表示对应的话题。

<body>
 <article>
  <header>
   <h1>Ratatouille wins <i>Best Movie of the Year</i> award</h1>
   <p><img src="movies.png" alt="Movies"></p>
  </header>
  <p>Pixar has won yet another <i>Best Movie of the Year</i> award,
  making this its 8th win in the last 12 years.</p>
 </article>
 <article>
  <header>
   <h1>Latest TWiT episode is online</h1>
   <p><img src="podcasts.png" alt="Podcasts"></p>
  </header>
  <p>The latest TWiT episode has been posted, in which we hear
  several tech news stories as well as learning much more about the
  iPhone. This week, the panelists compare how reflective their
  iPhones' Apple logos are.</p>
 </article>
</body>

许多页面包含标志(Logo),徽章,旗帜或徽记,代表某个特定实体,如公司,组织,项目,乐队,软件包,国家或某些特定实体。

如果标志(Logo)被用于表示实体,例如作为页面标题。 alt 属性必须包含由徽标表示的实体的名称。 alt 属性 不得 包含类似 “logo” 的文字,因为它传达的不是标志,而是实体本身。

如果标志(Logo)用在它表示的实体的名字旁边,那这个标志就是补充性的, 其 alt 属性必须为空。

如果标志(Logo)仅用作装饰材料(例如品牌标识,或者例如,作为提及徽标所属实体的文章中的配图),那么它适用下文的纯粹装饰性图片的条目。 如果实际上讨论的就是标志,那么它就用作了短语或段落(徽标的描述)并且有替代的图形表示(徽标本身),它适用上面的第一个条目。

在下面的代码片段中,上面四种情况都存在。首先这个标志用于表示一个公司:

<h1><img src="XYZ.gif" alt="The XYZ company"></h1>

然后下面的段落中,在公司名旁边使用标志,所以没有替代文本:

<article>
 <h2>News</h2>
 <p>We have recently been looking at buying the <img src="alpha.gif"
 alt=""> ΑΒΓ company, a small Greek company
 specializing in our type of product.</p>

在这第三个代码片段中,在边栏中有一个标志,作为一个大的讨论并购的文章的一部分:

 <aside><p><img src="alpha-large.gif" alt=""></p></aside>
 <p>The ΑΒΓ company has had a good quarter, and our
 pie chart studies of their accounts suggest a much bigger blue slice
 than its green and orange slices, which is always a good sign.</p>
</article>

最后,我们有一个意见部分谈论一个标志,因此在替代文本中细致地描述了这个标志。

<p>Consider for a moment their logo:</p>

<p><img src="/images/logo" alt="It consists of a green circle with a
green question mark centered inside it."></p>

<p>How unoriginal can you get? I mean, oooooh, a question mark, how
<em>revolutionary</em>, how utterly <em>ground-breaking</em>, I'm
sure everyone will rush to adopt those specifications now! They could
at least have tried for some sort of, I don't know, sequence of
rounded squares with varying shades of green and bold white outlines,
at least that would look good on the cover of a blue book.</p>

图片 不可用 时就会使用文本。 这个例子展示了替代文本应该怎样写,使得这些文本可以无缝地嵌入周围的文本, 就像那里从来没有图片一样。

4.8.4.4.5 Text that has been rendered to a graphic for typographical effect

Sometimes, an image just consists of text, and the purpose of the image is not to highlight the actual typographic effects used to render the text, but just to convey the text itself.

In such cases, the alt attribute must be present but must consist of the same text as written in the image itself.

Consider a graphic containing the text "Earth Day", but with the letters all decorated with flowers and plants. If the text is merely being used as a heading, to spice up the page for graphical users, then the correct alternative text is just the same text "Earth Day", and no mention need be made of the decorations:

<h1><img src="earthdayheading.png" alt="Earth Day"></h1>

An illuminated manuscript might use graphics for some of its images. The alternative text in such a situation is just the character that the image represents.

<p><img src="initials/o.svg" alt="O">nce upon a time and a long long time ago, late at
night, when it was dark, over the hills, through the woods, across a great ocean, in a land far
away, in a small house, on a hill, under a full moon...

When an image is used to represent a character that cannot otherwise be represented in Unicode, for example gaiji, itaiji, or new characters such as novel currency symbols, the alternative text should be a more conventional way of writing the same thing, e.g. using the phonetic hiragana or katakana to give the character's pronunciation.

In this example from 1997, a new-fangled currency symbol that looks like a curly E with two bars in the middle instead of one is represented using an image. The alternative text gives the character's pronunciation.

<p>Only <img src="euro.png" alt="euro ">5.99!

An image should not be used if characters would serve an identical purpose. Only when the text cannot be directly represented using text, e.g., because of decorations or because there is no appropriate character (as in the case of gaiji), would an image be appropriate.

If an author is tempted to use an image because their default system font does not support a given character, then web Fonts are a better solution than images.

4.8.4.4.6 A graphical representation of some of the surrounding text

In many cases, the image is actually just supplementary, and its presence merely reinforces the surrounding text. In these cases, the alt attribute must be present but its value must be the empty string.

In general, an image falls into this category if removing the image doesn't make the page any less useful, but including the image makes it a lot easier for users of visual browsers to understand the concept.

A flowchart that repeats the previous paragraph in graphical form:

<p>The Network passes data to the Input Stream Preprocessor, which
passes it to the Tokenizer, which passes it to the Tree Construction
stage. From there, data goes to both the DOM and to Script Execution.
Script Execution is linked to the DOM, and, using document.write(),
passes data to the Tokenizer.</p>
<p><img src="images/parsing-model-overview.svg" alt=""></p>

In these cases, it would be wrong to include alternative text that consists of just a caption. If a caption is to be included, then either the title attribute can be used, or the figure and figcaption elements can be used. In the latter case, the image would in fact be a phrase or paragraph with an alternative graphical representation, and would thus require alternative text.

<!-- Using the title="" attribute -->
<p>The Network passes data to the Input Stream Preprocessor, which
passes it to the Tokenizer, which passes it to the Tree Construction
stage. From there, data goes to both the DOM and to Script Execution.
Script Execution is linked to the DOM, and, using document.write(),
passes data to the Tokenizer.</p>
<p><img src="images/parsing-model-overview.svg" alt=""
        title="Flowchart representation of the parsing model."></p>
<!-- Using <figure> and <figcaption> -->
<p>The Network passes data to the Input Stream Preprocessor, which
passes it to the Tokenizer, which passes it to the Tree Construction
stage. From there, data goes to both the DOM and to Script Execution.
Script Execution is linked to the DOM, and, using document.write(),
passes data to the Tokenizer.</p>
<figure>
 <img src="images/parsing-model-overview.svg" alt="The Network leads to
 the Input Stream Preprocessor, which leads to the Tokenizer, which
 leads to the Tree Construction stage. The Tree Construction stage
 leads to two items. The first is Script Execution, which leads via
 document.write() back to the Tokenizer. The second item from which
 Tree Construction leads is the DOM. The DOM is related to the Script
 Execution.">
 <figcaption>Flowchart representation of the parsing model.</figcaption>
</figure>
<!-- This is WRONG. Do not do this. Instead, do what the above examples do. -->
<p>The Network passes data to the Input Stream Preprocessor, which
passes it to the Tokenizer, which passes it to the Tree Construction
stage. From there, data goes to both the DOM and to Script Execution.
Script Execution is linked to the DOM, and, using document.write(),
passes data to the Tokenizer.</p>
<p><img src="images/parsing-model-overview.svg"
        alt="Flowchart representation of the parsing model."></p>
<!-- Never put the image's caption in the alt="" attribute! -->

A graph that repeats the previous paragraph in graphical form:

<p>According to a study covering several billion pages,
about 62% of documents on the web in 2007 triggered the Quirks
rendering mode of web browsers, about 30% triggered the Almost
Standards mode, and about 9% triggered the Standards mode.</p>
<p><img src="rendering-mode-pie-chart.png" alt=""></p>
4.8.4.4.7 辅助性图片

有些图片对内容不那么重要,可能是纯粹装饰性图片,也可能与文本完全冗余。 这些情况下,alt 属性也必须存在,它的值应该是空字符串, 或者是一个图片传达的信息的文本表示。如果图片的标题部分给出了图片标题,那么 alt 属性值不得为空(因为那可能会让非视觉媒体的读者感到困惑)。

考虑一篇关于政治人物的新文章,其中的图片显示了人物的面部,通过样式表浮动到右侧。 这张图片就不是纯装饰性的,因为它与故事相关。这张图片也不完全与故事冗余,因为它显示了政客的长相。 是否提供替代文本取决于作者,也部分取决于这张图片是否对文章起到润色的作用。

下面第一个例子中,图片没有上下文也没有替代文本:

<p><img src="alexsalmond.jpeg" alt=""> Ahead of today's referendum,
the First Minister of Scotland, Alex Salmond, wrote an open letter to all
registered voters. In it, he admitted that all countries make mistakes.</p>

如果图片只是一张脸,可能没有必要描述它。 读者完全不关心他的头发是红色还是棕色,白皮肤或黑皮肤,有一个眼睛还是两个眼睛。

但是如果图片更加动态,比如显示了政客很生气,或者非常开心,或者很颓废, 可能就应该加一些替代文本来给文章一个基调。如果没有替代文本可能这个基调就会被读者遗漏。

<p><img src="alexsalmond.jpeg" alt="Alex Salmond is sad.">
Ahead of today's referendum, the First Minister of Scotland, Alex Salmond,
wrote an open letter to all registered voters. In it, he admitted that all
countries make mistakes.</p>
<p><img src="alexsalmond.jpeg" alt="Alex Salmond is ecstatic!">
Ahead of today's referendum, the First Minister of Scotland, Alex Salmond,
wrote an open letter to all registered voters. In it, he admitted that all
countries make mistakes.</p>

任务是 "伤心" 还是 "高兴" 会影响后续段落的解读: 他可能是说由于即将举行的公民投票会对他不利而向民众辞职, 也可能是说这次选举出了一些问题,但是接下来的投票率可能使它变得无关紧要。 解读因图片内容而异。

如果该图片有标题部分,那么包含一段替代文本可以避免让非视觉媒体的用户困惑标题指代的内容。

<p>Ahead of today's referendum, the First Minister of Scotland, Alex Salmond,
wrote an open letter to all registered voters. In it, he admitted that all
countries make mistakes.</p>
<figure>
 <img src="alexsalmond.jpeg"
      alt="A high forehead, cheerful disposition, and dark hair round out Alex Salmond's face.">
 <figcaption> Alex Salmond, SNP. Photo © 2014 PolitiPhoto. </figcaption>
</figure>
4.8.4.4.8 不提供任何信息的纯装饰性图片

如果图片是装饰性的而且不是页面特定的 — 比如这个图片作为站点设计的一部分。 — 那么这个图片应该通过站点 CSS 来指定,而不是写在文档标记中。

但是如果一张图片没有在周围的文字中加以讨论,但仍然有些关联,也可以使用 img 元素把它包含在页面中。这样的图片的 alt 属性必须存在而且值必须是空字符串。

有些关联的纯装饰性图片的例子比如,一篇介绍在 Burning Man 发生的事件的博文会引入一张 Black Rock City 景色的照片,或者在显示诗歌的页面上引入一张受这首诗启发的绘画作品。 下面的代码片段是第二种情况的例子(代码中只引入了诗歌的第一小节):

<h1>The Lady of Shalott</h1>
<p><img src="shalott.jpeg" alt=""></p>
<p>On either side the river lie<br>
Long fields of barley and of rye,<br>
That clothe the wold and meet the sky;<br>
And through the field the road run by<br>
To many-tower'd Camelot;<br>
And up and down the people go,<br>
Gazing where the lilies blow<br>
Round an island there below,<br>
The island of Shalott.</p>

当一张图片被切分为若干个小图片文件,用来拼装成原来的大图时,这些图片中要有一个的 alt 属性按照相关规则设置为大图的替代文本。 然后其他所有剩余图片必须把 alt 属性设为空字符串。

下面的例子中,表示 XYZ Corp 公司 Logo 的图片被分为两部分, 第一个包含字母 "XYZ" 第二个包含单词 "Corp"。 都包含在了第一个图片的替代文本("XYZ Corp")中。

<h1><img src="logo1.png" alt="XYZ Corp"><img src="logo2.png" alt=""></h1>

下面的例子中,评分显示为三颗星星和两颗空星。 虽然替代文本可以是 "★★★☆☆",但作者决定提供更有帮助的评分格式比如 "3 / 5"。它设置为第一个图片的替代文本。其他图片的替代文本为空。

<p>Rating: <meter max=5 value=3><img src="1" alt="3 out of 5"
  ><img src="1" alt=""><img src="1" alt=""><img src="0" alt=""
  ><img src="0" alt=""></meter></p>

通常带连接的图片应该使用 图片映射 而不是切分图片。

但是,如果图片确实已经被切分了,而且切分后的部分是链接的唯一内容, 那么每个链接必须有一个图片必须把它的 alt 属性设置为表示链接用途的替代文本。

下面的例子是一张表示飞行面条怪物徽章的图片,左右两侧的面条状物是单独的两张图片, 这样用户就可以在探险中选择左右两侧的图片了。

<h1>The Church</h1>
<p>You come across a flying spaghetti monster. Which side of His
Noodliness do you wish to reach out for?</p>
<p><a href="?go=left" ><img src="fsm-left.png"  alt="Left side. "></a
  ><img src="fsm-middle.png" alt=""
  ><a href="?go=right"><img src="fsm-right.png" alt="Right side."></a></p>
4.8.4.4.11 内容的关键部分

有些情况下,图片是内容的关键部分。比如照片库页面中的图片就是这样的情况。 这时图片就是包含它的页面的重点。

如何为内容关键的图片提供替代文本取决于图片的出处。

通常情况

如果可以提供详细的替代文本,如果图像是杂志评论中的一系列截图的一部分,或者是连环漫画的一部分, 或者是关于该照片的博客文章中的那个照片,则必须通过 alt 属性给出替代图片的文字。

新操作系统的屏幕截图,其中包含一些替代文字:

<figure>
 <img src="KDE%20Light%20desktop.png"
      alt="The desktop is blue, with icons along the left hand side in
           two columns, reading System, Home, K-Mail, etc. A window is
           open showing that menus wrap to a second line if they
           cannot fit in the window. The window has a list of icons
           along the top, with an address bar below it, a list of
           icons for tabs along the left edge, a status bar on the
           bottom, and two panes in the middle. The desktop has a bar
           at the bottom of the screen with a few buttons, a pager, a
           list of open applications, and a clock.">
 <figcaption>Screenshot of a KDE desktop.</figcaption>
</figure>

财务报告中的图表:

<img src="sales.gif"
     title="Sales graph"
     alt="From 1998 to 2005, sales increased by the following percentages
     with each year: 624%, 75%, 138%, 40%, 35%, 9%, 21%">

请注意,“销售图”对于销售图而言是不充分的替代文本。 做 标题 很好的文本通常不适合做替代文本。

难以提供完整描述的图片

有些情况下图片的特性决定了提供完整的替代文本不现实。 例如,图像可能模糊不清,或者可能是复杂的分形,或者可能是详细的地形图。

这些情况下 alt 属性也必须包含一些适当的替代文本, 但可以比较简短。

有时候根本无法用文字对图片做出正确的描述。例如对罗夏墨迹测验就无法提供有用的描述。 但是,即使是一个简单的描述也比什么都没有要好:

<figure>
 <img src="/commons/a/a7/Rorschach1.jpg" alt="A shape with left-right
 symmetry with indistinct edges, with a small gap in the center, two
 larger gaps offset slightly from the center, with two similar gaps
 under them. The outline is wider in the top half than the bottom
 half, with the sides extending upwards higher than the center, and
 the center extending below the sides.">
 <figcaption>A black outline of the first of the ten cards
 in the Rorschach inkblot test.</figcaption>
</figure>

注意下面是一个替代文本的非常糟糕的使用方式:

<!-- This example is wrong. Do not copy it. -->
<figure>
 <img src="/commons/a/a7/Rorschach1.jpg" alt="A black outline
 of the first of the ten cards in the Rorschach inkblot test.">
 <figcaption>A black outline of the first of the ten cards
 in the Rorschach inkblot test.</figcaption>
</figure>

这样把标题放到替代文字中根本没用,因为对于没有图片的用户它只是重复了标题, 相比于只读到或听到一次标题,再来重复一次根本不会有任何帮助。

无法描述的图片的另一个例子是分型,根据定义它的细节是无限的。

下面的例子展示了为曼德博集合提供替代文字的一种可能的方式。

<img src="ms1.jpeg" alt="The Mandelbrot set appears as a cardioid with
its cusp on the real axis in the positive direction, with a smaller
bulb aligned along the same center line, touching it in the negative
direction, and with these two shapes being surrounded by smaller bulbs
of various sizes.">

类似地,在生物学中人脸的照片也是内容的关键部分,也很难完全用文字替代:

<section class="bio">
 <h1>A Biography of Isaac Asimov</h1>
 <p>Born <b>Isaak Yudovich Ozimov</b> in 1920, Isaac was a prolific author.</p>
 <p><img src="headpics/asimov.jpeg" alt="Isaac Asimov had dark hair, a tall forehead, and wore glasses.
 Later in life, he wore long white sideburns.">
 <p>Asimov was born in Russia, and moved to the US when he was three years old.</p>
 <p>...
</section>

在这样的情况下,在替代文本中引述图片本身是不必要的(并且实际上不鼓励), 因为这样的文本与浏览器自身的图片报告是冗余的。 例如,如果替代文本是“Isaac Asimov的照片”,那么标准的用户代理可能将其读作 “(Image)Isaac Asimov 的照片” 而不是(更有用) “(Image)Isaac Asimov 是黑发 ,额头很高,戴着眼镜......”。

未知内容的图片

有些情况比较不幸,根本没有替代文字。可能是因为图片是动态获取的且没有关联的替代文本 (比如 Web 摄像头),也可能因为页面是由用户提供的图片通过脚本生成的, 而用户并没有提供合适的可用替代文本(例如照片分享站点), 也可能是因为作者自己不知道图片表示着什么(比如一个盲人摄影师在博客上分享了一张图片)。

这种情况下,alt 属性可以忽略,但必须符合以下条件之一:

这种情况应该保持在最低限度。只要作者有能力提供真正的替代文本, 那么忽略 alt 属性就是不可接受的。

如果一个照片分享网站收到图片时除了标题没有其他任何元数据, 这个照片可以这样标记:

<figure>
 <img src="1100670787_6a7c664aef.jpg">
 <figcaption>Bubbles traveled everywhere with us.</figcaption>
</figure>

当然如果能详细描述图片的重要部分,并通过替代文本提供出来会更好。

一个盲人的博客中,显示了一张用户拍的照片。刚开始用户可能不知道他们拍的照片上有什么:

<article>
 <h1>I took a photo</h1>
 <p>I went out today and took a photo!</p>
 <figure>
  <img src="photo2.jpeg">
  <figcaption>A photograph taken blindly from my front porch.</figcaption>
 </figure>
</article>

最后如果用户从他们的朋友那里得到了图片的描述,他们就可以包含一些替代文本:

<article>
 <h1>I took a photo</h1>
 <p>I went out today and took a photo!</p>
 <figure>
  <img src="photo2.jpeg" alt="The photograph shows my squirrel
  feeder hanging from the edge of my roof. It is half full, but there
  are no squirrels around. In the background, out-of-focus trees fill the
  shot. The feeder is made of wood with a metal grate, and it contains
  peanuts. The edge of the roof is wooden too, and is painted white
  with light blue streaks.">
  <figcaption>A photograph taken blindly from my front porch.</figcaption>
 </figure>
</article>

有时图片的整个意义就是没有文本描述,要用户为它提供描述。 例如,CAPTCHA 图片的目的就是看用户能否从用文字描述图形。 下面是标记 CAPTCHA 的一种方式(注意 title 属性):

<p><label>What does this image say?
<img src="captcha.cgi?id=8934" title="CAPTCHA">
<input type=text name=captcha></label>
(If you cannot see the image, you can use an <a
href="?audio">audio</a> test instead.)</p>

另一个例子是显示图片并询问替代文本的软件,这些文本之后会被写入到页面中。 这样的页面可能会有一个图片表格,像这样:

<table>
 <thead>
  <tr> <th> Image <th> Description
 <tbody>
  <tr>
   <td> <img src="2421.png" title="Image 640 by 100, filename 'banner.gif'">
   <td> <input name="alt2421">
  <tr>
   <td> <img src="2422.png" title="Image 200 by 480, filename 'ad3.gif'">
   <td> <input name="alt2422">
</table>

注意即使在这个例子中,在 title 属性中还是提供了尽可能多的有用信息。

因为有些用户根本不能使用照片 (比如因为他们的网络很慢,或因为他们在使用文本浏览器,或者因为他们正在听汽车的语音 Web 浏览器阅读页面内容,或者只是因为他们是盲人), 只在没有可用的替代文本而且没人可以提供时,才允许忽略 alt 属性。 作者没有付出努力不是一个可以接受的理由。

4.8.4.4.12 不是给用户看的图片

通常作者应该避免使用不用来显示的 img 元素。

如果一个 img 元素不是用于显示的,比如用于计算页面浏览量的服务。 那么 alt 属性必须为空字符串。

在这些场景下,widthheight 属性必须设为 0。

4.8.4.4.13 An image in an email or private document intended for a specific person who is known to be able to view images

This section does not apply to documents that are publicly accessible, or whose target audience is not necessarily personally known to the author, such as documents on a web site, emails sent to public mailing lists, or software documentation.

When an image is included in a private communication (such as an HTML email) aimed at a specific person who is known to be able to view images, the alt attribute may be omitted. However, even in such cases authors are strongly urged to include alternative text (as appropriate according to the kind of image involved, as described in the above entries), so that the email is still usable should the user use a mail client that does not support images, or should the document be forwarded on to other users whose abilities might not include easily seeing images.

4.8.4.4.14 Guidance for markup generators

Markup generators (such as WYSIWYG authoring tools) should, wherever possible, obtain alternative text from their users. However, it is recognized that in many cases, this will not be possible.

For images that are the sole contents of links, markup generators should examine the link target to determine the title of the target, or the URL of the target, and use information obtained in this manner as the alternative text.

For images that have captions, markup generators should use the figure and figcaption elements, or the title attribute, to provide the image's caption.

As a last resort, implementers should either set the alt attribute to the empty string, under the assumption that the image is a purely decorative image that doesn't add any information but is still specific to the surrounding content, or omit the alt attribute altogether, under the assumption that the image is a key part of the content.

Markup generators may specify a generator-unable-to-provide-required-alt attribute on img elements for which they have been unable to obtain alternative text and for which they have therefore omitted the alt attribute. The value of this attribute must be the empty string. Documents containing such attributes are not conforming, but conformance checkers will silently ignore this error.

This is intended to avoid markup generators from being pressured into replacing the error of omitting the alt attribute with the even more egregious error of providing phony alternative text, because state-of-the-art automated conformance checkers cannot distinguish phony alternative text from correct alternative text.

Markup generators should generally avoid using the image's own file name as the alternative text. Similarly, markup generators should avoid generating alternative text from any content that will be equally available to presentation user agents (e.g., web browsers).

This is because once a page is generated, it will typically not be updated, whereas the browsers that later read the page can be updated by the user, therefore the browser is likely to have more up-to-date and finely-tuned heuristics than the markup generator did when generating the page.

4.8.4.4.15 规范检查工具指引

规范检查工具必须把缺少 alt 属性报告为错误, 符合以下条件之一的情形除外:

4.8.5 The iframe element

Element/iframe

Support in all current engines.

FirefoxYesSafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLIFrameElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Phrasing content.
Embedded content.
Interactive content.
Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
Nothing.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
src — Address of the resource
srcdoc — A document to render in the iframe
name — Name of nested browsing context
sandbox — Security rules for nested content
allowPermissions policy to be applied to the iframe's contents
allowfullscreen — Whether to allow the iframe's contents to use requestFullscreen()
width — Horizontal dimension
height — Vertical dimension
referrerpolicyReferrer policy for fetches initiated by the element
loading — Used when determining loading deferral
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLIFrameElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString srcdoc;
  [CEReactions] attribute DOMString name;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList sandbox;
  [CEReactions] attribute DOMString allow;
  [CEReactions] attribute boolean allowFullscreen;
  [CEReactions] attribute DOMString width;
  [CEReactions] attribute DOMString height;
  [CEReactions] attribute DOMString referrerPolicy;
  [CEReactions] attribute DOMString loading;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;
  Document? getSVGDocument();

  // also has obsolete members
};

The iframe element represents its nested browsing context.

The src attribute gives the URL of a page that the element's nested browsing context is to contain. The attribute, if present, must be a valid non-empty URL potentially surrounded by spaces. If the itemprop attribute is specified on an iframe element, then the src attribute must also be specified.

Element/iframe#attr-srcdoc

Support in all current engines.

Firefox25+Safari6+Chrome20+
Opera15+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android25+Safari iOS?Chrome Android25+WebView Android37+Samsung Internet1.5+Opera Android?

The srcdoc attribute gives the content of the page that the element's nested browsing context is to contain. The value of the attribute is the source of an iframe srcdoc document.

The srcdoc attribute, if present, must have a value using the HTML syntax that consists of the following syntactic components, in the given order:

  1. Any number of comments and ASCII whitespace.
  2. Optionally, a DOCTYPE.
  3. Any number of comments and ASCII whitespace.
  4. The document element, in the form of an html element.
  5. Any number of comments and ASCII whitespace.

The above requirements apply in XML documents as well.

Here a blog uses the srcdoc attribute in conjunction with the sandbox attribute described below to provide users of user agents that support this feature with an extra layer of protection from script injection in the blog post comments:

<article>
 <h1>I got my own magazine!</h1>
 <p>After much effort, I've finally found a publisher, and so now I
 have my own magazine! Isn't that awesome?! The first issue will come
 out in September, and we have articles about getting food, and about
 getting in boxes, it's going to be great!</p>
 <footer>
  <p>Written by <a href="/users/cap">cap</a>, 1 hour ago.
 </footer>
 <article>
  <footer> Thirteen minutes ago, <a href="/users/ch">ch</a> wrote: </footer>
  <iframe sandbox srcdoc="<p>did you get a cover picture yet?"></iframe>
 </article>
 <article>
  <footer> Nine minutes ago, <a href="/users/cap">cap</a> wrote: </footer>
  <iframe sandbox srcdoc="<p>Yeah, you can see it <a href=&quot;/gallery?mode=cover&amp;amp;page=1&quot;>in my gallery</a>."></iframe>
 </article>
 <article>
  <footer> Five minutes ago, <a href="/users/ch">ch</a> wrote: </footer>
  <iframe sandbox srcdoc="<p>hey that's earl's table.
<p>you should get earl&amp;amp;me on the next cover."></iframe>
 </article>

Notice the way that quotes have to be escaped (otherwise the srcdoc attribute would end prematurely), and the way raw ampersands (e.g. in URLs or in prose) mentioned in the sandboxed content have to be doubly escaped — once so that the ampersand is preserved when originally parsing the srcdoc attribute, and once more to prevent the ampersand from being misinterpreted when parsing the sandboxed content.

Furthermore, notice that since the DOCTYPE is optional in iframe srcdoc documents, and the html, head, and body elements have optional start and end tags, and the title element is also optional in iframe srcdoc documents, the markup in a srcdoc attribute can be relatively succinct despite representing an entire document, since only the contents of the body element need appear literally in the syntax. The other elements are still present, but only by implication.

In the HTML syntax, authors need only remember to use U+0022 QUOTATION MARK characters (") to wrap the attribute contents and then to escape all U+0026 AMPERSAND (&) and U+0022 QUOTATION MARK (") characters, and to specify the sandbox attribute, to ensure safe embedding of content. (And remember to escape ampersands before quotation marks, to ensure quotation marks become &quot; and not &amp;quot;.)

In XML the U+003C LESS-THAN SIGN character (<) needs to be escaped as well. In order to prevent attribute-value normalization, some of XML's whitespace characters — specifically U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), and U+000D CARRIAGE RETURN (CR) — also need to be escaped. [XML]

If the src attribute and the srcdoc attribute are both specified together, the srcdoc attribute takes priority. This allows authors to provide a fallback URL for legacy user agents that do not support the srcdoc attribute.


When an iframe element element is inserted into a document whose browsing context is non-null, the user agent must run these steps:

  1. Create a new nested browsing context for element.

  2. Process the iframe attributes for element, with initialInsertion set to true.

When an iframe element is removed from a document, the user agent must discard the element's nested browsing context, if it is not null, and then set the element's nested browsing context to null.

This happens without any unload events firing (the element's nested browsing context and its Document are discarded, not unloaded).

Whenever an iframe element with a non-null nested browsing context has its srcdoc attribute set, changed, or removed, the user agent must process the iframe attributes.

Similarly, whenever an iframe element with a non-null nested browsing context but with no srcdoc attribute specified has its src attribute set, changed, or removed, the user agent must process the iframe attributes.

To process the iframe attributes for an element element, with an optional boolean initialInsertion (default false):

  1. If element's srcdoc attribute is specified, then:

    1. Set element's current navigation was lazy loaded boolean to false.

    2. If the will lazy load element steps given element return true, then:

      1. Set element's lazy load resumption steps to the rest of this algorithm starting with the step labeled navigate to the srcdoc resource.

      2. Set element's current navigation was lazy loaded boolean to true.

      3. Start intersection-observing a lazy loading element for element.

      4. Return.

    3. Navigate to the srcdoc resource: navigate an iframe or frame given element and a new response whose url list consists of about:srcdoc, header list consists of `Content-Type`/`text/html`, body is the value of element's srcdoc attribute, and CSP list is a clone of element's node document's CSP list.

      The resulting Document must be considered an iframe srcdoc document.

  2. Otherwise, if initialInsertion is false, run the otherwise steps for iframe or frame elements given element.

The otherwise steps for iframe or frame elements, given an element element, are:

  1. If element has no src attribute specified, or its value is the empty string, let url be the URL "about:blank".

    Otherwise, parse the value of element's src attribute, relative to element's node document.

    If that is not successful, then let url be the URL "about:blank". Otherwise, let url be the resulting URL record.

  2. If there exists an ancestor browsing context of element's nested browsing context whose active document's URL, ignoring fragments, is equal to url, then return.

  3. Let resource be a new request whose url is url and whose referrer policy is the current state of element's referrerpolicy content attribute.

  4. If element is an iframe element, then set element's current navigation was lazy loaded boolean to false.

  5. If element is an iframe element, and the will lazy load element steps given element return true, then:

    1. Set element's lazy load resumption steps to the rest of this algorithm starting with the step labeled navigate to the resource.

    2. Set element's current navigation was lazy loaded boolean to true.

    3. Start intersection-observing a lazy loading element for element.

    4. Return.

  6. Navigate to the resource: navigate an iframe or frame given element and resource.

To navigate an iframe or frame given an element element and a resource resource:

  1. Let historyHandling be "default".

  2. If element's nested browsing context's session history contains only one Document, and that was the about:blank Document created when element's nested browsing context was created, then set historyHandling to "replace".

  3. If element's nested browsing context's active document is not completely loaded, then set historyHandling to "replace".

  4. Navigate element's nested browsing context to resource, with historyHandling set to historyHandling and the source browsing context set to element's node document's browsing context.

A load event is also fired at the iframe element when it is created if no other data is loaded in it.

Each Document has an iframe load in progress flag and a mute iframe load flag. When a Document is created, these flags must be unset for that Document.

To run the iframe load event steps, given an iframe element element:

  1. Assert: element's nested browsing context is not null.

  2. Let childDocument be the active document of element's nested browsing context.

  3. If childDocument has its mute iframe load flag set, then return.

  4. Set childDocument's iframe load in progress flag.

  5. Fire an event named load at element.

  6. Unset childDocument's iframe load in progress flag.

This, in conjunction with scripting, can be used to probe the URL space of the local network's HTTP servers. User agents may implement cross-origin access control policies that are stricter than those described above to mitigate this attack, but unfortunately such policies are typically not compatible with existing web content.

If an element type potentially delays the load event, then for each element element of that type, the user agent must delay the load event of element's node document if element's nested browsing context is non-null and any of the following are true:

If, during the handling of the load event, element's nested browsing context is again navigated, that will further delay the load event.

Each iframe element has an associated current navigation was lazy loaded boolean, initially false. It is set and unset in the process the iframe attributes algorithm.

An iframe element whose current navigation was lazy loaded boolean is false potentially delays the load event.

If, when the element is created, the srcdoc attribute is not set, and the src attribute is either also not set or set but its value cannot be parsed, the browsing context will remain at the initial about:blank page.

If the user navigates away from this page, the iframe's nested browsing context's WindowProxy object will proxy new Window objects for new Document objects, but the src attribute will not change.


The name attribute, if present, must be a valid browsing context name. The given value is used to name the element's nested browsing context if present when that is created.


Element/iframe#attr-sandbox

Support in all current engines.

Firefox17+Safari5+Chrome4+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android17+Safari iOS4.2+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android?

The sandbox attribute, when specified, enables a set of extra restrictions on any content hosted by the iframe. Its value must be an unordered set of unique space-separated tokens that are ASCII case-insensitive. The allowed values are allow-forms, allow-modals, allow-orientation-lock, allow-pointer-lock, allow-popups, allow-popups-to-escape-sandbox, allow-presentation, allow-same-origin, allow-scripts, allow-top-navigation, allow-top-navigation-by-user-activation, and allow-downloads.

When the attribute is set, the content is treated as being from a unique origin, forms, scripts, and various potentially annoying APIs are disabled, links are prevented from targeting other browsing contexts, and plugins are secured. The allow-same-origin keyword causes the content to be treated as being from its real origin instead of forcing it into a unique origin; the allow-top-navigation keyword allows the content to navigate its top-level browsing context; the allow-top-navigation-by-user-activation keyword behaves similarly but allows such navigation only when the browsing context's active window has transient activation; and the allow-forms, allow-modals, allow-orientation-lock, allow-pointer-lock, allow-popups, allow-presentation, allow-scripts, and allow-popups-to-escape-sandbox keywords re-enable forms, modal dialogs, screen orientation lock, the pointer lock API, popups, the presentation API, scripts, and the creation of unsandboxed auxiliary browsing contexts respectively. [POINTERLOCK] [SCREENORIENTATION] [PRESENTATION]

The allow-top-navigation and allow-top-navigation-by-user-activation keywords must not both be specified, as doing so is redundant; only allow-top-navigation will have an effect in such non-conformant markup.

Setting both the allow-scripts and allow-same-origin keywords together when the embedded page has the same origin as the page containing the iframe allows the embedded page to simply remove the sandbox attribute and then reload itself, effectively breaking out of the sandbox altogether.

These flags only take effect when the nested browsing context of the iframe element is navigated. Removing them, or removing the entire sandbox attribute, has no effect on an already-loaded page.

Potentially hostile files should not be served from the same server as the file containing the iframe element. Sandboxing hostile content is of minimal help if an attacker can convince the user to just visit the hostile content directly, rather than in the iframe. To limit the damage that can be caused by hostile HTML content, it should be served from a separate dedicated domain. Using a different domain ensures that scripts in the files are unable to attack the site, even if the user is tricked into visiting those pages directly, without the protection of the sandbox attribute.

When an iframe element with a sandbox attribute has its nested browsing context created (before the initial about:blank Document is created), and when an iframe element's sandbox attribute is set or changed while it has a nested browsing context, the user agent must parse the sandboxing directive using the attribute's value as the input and the iframe element's iframe sandboxing flag set as the output.

When an iframe element's sandbox attribute is removed while it has a non-null nested browsing context, the user agent must empty the iframe element's iframe sandboxing flag set.

In this example, some completely-unknown, potentially hostile, user-provided HTML content is embedded in a page. Because it is served from a separate domain, it is affected by all the normal cross-site restrictions. In addition, the embedded page has scripting disabled, plugins disabled, forms disabled, and it cannot navigate any frames or windows other than itself (or any frames or windows it itself embeds).

<p>We're not scared of you! Here is your content, unedited:</p>
<iframe sandbox src="https://usercontent.example.net/getusercontent.cgi?id=12193"></iframe>

It is important to use a separate domain so that if the attacker convinces the user to visit that page directly, the page doesn't run in the context of the site's origin, which would make the user vulnerable to any attack found in the page.

In this example, a gadget from another site is embedded. The gadget has scripting and forms enabled, and the origin sandbox restrictions are lifted, allowing the gadget to communicate with its originating server. The sandbox is still useful, however, as it disables plugins and popups, thus reducing the risk of the user being exposed to malware and other annoyances.

<iframe sandbox="allow-same-origin allow-forms allow-scripts"
        src="https://maps.example.com/embedded.html"></iframe>

Suppose a file A contained the following fragment:

<iframe sandbox="allow-same-origin allow-forms" src=B></iframe>

Suppose that file B contained an iframe also:

<iframe sandbox="allow-scripts" src=C></iframe>

Further, suppose that file C contained a link:

<a href=D>Link</a>

For this example, suppose all the files were served as text/html.

Page C in this scenario has all the sandboxing flags set. Scripts are disabled, because the iframe in A has scripts disabled, and this overrides the allow-scripts keyword set on the iframe in B. Forms are also disabled, because the inner iframe (in B) does not have the allow-forms keyword set.

Suppose now that a script in A removes all the sandbox attributes in A and B. This would change nothing immediately. If the user clicked the link in C, loading page D into the iframe in B, page D would now act as if the iframe in B had the allow-same-origin and allow-forms keywords set, because that was the state of the nested browsing context in the iframe in A when page B was loaded.

Generally speaking, dynamically removing or changing the sandbox attribute is ill-advised, because it can make it quite hard to reason about what will be allowed and what will not.


The allow attribute, when specified, determines the container policy that will be used when the permissions policy for a Document in the iframe's nested browsing context is initialized. Its value must be a serialized permissions policy. [PERMISSIONSPOLICY]

In this example, an iframe is used to embed a map from an online navigation service. The allow attribute is used to enable the Geolocation API within the nested context.

<iframe src="https://maps.example.com/" allow="geolocation"></iframe>

The allowfullscreen attribute is a boolean attribute. When specified, it indicates that Document objects in the iframe element's nested browsing context will be initialized with a permissions policy which allows the "fullscreen" feature to be used from any origin. This is enforced by the process permissions policy attributes algorithm. [PERMISSIONSPOLICY]

Here, an iframe is used to embed a player from a video site. The allowfullscreen attribute is needed to enable the player to show its video fullscreen.

<article>
 <header>
  <p><img src="/usericons/1627591962735"> <b>Fred Flintstone</b></p>
  <p><a href="/posts/3095182851" rel=bookmark>12:44</a> — <a href="#acl-3095182851">Private Post</a></p>
 </header>
 <p>Check out my new ride!</p>
 <iframe src="https://video.example.com/embed?id=92469812" allowfullscreen></iframe>
</article>

Neither allow nor allowfullscreen can grant access to a feature in an iframe element's nested browsing context if the element's node document is not already allowed to use that feature.

To determine whether a Document object document is allowed to use the policy-controlled-feature feature, run these steps:

  1. If document's browsing context is null, then return false.

  2. If document's browsing context's active document is not document, then return false.

  3. If the result of running is feature enabled in document for origin on feature, document, and document's origin is "Enabled", then return true.

  4. Return false.

Because they only influence the permissions policy of the nested browsing context's active document, the allow and allowfullscreen attributes only take effect when the nested browsing context of the iframe is navigated. Adding or removing them has no effect on an already-loaded document.


The iframe element supports dimension attributes for cases where the embedded content has specific dimensions (e.g. ad units have well-defined dimensions).

An iframe element never has fallback content, as it will always create a new nested browsing context, regardless of whether the specified initial contents are successfully used.


The referrerpolicy attribute is a referrer policy attribute. Its purpose is to set the referrer policy used when processing the iframe attributes. [REFERRERPOLICY]

The loading attribute is a lazy loading attribute. Its purpose is to indicate the policy for loading iframe elements that are outside the viewport.

When the loading attribute's state is changed to the Eager state, the user agent must run these steps:

  1. Let resumptionSteps be the iframe element's lazy load resumption steps.

  2. If resumptionSteps is null, then return.

  3. Set the iframe's lazy load resumption steps to null.

  4. Invoke resumptionSteps.


Descendants of iframe elements represent nothing. (In legacy user agents that do not support iframe elements, the contents would be parsed as markup that could act as fallback content.)

The HTML parser treats markup inside iframe elements as text.


HTMLIFrameElement/src

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLIFrameElement/srcdoc

Support in all current engines.

Firefox25+Safari6+Chrome20+
Opera15+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android25+Safari iOS6+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android14+

The IDL attributes src, srcdoc, name, sandbox, and allow must reflect the respective content attributes of the same name.

The supported tokens for sandbox's DOMTokenList are the allowed values defined in the sandbox attribute and supported by the user agent.

The allowFullscreen IDL attribute must reflect the allowfullscreen content attribute.

HTMLIFrameElement/referrerPolicy

Support in all current engines.

Firefox50+Safari14+Chrome53+
Opera38+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android50+Safari iOS14+Chrome Android53+WebView Android53+Samsung Internet6.0+Opera Android41+

The referrerPolicy IDL attribute must reflect the referrerpolicy content attribute, limited to only known values.

The loading IDL attribute must reflect the loading content attribute, limited to only known values.

HTMLIFrameElement/contentDocument

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The contentDocument IDL attribute, on getting, must return the iframe element's content document.

HTMLIFrameElement/contentWindow

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

The contentWindow IDL attribute must return the WindowProxy object of the iframe element's nested browsing context, if its nested browsing context is non-null, or null otherwise.

Here is an example of a page using an iframe to include advertising from an advertising broker:

<iframe src="https://ads.example.com/?customerid=923513721&amp;format=banner"
        width="468" height="60"></iframe>

4.8.6 The embed element

Element/embed

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLEmbedElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Phrasing content.
Embedded content.
Interactive content.
Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
Nothing.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
src — Address of the resource
type — Type of embedded resource
width — Horizontal dimension
height — Vertical dimension
Any other attribute that has no namespace (see prose).
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLEmbedElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute DOMString width;
  [CEReactions] attribute DOMString height;
  Document? getSVGDocument();

  // also has obsolete members
};

Depending on the type of content instantiated by the embed element, the node may also support other interfaces.

The embed element provides an integration point for an external (typically non-HTML) application or interactive content.

The src attribute gives the URL of the resource being embedded. The attribute, if present, must contain a valid non-empty URL potentially surrounded by spaces.

Authors should avoid referencing untrusted resources, as such a resource can be used to instantiate plugins or run scripts, even if the author has used features such as the Flash "allowScriptAccess" parameter.

If the itemprop attribute is specified on an embed element, then the src attribute must also be specified.

The type attribute, if present, gives the MIME type by which the plugin to instantiate is selected. The value must be a valid MIME type string. If both the type attribute and the src attribute are present, then the type attribute must specify the same type as the explicit Content-Type metadata of the resource given by the src attribute.

While any of the following conditions are occurring, any plugin instantiated for the element must be removed, and the embed element represents nothing:

An embed element is said to be potentially active when the following conditions are all met simultaneously:

Whenever an embed element that was not potentially active becomes potentially active, and whenever a potentially active embed element that is remaining potentially active and has its src attribute set, changed, or removed or its type attribute set, changed, or removed, the user agent must queue an element task on the embed task source given the element to run the embed element setup steps for that element.

The embed element setup steps for a given embed element element are as follows:

  1. If another task has since been queued to run the embed element setup steps for element, then return.

  2. If the Should plugin element be blocked a priori by Content Security Policy? algorithm returns "Blocked" when executed on element, then return. [CSP]

  3. If element has a src attribute set, then:

    1. Let url be the result of parsing the value of element's src attribute, relative to element's node document.

    2. If url is failure, then return.

    3. Let request be a new request whose url is url, client is element's node document's relevant settings object, destination is "embed", credentials mode is "include", mode is "navigate", and whose use-URL-credentials flag is set.

    4. Fetch request.

      Fetching the resource must delay the load event of element's node document.

      To process response for the response response:

      1. If another task has since been queued to run the embed element setup steps for element, then return.

      2. If response is a network error, then fire an event named load at element, and return.

      3. Let type be the result of determining the type of content given element and response.

      4. Switch on type:

        null
        1. Display no plugin for element.

        image/svg+xml
        1. If element's nested browsing context is null, then create a new nested browsing context for element.

        2. Navigate element's nested browsing context to response, with historyHandling set to "replace" and the source browsing context set to element's node document's browsing context.

          element's src attribute does not get updated if the browsing context gets further navigated to other locations.

        3. element now represents its nested browsing context.

        Otherwise
        1. Display a plugin for element, given type and response.

  4. Otherwise:

    1. Let type be the value of element's type attribute.

    2. If type is a type that a plugin supports, then display a plugin for element given type.

    3. Otherwise, display no plugin for element.

To determine the type of the content given an embed element element and a response response, run the following steps:

  1. If element has a type attribute, and that attribute's value is a type that a plugin supports, then return the value of the type attribute.

  2. If the path component of response's url matches a pattern that a plugin supports, then return the type that that plugin can handle.

    For example, a plugin might say that it can handle URLs with path components that end with the four character string ".swf".

  3. If response has explicit Content-Type metadata, and that value is a type that a plugin supports, then return that value.

  4. Return null.

It is intentional that the above algorithm allows response to have a non-ok status. This allows servers to return data for plugins even with error responses (e.g., HTTP 500 Internal Server Error codes can still contain plugin data).

To display a plugin for an embed element element, given a string type and optionally a response response:

  1. If element's nested browsing context is not null, then:

    1. Discard element's nested browsing context.

    2. Set element's nested browsing context to null.

  2. Find and instantiate an appropriate plugin based on type, replacing any previously-instantiated plugin for element. If response was given, forward it to the plugin.

  3. element now represents this plugin instance.

  4. Once the plugin, and response if given, are completely loaded, queue an element task on the DOM manipulation task source give element to fire an event named load at element.

To display no plugin for an embed element element:

  1. If element's nested browsing context is not null, then:

    1. Discard element's nested browsing context.

    2. Set element's nested browsing context to null.

  2. Display an indication that no plugin could be found for element, replacing any previously-instantiated plugin for element.

  3. element now represents nothing.

The embed element has no fallback content; its descendants are ignored.

Whenever an embed element that was potentially active stops being potentially active, any plugin that had been instantiated for that element must be unloaded.

When a plugin is to be instantiated but it cannot be secured and the sandboxed plugins browsing context flag is set on the embed element's node document's active sandboxing flag set, then the user agent must not instantiate the plugin, and must instead render the embed element in a manner that conveys that the plugin was disabled. The user agent may offer the user the option to override the sandbox and instantiate the plugin anyway; if the user invokes such an option, the user agent must act as if the conditions above did not apply for the purposes of this element.

Plugins that cannot be secured are disabled in sandboxed browsing contexts because they might not honor the restrictions imposed by the sandbox (e.g. they might allow scripting even when scripting in the sandbox is disabled). User agents should convey the danger of overriding the sandbox to the user if an option to do so is provided.

The embed element potentially delays the load event.

Any namespace-less attribute other than name, align, hspace, and vspace may be specified on the embed element, so long as its name is XML-compatible and contains no ASCII upper alphas. These attributes are then passed as parameters to the plugin.

All attributes in HTML documents get lowercased automatically, so the restriction on uppercase letters doesn't affect such documents.

The four exceptions are to exclude legacy attributes that have side-effects beyond just sending parameters to the plugin.

The user agent should pass the names and values of all the attributes of the embed element that have no namespace to the plugin used, when one is instantiated.

The HTMLEmbedElement object representing the element must expose the scriptable interface of the plugin instantiated for the embed element, if any.

The embed element supports dimension attributes.

The IDL attributes src and type each must reflect the respective content attributes of the same name.

Here's a way to embed a resource that requires a proprietary plugin, like Flash:

<embed src="catgame.swf">

If the user does not have the plugin (for example if the plugin vendor doesn't support the user's platform), then the user will be unable to use the resource.

To pass the plugin a parameter "quality" with the value "high", an attribute can be specified:

<embed src="catgame.swf" quality="high">

This would be equivalent to the following, when using an object element instead:

<object data="catgame.swf">
 <param name="quality" value="high">
</object>

4.8.7 The object element

Element/object

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLObjectElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Phrasing content.
Embedded content.
If the element has a usemap attribute: Interactive content.
Listed and submittable form-associated element.
Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
Zero or more param elements, then, transparent.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
data — Address of the resource
type — Type of embedded resource
name — Name of nested browsing context
usemap — Name of image map to use
form — Associates the element with a form element
width — Horizontal dimension
height — Vertical dimension
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLObjectElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString data;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString useMap;
  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute DOMString width;
  [CEReactions] attribute DOMString height;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;
  Document? getSVGDocument();

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity(DOMString error);

  // also has obsolete members
};

Depending on the type of content instantiated by the object element, the node also supports other interfaces.

The object element can represent an external resource, which, depending on the type of the resource, will either be treated as an image, as a child browsing context, or as an external resource to be processed by a plugin.

The data attribute, if present, specifies the URL of the resource. If present, the attribute must be a valid non-empty URL potentially surrounded by spaces.

Authors should avoid referencing untrusted resources, as such a resource can be used to instantiate plugins or run scripts, even if the author has used features such as the Flash "allowScriptAccess" parameter.

The type attribute, if present, specifies the type of the resource. If present, the attribute must be a valid MIME type string.

At least one of either the data attribute or the type attribute must be present.

If the itemprop attribute is specified on an object element, then the data attribute must also be specified.

The name attribute, if present, must be a valid browsing context name. The given value is used to name the element's nested browsing context, if applicable, and if present when the element's nested browsing context is created.

Whenever one of the following conditions occur:

...the user agent must queue an element task on the DOM manipulation task source given the object element to run the following steps to (re)determine what the object element represents. This task being queued or actively running must delay the load event of the element's node document.

  1. If the user has indicated a preference that this object element's fallback content be shown instead of the element's usual behavior, then jump to the step below labeled fallback.

    For example, a user could ask for the element's fallback content to be shown because that content uses a format that the user finds more accessible.

  2. If the element has an ancestor media element, or has an ancestor object element that is not showing its fallback content, or if the element is not in a document whose browsing context is non-null, or if the element's node document is not fully active, or if the element is still in the stack of open elements of an HTML parser or XML parser, or if the element is not being rendered, or if the Should plugin element be blocked a priori by Content Security Policy? algorithm returns "Blocked" when executed on the element, then jump to the step below labeled fallback. [CSP]

  3. If the classid attribute is present, and has a value that isn't the empty string, then: if the user agent can find a plugin suitable according to the value of the classid attribute, and either plugins aren't being sandboxed or that plugin can be secured, then that plugin should be used, and the value of the data attribute, if any, should be passed to the plugin. If no suitable plugin can be found, or if the plugin reports an error, jump to the step below labeled fallback.

  4. If the data attribute is present and its value is not the empty string, then:

    1. If the type attribute is present and its value is not a type that the user agent supports, and is not a type that the user agent can find a plugin for, then the user agent may jump to the step below labeled fallback without fetching the content to examine its real type.

    2. Parse the URL specified by the data attribute, relative to the element's node document.

    3. If that failed, fire an event named error at the element, then jump to the step below labeled fallback.

    4. Let request be a new request whose url is the resulting URL record, client is the element's node document's relevant settings object, destination is "object", credentials mode is "include", mode is "navigate", and whose use-URL-credentials flag is set.

    5. Fetch request.

      Fetching the resource must delay the load event of the element's node document until the task that is queued by the networking task source once the resource has been fetched (defined next) has been run.

      For the purposes of the application cache networking model, this fetch operation is not for a child browsing context (though it might end up being used for one after all, as defined below).

    6. If the resource is not yet available (e.g. because the resource was not available in the cache, so that loading the resource required making a request over the network), then jump to the step below labeled fallback. The task that is queued by the networking task source once the resource is available must restart this algorithm from this step. Resources can load incrementally; user agents may opt to consider a resource "available" whenever enough data has been obtained to begin processing the resource.

    7. If the load failed (e.g. there was an HTTP 404 error, there was a DNS error), fire an event named error at the element, then jump to the step below labeled fallback.

    8. Determine the resource type, as follows:

      1. Let the resource type be unknown.

      2. If the user agent is configured to strictly obey Content-Type headers for this resource, and the resource has associated Content-Type metadata, then let the resource type be the type specified in the resource's Content-Type metadata, and jump to the step below labeled handler.

        This can introduce a vulnerability, wherein a site is trying to embed a resource that uses a particular plugin, but the remote site overrides that and instead furnishes the user agent with a resource that triggers a different plugin with different security characteristics.

      3. If there is a type attribute present on the object element, and that attribute's value is not a type that the user agent supports, but it is a type that a plugin supports, then let the resource type be the type specified in that type attribute, and jump to the step below labeled handler.

      4. Run the appropriate set of steps from the following list:

        If the resource has associated Content-Type metadata
        1. Let binary be false.

        2. If the type specified in the resource's Content-Type metadata is "text/plain", and the result of applying the rules for distinguishing if a resource is text or binary to the resource is that the resource is not text/plain, then set binary to true.

        3. If the type specified in the resource's Content-Type metadata is "application/octet-stream", then set binary to true.

        4. If binary is false, then let the resource type be the type specified in the resource's Content-Type metadata, and jump to the step below labeled handler.

        5. If there is a type attribute present on the object element, and its value is not application/octet-stream, then run the following steps:

          1. If the attribute's value is a type that a plugin supports, or the attribute's value is a type that starts with "image/" that is not also an XML MIME type, then let the resource type be the type specified in that type attribute.

          2. Jump to the step below labeled handler.

        Otherwise, if the resource does not have associated Content-Type metadata
        1. If there is a type attribute present on the object element, then let the tentative type be the type specified in that type attribute.

          Otherwise, let tentative type be the computed type of the resource.

        2. If tentative type is not application/octet-stream, then let resource type be tentative type and jump to the step below labeled handler.

      5. If applying the URL parser algorithm to the URL of the specified resource (after any redirects) results in a URL record whose path component matches a pattern that a plugin supports, then let resource type be the type that that plugin can handle.

        For example, a plugin might say that it can handle resources with path components that end with the four character string ".swf".

      It is possible for this step to finish, or for one of the substeps above to jump straight to the next step, with resource type still being unknown. In both cases, the next step will trigger fallback.

    9. Handler: Handle the content as given by the first of the following cases that matches:

      If the resource type is not a type that the user agent supports, but it is a type that a plugin supports

      If the object element's nested browsing context is non-null, then it must be discarded and then set to null.

      If plugins are being sandboxed and the plugin that supports resource type cannot be secured, jump to the step below labeled fallback.

      Otherwise, the user agent should use the plugin that supports resource type and pass the content of the resource to that plugin. If the plugin reports an error, then jump to the step below labeled fallback.

      If the resource type is an XML MIME type, or if the resource type does not start with "image/"

      If the object element's nested browsing context is null, then create a new nested browsing context for the element.

      If the URL of the given resource is not about:blank, then navigate the element's nested browsing context to that resource, with historyHandling set to "replace" and the source browsing context set to the object element's node document's browsing context. (The data attribute of the object element doesn't get updated if the browsing context gets further navigated to other locations.)

      The object element represents its nested browsing context.

      In certain situations, e.g., if the resource was fetched from an application cache but it is an HTML file with a manifest attribute that points to a different application cache manifest, the navigation of the browsing context will be restarted so as to load the resource afresh from the network or a different application cache. Even if the resource is then found to have a different type, it is still used as part of a browsing context: only the navigate algorithm is restarted, not this object algorithm.

      If the resource type starts with "image/", and support for images has not been disabled

      If the object element's nested browsing context is non-null, then it must be discarded and then set to null.

      Apply the image sniffing rules to determine the type of the image.

      The object element represents the specified image.

      If the image cannot be rendered, e.g. because it is malformed or in an unsupported format, jump to the step below labeled fallback.

      Otherwise

      The given resource type is not supported. Jump to the step below labeled fallback.

      If the previous step ended with the resource type being unknown, this is the case that is triggered.

    10. The element's contents are not part of what the object element represents.

    11. If the object element does not represent its nested browsing context, then once the resource is completely loaded, queue an element task on the DOM manipulation task source given the object element to fire an event named load at the element.

      If the element does represent its nested browsing context, then an analogous task will be queued when the created Document is completely finished loading.

    12. Return.

  5. If the data attribute is absent but the type attribute is present, and the user agent can find a plugin suitable according to the value of the type attribute, and either plugins aren't being sandboxed or the plugin can be secured, then that plugin should be used. If these conditions cannot be met, or if the plugin reports an error, jump to the step below labeled fallback. Otherwise return; once the plugin is completely loaded, queue an element task on the DOM manipulation task source given the object element to fire an event named load at the element.

  6. Fallback: The object element represents the element's children, ignoring any leading param element children. This is the element's fallback content. If the element has an instantiated plugin, then unload it. If the element's nested browsing context is non-null, then it must be discarded and then set to null.

When the algorithm above instantiates a plugin, the user agent should pass to the plugin used the names and values of all the attributes on the element, in the order they were added to the element, with the attributes added by the parser being ordered in source order, followed by a parameter named "PARAM" whose value is null, followed by all the names and values of parameters given by param elements that are children of the object element, in tree order. If the plugin supports a scriptable interface, the HTMLObjectElement object representing the element should expose that interface. The object element represents the plugin. The plugin is not a nested browsing context.

Plugins are considered sandboxed for the purpose of an object element if the sandboxed plugins browsing context flag is set on the object element's node document's active sandboxing flag set.

Due to the algorithm above, the contents of object elements act as fallback content, used only when referenced resources can't be shown (e.g. because it returned a 404 error). This allows multiple object elements to be nested inside each other, targeting multiple user agents with different capabilities, with the user agent picking the first one it supports.

The object element potentially delays the load event.

The usemap attribute, if present while the object element represents an image, can indicate that the object has an associated image map. The attribute must be ignored if the object element doesn't represent an image.

The form attribute is used to explicitly associate the object element with its form owner.

Constraint validation: object elements are always barred from constraint validation.

The object element supports dimension attributes.

HTMLObjectElement/data

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLObjectElement/type

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLObjectElement/name

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLObjectElement/useMap

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The IDL attributes data, type and name each must reflect the respective content attributes of the same name. The useMap IDL attribute must reflect the usemap content attribute.

HTMLObjectElement/contentDocument

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The contentDocument IDL attribute, on getting, must return the object element's content document.

HTMLObjectElement/contentWindow

Support in all current engines.

Firefox22+Safari13+Chrome53+
OperaNoEdge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android22+Safari iOS13+Chrome Android53+WebView Android53+Samsung Internet6.0+Opera AndroidNo

The contentWindow IDL attribute must return the WindowProxy object of the object element's nested browsing context, if its nested browsing context is non-null; otherwise, it must return null.

The willValidate, validity, and validationMessage attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The form IDL attribute is part of the element's forms API.

In this example, an HTML page is embedded in another using the object element.

<figure>
 <object data="clock.html"></object>
 <figcaption>My HTML Clock</figcaption>
</figure>

The following example shows how a plugin can be used in HTML (in this case the Flash plugin, to show a video file). Fallback is provided for users who do not have Flash enabled, in this case using the video element to show the video for those using user agents that support video, and finally providing a link to the video for those who have neither Flash nor a video-capable browser.

<p>Look at my video:
 <object type="application/x-shockwave-flash">
  <param name=movie value="https://video.example.com/library/watch.swf">
  <param name=allowfullscreen value=true>
  <param name=flashvars value="https://video.example.com/vids/315981">
  <video controls src="https://video.example.com/vids/315981">
   <a href="https://video.example.com/vids/315981">View video</a>.
  </video>
 </object>
</p>

4.8.8 The param element

Categories:
None.
Contexts in which this element can be used:
As a child of an object element, before any flow content.
Content model:
Nothing.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
name — Name of parameter
value — Value of parameter
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLParamElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString value;

  // also has obsolete members
};

The param element defines parameters for plugins invoked by object elements. It does not represent anything on its own.

The name attribute gives the name of the parameter.

The value attribute gives the value of the parameter.

Both attributes must be present. They may have any value.

If both attributes are present, and if the parent element of the param is an object element, then the element defines a parameter with the given name-value pair.

If either the name or value of a parameter defined by a param element that is the child of an object element that represents an instantiated plugin changes, and if that plugin is communicating with the user agent using an API that features the ability to update the plugin when the name or value of a parameter so changes, then the user agent must appropriately exercise that ability to notify the plugin of the change.

The IDL attributes name and value must both reflect the respective content attributes of the same name.

The following example shows how the param element can be used to pass a parameter to a plugin, in this case the O3D plugin.

<!DOCTYPE HTML>
<html lang="en">
  <head>
   <title>O3D Utah Teapot</title>
  </head>
  <body>
   <p>
    <object type="application/vnd.o3d.auto">
     <param name="o3d_features" value="FloatingPointTextures">
     <img src="o3d-teapot.png"
          title="3D Utah Teapot illustration rendered using O3D."
          alt="When O3D renders the Utah Teapot, it appears as a squat
          teapot with a shiny metallic finish on which the
          surroundings are reflected, with a faint shadow caused by
          the lighting.">
     <p>To see the teapot actually rendered by O3D on your
     computer, please download and install the <a
     href="http://code.google.com/apis/o3d/docs/gettingstarted.html#install">O3D plugin</a>.</p>
    </object>
    <script src="o3d-teapot.js"></script>
   </p>
  </body>
</html>

4.8.9 video 元素

Element/video

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLVideoElement

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
分类
Flow content.
Phrasing content.
Embedded content.
如果有 controls 属性: Interactive content.
Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
如果该元素有src 属性: 后代可以有零个或多个 track 元素,均为透明的,并且没有媒体元素
如果该元素没有 src 属性: 后代可以有零个或多个 source 元素,零个或多个 track 元素,后代元素均是透明的,并且没有媒体元素
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
src — Address of the resource
crossorigin — How the element handles crossorigin requests
poster — Poster frame to show prior to video playback
preload — Hints how much buffering the media resource will likely need
autoplay — Hint that the media resource can be started automatically when the page is loaded
playsinline — Encourage the user agent to display video content within the element's playback area
loop — Whether to loop the media resource
muted — Whether to mute the media resource by default
controls — Show user agent controls
width — Horizontal dimension
height — Vertical dimension
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLVideoElement : HTMLMediaElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute unsigned long width;
  [CEReactions] attribute unsigned long height;
  readonly attribute unsigned long videoWidth;
  readonly attribute unsigned long videoHeight;
  [CEReactions] attribute USVString poster;
  [CEReactions] attribute boolean playsInline;
};

video 元素用于播放视频或电影,以及带有字幕的音频文件。

可以在 video 元素内提供一些文本内容。用户代理不应向用户展示这些内容;这些内容是用来提供给那些不支持 video元素的老旧浏览器,这样他们可以尝试替换为以前的视频插件,或者向用户展示这些文字,以便告知用户如何访问视频内容。

需要注意的是,video 标签内部的文本并不是为了解决可访问性问题。有许多其他特性能帮助弱视、盲人、听力障碍者、聋人以及有其他身体或认知障碍的人获取视频内容。要提供字幕,可以将其直接嵌入到视频中,也可以通过 track 元素外引文件的方式。可以将手语作为额外的视频轨道嵌入到视频流中。音频描述可以直接嵌入到视频流中或者通过 WebVTT 文件以文本的形式提供,通过 track 元素引用 WebVTT 文件时,浏览器会自动将文本合成为语音。WebVTT 同样可以用来提供章节标题。对于那些完全不想看视频的用户,可以在视频附近为他们提供一些链接用于跳转到一些文本内容。 [WEBVTT]

video 元素表面上只有视频数据,但其中也可能包含一些音频数据。

srccrossoriginpreloadautoplayloopmuted,以及 controls 属性是媒体元素的共有属性

poster 属性提供图片文件的 URL,用于在浏览器没有视频数据可用时显示。该属性的值必需是一个可能由空格包裹的合法的非空 URL

如果要使用指定的资源,那么在该元素创建时,或者 poster 属性被设置,更改或移除时,浏览器必须执行以下步骤以确定该元素的 poster frame(无论该元素的封面展示标志位的值如何):

  1. 如果 video 元素已经有一个此类型的算法实例在运行,在不改变当前 poster frame 的情况下终止该算法实例。

  2. 如果 poster 属性的值是空字符串或者没有设置该属性,那么便没有 poster frame;返回。

  3. 以相对于当前节点文档的路径解析 poster 属性的值。如果解析失败,那么便没有 poster frame;返回。

  4. 新建一个请求,其 urlresulting URL record客户端是元素的节点文档相关设置对象请求目的是"image",凭据模式是 "include",并且设置其 use-URL-credentials 标志位

  5. 获取请求。这个请求应当延迟文档节点的加载事件

  6. 如果成功加载图片,则 poster frame 就是该图片。否则没有 poster frame

poster 属性提供的图片(poster frame),旨在为用户提供一个该视频的大体印象。

playsinline 属性是一个布尔属性。如果展现该属性,则表明希望浏览器默认以“内联”的形式播放视频,”内联“是指限制在视频元素所在的区域播放,而不是直接全屏播放或者位于一个独立的可随意调整大小的窗口中。

没有显式地声明 playsinline 属性并不意味着视频会默认全屏播放,这完全由浏览器决定。实际上大多数浏览器更倾向于默认以“内联”的形式播放视频,因此在那些浏览器中,加不加 playsinline 属性都是一样的。


A video element represents what is given for the first matching condition in the list below:

When no video data is available (the element's readyState attribute is either HAVE_NOTHING, or HAVE_METADATA but no video data has yet been obtained at all, or the element's readyState attribute is any subsequent value but the media resource does not have a video channel)
The video element represents its poster frame, if any, or else transparent black with no intrinsic dimensions.
When the video element is paused, the current playback position is the first frame of video, and the element's show poster flag is set
The video element represents its poster frame, if any, or else the first frame of the video.
When the video element is paused, and the frame of video corresponding to the current playback position is not available (e.g. because the video is seeking or buffering)
When the video element is neither potentially playing nor paused (e.g. when seeking or stalled)
The video element represents the last frame of the video to have been rendered.
When the video element is paused
The video element represents the frame of video corresponding to the current playback position.
Otherwise (the video element has a video channel and is potentially playing)
The video element represents the frame of video at the continuously increasing "current" position. When the current playback position changes such that the last frame rendered is no longer the frame corresponding to the current playback position in the video, the new frame must be rendered.

Frames of video must be obtained from the video track that was selected when the event loop last reached step 1.

视频中的每一帧对应哪个播放位置由视频流的格式决定。

The video element also represents any text track cues whose text track cue active flag is set and whose text track is in the showing mode, and any audio from the media resource, at the current playback position.

Any audio associated with the media resource must, if played, be played synchronized with the current playback position, at the element's effective media volume. The user agent must play the audio from audio tracks that were enabled when the event loop last reached step 1.

除了上述提到的之外,用户代理可以以文字、图标或其他方式在播放区域为用户提供一些信息(比如缓冲中,未发现视频资源,视频加载出错等)。

无法渲染 video 标签的用户代理可以展示一个链接用于链接至其他的视频播放程序或者视频资源本身。

当一个 video 元素的媒体资源具有视频通道时, 该元素提供一个绘制源(paint source)绘制源的宽度是媒体资源固有宽度,高度是媒体资源固有高度,外观是当前播放位置对应的视频帧,如果当前帧不可用(比如在加载中时),则显示之前帧,如果没有之前的帧可用(比如视频第一帧都没加载完成),则显示黑色背景。


video . videoWidth

HTMLVideoElement/videoWidth

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
video . videoHeight

HTMLVideoElement/videoHeight

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

这些属性返回视频的固有尺寸,如果尺寸未知,则返回零。

媒体资源固有宽度固有高度CSS 像素为单位,这些值是在考虑过资源的尺寸、高宽比、净光圈、分辨率以及视频格式后得出的。如果一个有所变化的格式没有定义如何将宽高比作用于视频数据以获得“正确”的视频尺寸,那么浏览器必须通过增加增加某一维度同时使得另一维度保持不变来应用该比例。

videoWidth IDL 属性必须返回以 CSS 像素为单位的视频固有宽度videoHeight IDL 属性必须返回以 CSS 像素为单位的视频固有高度。如果一个元素的 readyState 属性是 HAVE_NOTHING,那么两个属性都必须返回 0。

无论何时,当视频的固有宽度或者固有高度改变时,(比如因为 selected video track 改变),如果此时元素的 readyState 属性不是 HAVE_NOTHING, 那么浏览器必须 入队一个媒体元素任务(指定元素为 媒体元素)来触发媒体元素上的 resize 事件。

video 元素支持 dimension attributes.

在没有其他的样式规则时,视频内容应当在播放区域中展现完整,并且高宽比保持不变,居中且尽可能的占据空间。这样一来,如果播放区域的高宽比与视频的高宽比并不一致,视频就会以 letterboxed 或 pillarboxed 的形式展现。不被视频内容占据的播放区域就什么都不显示(显示黑色)。

用户代理实现 CSS 样式时,上述要求可以使用渲染 video 时建议的样式来实现。

The intrinsic width of a video element's playback area is the intrinsic width of the poster frame, if that is available and the element currently represents its poster frame; otherwise, it is the intrinsic width of the video resource, if that is available; otherwise the intrinsic width is missing.

The intrinsic height of a video element's playback area is the intrinsic height of the poster frame, if that is available and the element currently represents its poster frame; otherwise it is the intrinsic height of the video resource, if that is available; otherwise the intrinsic height is missing.

video 元素的默认尺寸大小是宽 300 像素,高 150 像素[CSSIMAGES]


浏览器应当提供控制字幕的显隐,音频以及其他视频附加数据的功能,并且这些功能应该不会影响页面的正常渲染。

用户代理可以通过一些方式使得用户更加舒服地观看视频,比如全屏或者以一个独立的可改变大小的窗口播放视频。用户代理甚至可以在播放视频时默认触发这种模式,不过当 playsinline 属性被指定时,他们就不应该这么做了。跟其他的用户界面功能一样,除非显式地展现了切换不同模式时的功能按钮,否则进行模式切换时不应当影响页面的正常渲染。在这种独立的视口模式下,就算 controls 属性被省略,用户代理也可以显示完整的控制组件。

在播放视频时,浏览器可以调整某些系统功能来提升用户体验,比如禁用屏幕保护程序。


The poster IDL attribute must reflect the poster content attribute.

The playsInline IDL attribute must reflect the playsinline content attribute.

以下示例说明当视频播放失败时如何检测:

<script>
 function failed(e) {
   // video playback failed - show a message saying why
   switch (e.target.error.code) {
     case e.target.error.MEDIA_ERR_ABORTED:
       alert('You aborted the video playback.');
       break;
     case e.target.error.MEDIA_ERR_NETWORK:
       alert('A network error caused the video download to fail part-way.');
       break;
     case e.target.error.MEDIA_ERR_DECODE:
       alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');
       break;
     case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:
       alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');
       break;
     default:
       alert('An unknown error occurred.');
       break;
   }
 }
</script>
<p><video src="tgif.vid" autoplay controls onerror="failed(event)"></video></p>
<p><a href="tgif.vid">Download the video file</a>.</p>

4.8.10 The audio element

Element/audio

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera AndroidYes

HTMLAudioElement

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Categories:
Flow content.
Phrasing content.
Embedded content.
If the element has a controls attribute: Interactive content.
If the element has a controls attribute: Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
If the element has a src attribute: zero or more track elements, then transparent, but with no media element descendants.
If the element does not have a src attribute: zero or more source elements, then zero or more track elements, then transparent, but with no media element descendants.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
src — Address of the resource
crossorigin — How the element handles crossorigin requests
preload — Hints how much buffering the media resource will likely need
autoplay — Hint that the media resource can be started automatically when the page is loaded
loop — Whether to loop the media resource
muted — Whether to mute the media resource by default
controls — Show user agent controls
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window,
 LegacyFactoryFunction=Audio(optional DOMString src)]
interface HTMLAudioElement : HTMLMediaElement {
  [HTMLConstructor] constructor();
};

An audio element represents a sound or audio stream.

Content may be provided inside the audio element. User agents should not show this content to the user; it is intended for older web browsers which do not support audio, so that legacy audio plugins can be tried, or to show text to the users of these older browsers informing them of how to access the audio contents.

In particular, this content is not intended to address accessibility concerns. To make audio content accessible to the deaf or to those with other physical or cognitive disabilities, a variety of features are available. If captions or a sign language video are available, the video element can be used instead of the audio element to play the audio, allowing users to enable the visual alternatives. Chapter titles can be provided to aid navigation, using the track element and a WebVTT file. And, naturally, transcripts or other textual alternatives can be provided by simply linking to them in the prose near the audio element. [WEBVTT]

The audio element is a media element whose media data is ostensibly audio data.

The src, crossorigin, preload, autoplay, loop, muted, and controls attributes are the attributes common to all media elements.

audio = new Audio( [ url ] )

HTMLAudioElement/Audio

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns a new audio element, with the src attribute set to the value passed in the argument, if applicable.

A legacy factory function is provided for creating HTMLAudioElement objects (in addition to the factory methods from DOM such as createElement()): Audio(src). When invoked, the legacy factory function must perform the following steps:

  1. Let document be the current global object's associated Document.

  2. Let audio be the result of creating an element given document, audio, and the HTML namespace.

  3. Set an attribute value for audio using "preload" and "auto".

  4. If src is given, then set an attribute value for audio using "src" and src. (This will cause the user agent to invoke the object's resource selection algorithm before returning.)

  5. Return audio.

4.8.11 The track element

Element/track

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS6+Chrome Android25+WebView AndroidYesSamsung Internet1.5+Opera Android?

HTMLTrackElement

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS6+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12+
Categories:
None.
Contexts in which this element can be used:
As a child of a media element, before any flow content.
Content model:
Nothing.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
kind — The type of text track
src — Address of the resource
srclang — Language of the text track
label — User-visible label
default — Enable the track if no other text track is more suitable
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLTrackElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString kind;
  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString srclang;
  [CEReactions] attribute DOMString label;
  [CEReactions] attribute boolean default;

  const unsigned short NONE = 0;
  const unsigned short LOADING = 1;
  const unsigned short LOADED = 2;
  const unsigned short ERROR = 3;
  readonly attribute unsigned short readyState;

  readonly attribute TextTrack track;
};

The track element allows authors to specify explicit external timed text tracks for media elements. It does not represent anything on its own.

The kind attribute is an enumerated attribute. The following table lists the keywords defined for this attribute. The keyword given in the first cell of each row maps to the state given in the second cell.

Keyword State Brief description
subtitles Subtitles Transcription or translation of the dialogue, suitable for when the sound is available but not understood (e.g. because the user does not understand the language of the media resource's audio track). Overlaid on the video.
captions Captions Transcription or translation of the dialogue, sound effects, relevant musical cues, and other relevant audio information, suitable for when sound is unavailable or not clearly audible (e.g. because it is muted, drowned-out by ambient noise, or because the user is deaf). Overlaid on the video; labeled as appropriate for the hard-of-hearing.
descriptions Descriptions Textual descriptions of the video component of the media resource, intended for audio synthesis when the visual component is obscured, unavailable, or not usable (e.g. because the user is interacting with the application without a screen while driving, or because the user is blind). Synthesized as audio.
chapters Chapters metadata Tracks intended for use from script. Not displayed by the user agent.
metadata Metadata

The attribute may be omitted. The missing value default is the subtitles state. The invalid value default is the metadata state.

The src attribute gives the URL of the text track data. The value must be a valid non-empty URL potentially surrounded by spaces. This attribute must be present.

If the element has a src attribute whose value is not the empty string and whose value, when the attribute was set, could be successfully parsed relative to the element's node document, then the element's track URL is the resulting URL string. Otherwise, the element's track URL is the empty string.

If the element's track URL identifies a WebVTT resource, and the element's kind attribute is not in the chapters metadata or metadata state, then the WebVTT file must be a WebVTT file using cue text. [WEBVTT]

The srclang attribute gives the language of the text track data. The value must be a valid BCP 47 language tag. This attribute must be present if the element's kind attribute is in the subtitles state. [BCP47]

If the element has a srclang attribute whose value is not the empty string, then the element's track language is the value of the attribute. Otherwise, the element has no track language.

The label attribute gives a user-readable title for the track. This title is used by user agents when listing subtitle, caption, and audio description tracks in their user interface.

The value of the label attribute, if the attribute is present, must not be the empty string. Furthermore, there must not be two track element children of the same media element whose kind attributes are in the same state, whose srclang attributes are both missing or have values that represent the same language, and whose label attributes are again both missing or both have the same value.

If the element has a label attribute whose value is not the empty string, then the element's track label is the value of the attribute. Otherwise, the element's track label is an empty string.

The default attribute is a boolean attribute, which, if specified, indicates that the track is to be enabled if the user's preferences do not indicate that another track would be more appropriate.

Each media element must have no more than one track element child whose kind attribute is in the subtitles or captions state and whose default attribute is specified.

Each media element must have no more than one track element child whose kind attribute is in the description state and whose default attribute is specified.

Each media element must have no more than one track element child whose kind attribute is in the chapters metadata state and whose default attribute is specified.

There is no limit on the number of track elements whose kind attribute is in the metadata state and whose default attribute is specified.

track . readyState

Returns the text track readiness state, represented by a number from the following list:

track . NONE (0)

The text track not loaded state.

track . LOADING (1)

The text track loading state.

track . LOADED (2)

The text track loaded state.

track . ERROR (3)

The text track failed to load state.

track . track

Returns the TextTrack object corresponding to the text track of the track element.

The readyState attribute must return the numeric value corresponding to the text track readiness state of the track element's text track, as defined by the following list:

NONE (numeric value 0)
The text track not loaded state.
LOADING (numeric value 1)
The text track loading state.
LOADED (numeric value 2)
The text track loaded state.
ERROR (numeric value 3)
The text track failed to load state.

The track IDL attribute must, on getting, return the track element's text track's corresponding TextTrack object.

HTMLTrackElement/src

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS6+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12+

The src, srclang, label, and default IDL attributes must reflect the respective content attributes of the same name. The kind IDL attribute must reflect the content attribute of the same name, limited to only known values.

This video has subtitles in several languages:

<video src="brave.webm">
 <track kind=subtitles src=brave.en.vtt srclang=en label="English">
 <track kind=captions src=brave.en.hoh.vtt srclang=en label="English for the Hard of Hearing">
 <track kind=subtitles src=brave.fr.vtt srclang=fr lang=fr label="Français">
 <track kind=subtitles src=brave.de.vtt srclang=de lang=de label="Deutsch">
</video>

(The lang attributes on the last two describe the language of the label attribute, not the language of the subtitles themselves. The language of the subtitles is given by the srclang attribute.)

4.8.12 Media elements

HTMLMediaElement objects (audio and video, in this specification) are simply known as media elements.

HTMLMediaElement

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android11+
enum CanPlayTypeResult { "" /* empty string */, "maybe", "probably" };
typedef (MediaStream or MediaSource or Blob) MediaProvider;

[Exposed=Window]
interface HTMLMediaElement : HTMLElement {

  // error state
  readonly attribute MediaError? error;

  // network state
  [CEReactions] attribute USVString src;
  attribute MediaProvider? srcObject;
  readonly attribute USVString currentSrc;
  [CEReactions] attribute DOMString? crossOrigin;
  const unsigned short NETWORK_EMPTY = 0;
  const unsigned short NETWORK_IDLE = 1;
  const unsigned short NETWORK_LOADING = 2;
  const unsigned short NETWORK_NO_SOURCE = 3;
  readonly attribute unsigned short networkState;
  [CEReactions] attribute DOMString preload;
  readonly attribute TimeRanges buffered;
  undefined load();
  CanPlayTypeResult canPlayType(DOMString type);

  // ready state
  const unsigned short HAVE_NOTHING = 0;
  const unsigned short HAVE_METADATA = 1;
  const unsigned short HAVE_CURRENT_DATA = 2;
  const unsigned short HAVE_FUTURE_DATA = 3;
  const unsigned short HAVE_ENOUGH_DATA = 4;
  readonly attribute unsigned short readyState;
  readonly attribute boolean seeking;

  // playback state
  attribute double currentTime;
  undefined fastSeek(double time);
  readonly attribute unrestricted double duration;
  object getStartDate();
  readonly attribute boolean paused;
  attribute double defaultPlaybackRate;
  attribute double playbackRate;
  attribute boolean preservesPitch;
  readonly attribute TimeRanges played;
  readonly attribute TimeRanges seekable;
  readonly attribute boolean ended;
  [CEReactions] attribute boolean autoplay;
  [CEReactions] attribute boolean loop;
  Promise<undefined> play();
  undefined pause();

  // controls
  [CEReactions] attribute boolean controls;
  attribute double volume;
  attribute boolean muted;
  [CEReactions] attribute boolean defaultMuted;

  // tracks
  [SameObject] readonly attribute AudioTrackList audioTracks;
  [SameObject] readonly attribute VideoTrackList videoTracks;
  [SameObject] readonly attribute TextTrackList textTracks;
  TextTrack addTextTrack(TextTrackKind kind, optional DOMString label = "", optional DOMString language = "");
};

The media element attributes, src, crossorigin, preload, autoplay, loop, muted, and controls, apply to all media elements. They are defined in this section.

Media elements are used to present audio data, or video and audio data, to the user. This is referred to as media data in this section, since this section applies equally to media elements for audio or for video. The term media resource is used to refer to the complete set of media data, e.g. the complete video file, or complete audio file.

A media resource can have multiple audio and video tracks. For the purposes of a media element, the video data of the media resource is only that of the currently selected track (if any) as given by the element's videoTracks attribute when the event loop last reached step 1, and the audio data of the media resource is the result of mixing all the currently enabled tracks (if any) given by the element's audioTracks attribute when the event loop last reached step 1.

Both audio and video elements can be used for both audio and video. The main difference between the two is simply that the audio element has no playback area for visual content (such as video or captions), whereas the video element does.

Each media element has a unique media element event task source.

To queue a media element task with a media element element and a series of steps steps, queue an element task on the media element's media element event task source given element and steps.

4.8.12.1 Error codes

MediaError

Support in all current engines.

Firefox4+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
media . error

HTMLMediaElement/error

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns a MediaError object representing the current error state of the element.

Returns null if there is no error.

All media elements have an associated error status, which records the last error the element encountered since its resource selection algorithm was last invoked. The error attribute, on getting, must return the MediaError object created for this last error, or null if there has not been an error.

[Exposed=Window]
interface MediaError {
  const unsigned short MEDIA_ERR_ABORTED = 1;
  const unsigned short MEDIA_ERR_NETWORK = 2;
  const unsigned short MEDIA_ERR_DECODE = 3;
  const unsigned short MEDIA_ERR_SRC_NOT_SUPPORTED = 4;

  readonly attribute unsigned short code;
  readonly attribute DOMString message;
};
media . error . code

MediaError/code

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the current error's error code, from the list below.

media . error . message

MediaError/message

Support in all current engines.

Firefox52+Safari15+Chrome59+
Opera46+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android52+Safari iOS15+Chrome Android59+WebView Android59+Samsung Internet7.0+Opera Android43+

Returns a specific informative diagnostic message about the error condition encountered. The message and message format are not generally uniform across different user agents. If no such message is available, then the empty string is returned.

Every MediaError object has a message, which is a string, and a code, which is one of the following:

MEDIA_ERR_ABORTED (numeric value 1)
The fetching process for the media resource was aborted by the user agent at the user's request.
MEDIA_ERR_NETWORK (numeric value 2)
A network error of some description caused the user agent to stop fetching the media resource, after the resource was established to be usable.
MEDIA_ERR_DECODE (numeric value 3)
An error of some description occurred while decoding the media resource, after the resource was established to be usable.
MEDIA_ERR_SRC_NOT_SUPPORTED (numeric value 4)
The media resource indicated by the src attribute or assigned media provider object was not suitable.

To create a MediaError, given an error code which is one of the above values, return a new MediaError object whose code is the given error code and whose message is a string containing any details the user agent is able to supply about the cause of the error condition, or the empty string if the user agent is unable to supply such details. This message string must not contain only the information already available via the supplied error code; for example, it must not simply be a translation of the code into a string format. If no additional information is available beyond that provided by the error code, the message must be set to the empty string.

The code attribute of a MediaError object must return this MediaError object's code.

The message attribute of a MediaError object must return this MediaError object's message.

4.8.12.2 Location of the media resource

The src content attribute on media elements gives the URL of the media resource (video, audio) to show. The attribute, if present, must contain a valid non-empty URL potentially surrounded by spaces.

If the itemprop attribute is specified on the media element, then the src attribute must also be specified.

The crossorigin content attribute on media elements is a CORS settings attribute.

If a media element is created with a src attribute, the user agent must immediately invoke the media element's resource selection algorithm.

If a src attribute of a media element is set or changed, the user agent must invoke the media element's media element load algorithm. (Removing the src attribute does not do this, even if there are source elements present.)

HTMLMediaElement/src

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The src IDL attribute on media elements must reflect the content attribute of the same name.

HTMLMediaElement/crossOrigin

Support in all current engines.

Firefox22+Safari10+Chrome33+
Opera20+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android22+Safari iOS10+Chrome Android33+WebView Android4.4.3+Samsung Internet2.0+Opera Android20+

The crossOrigin IDL attribute must reflect the crossorigin content attribute, limited to only known values.

A media provider object is an object that can represent a media resource, separate from a URL. MediaStream objects, MediaSource objects, and Blob objects are all media provider objects.

Each media element can have an assigned media provider object, which is a media provider object. When a media element is created, it has no assigned media provider object.

media . srcObject [ = source ]

HTMLMediaElement/srcObject

Support in one engine only.

Firefox🔰 42+Safari11+Chrome🔰 52+
Opera🔰 39+Edge🔰 79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android🔰 42+Safari iOS11+Chrome Android🔰 52+WebView Android🔰 52+Samsung Internet🔰 6.0+Opera Android🔰 41+

Allows the media element to be assigned a media provider object.

media . currentSrc

HTMLMediaElement/currentSrc

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the URL of the current media resource, if any.

Returns the empty string when there is no media resource, or it doesn't have a URL.

The currentSrc IDL attribute must initially be set to the empty string. Its value is changed by the resource selection algorithm defined below.

The srcObject IDL attribute, on getting, must return the element's assigned media provider object, if any, or null otherwise. On setting, it must set the element's assigned media provider object to the new value, and then invoke the element's media element load algorithm.

There are three ways to specify a media resource: the srcObject IDL attribute, the src content attribute, and source elements. The IDL attribute takes priority, followed by the content attribute, followed by the elements.

4.8.12.3 MIME types

A media resource can be described in terms of its type, specifically a MIME type, in some cases with a codecs parameter. (Whether the codecs parameter is allowed or not depends on the MIME type.) [RFC6381]

Types are usually somewhat incomplete descriptions; for example "video/mpeg" doesn't say anything except what the container type is, and even a type like "video/mp4; codecs="avc1.42E01E, mp4a.40.2"" doesn't include information like the actual bitrate (only the maximum bitrate). Thus, given a type, a user agent can often only know whether it might be able to play media of that type (with varying levels of confidence), or whether it definitely cannot play media of that type.

A type that the user agent knows it cannot render is one that describes a resource that the user agent definitely does not support, for example because it doesn't recognize the container type, or it doesn't support the listed codecs.

The MIME type "application/octet-stream" with no parameters is never a type that the user agent knows it cannot render. User agents must treat that type as equivalent to the lack of any explicit Content-Type metadata when it is used to label a potential media resource.

Only the MIME type "application/octet-stream" with no parameters is special-cased here; if any parameter appears with it, it will be treated just like any other MIME type. This is a deviation from the rule that unknown MIME type parameters should be ignored.

media . canPlayType(type)

HTMLMediaElement/canPlayType

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the empty string (a negative response), "maybe", or "probably" based on how confident the user agent is that it can play media resources of the given type.

The canPlayType(type) method must return the empty string if type is a type that the user agent knows it cannot render or is the type "application/octet-stream"; it must return "probably" if the user agent is confident that the type represents a media resource that it can render if used in with this audio or video element; and it must return "maybe" otherwise. Implementors are encouraged to return "maybe" unless the type can be confidently established as being supported or not. Generally, a user agent should never return "probably" for a type that allows the codecs parameter if that parameter is not present.

This script tests to see if the user agent supports a (fictional) new format to dynamically decide whether to use a video element or a plugin:

<section id="video">
 <p><a href="playing-cats.nfv">Download video</a></p>
</section>
<script>
 var videoSection = document.getElementById('video');
 var videoElement = document.createElement('video');
 var support = videoElement.canPlayType('video/x-new-fictional-format;codecs="kittens,bunnies"');
 if (support != "probably" && "New Fictional Video Plugin" in navigator.plugins) {
   // not confident of browser support
   // but we have a plugin
   // so use plugin instead
   videoElement = document.createElement("embed");
 } else if (support == "") {
   // no support from browser and no plugin
   // do nothing
   videoElement = null;
 }
 if (videoElement) {
   while (videoSection.hasChildNodes())
     videoSection.removeChild(videoSection.firstChild);
   videoElement.setAttribute("src", "playing-cats.nfv");
   videoSection.appendChild(videoElement);
 }
</script>

The type attribute of the source element allows the user agent to avoid downloading resources that use formats it cannot render.

4.8.12.4 网络状态
media . networkState

HTMLMediaElement/networkState

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

从下面的代码列表中,返回该元素网络活动的当前状态。

媒体元素 与网络交互时,它们当前的网络活动由 networkState 属性表示。 读取时,它必须返回该元素的当前网络状态,它的值必须是下面一种:

NETWORK_EMPTY (数字值 0)
这个元素还没初始化。所有属性都处于初始状态。
NETWORK_IDLE (数字值 1)
该元素 的 资源选择算法 处于活跃状态且 选择了一个 资源, 但它现在还没真正使用网络。
NETWORK_LOADING (数字值 2)
用户代理正在尝试下载数据。
NETWORK_NO_SOURCE (数字值 3)
该元素的 资源选择算法 处于活跃状态但 还没找到要使用的 资源

下面定义的 资源选择算法 确切地描述了 何时 networkState 属性的值会改变, 以及触发什么样的事件来表示这个状态改变。

4.8.12.5 Loading the media resource
media . load()

HTMLMediaElement/load

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Causes the element to reset and start selecting and loading a new media resource from scratch.

All media elements have a can autoplay flag, which must begin in the true state, and a delaying-the-load-event flag, which must begin in the false state. While the delaying-the-load-event flag is true, the element must delay the load event of its document.

When the load() method on a media element is invoked, the user agent must run the media element load algorithm.

The media element load algorithm consists of the following steps.

  1. Abort any already-running instance of the resource selection algorithm for this element.

  2. Let pending tasks be a list of all tasks from the media element's media element event task source in one of the task queues.

  3. For each task in pending tasks that would resolve pending play promises or reject pending play promises, immediately resolve or reject those promises in the order the corresponding tasks were queued.

  4. Remove each task in pending tasks from its task queue

    Basically, pending events and callbacks are discarded and promises in-flight to be resolved/rejected are resolved/rejected immediately when the media element starts loading a new resource.

  5. If the media element's networkState is set to NETWORK_LOADING or NETWORK_IDLE, queue a media element task given the media element to fire an event named abort at the media element.

  6. If the media element's networkState is not set to NETWORK_EMPTY, then:

    1. Queue a media element task given the media element to fire an event named emptied at the media element.

    2. If a fetching process is in progress for the media element, the user agent should stop it.

    3. If the media element's assigned media provider object is a MediaSource object, then detach it.

    4. Forget the media element's media-resource-specific tracks.

    5. If readyState is not set to HAVE_NOTHING, then set it to that state.

    6. If the paused attribute is false, then:

      1. Set the paused attribute to true.

      2. Take pending play promises and reject pending play promises with the result and an "AbortError" DOMException.

    7. If seeking is true, set it to false.

    8. Set the current playback position to 0.

      Set the official playback position to 0.

      If this changed the official playback position, then queue a media element task given the media element to fire an event named timeupdate at the media element.

    9. Set the timeline offset to Not-a-Number (NaN).

    10. Update the duration attribute to Not-a-Number (NaN).

      The user agent will not fire a durationchange event for this particular change of the duration.

  7. Set the playbackRate attribute to the value of the defaultPlaybackRate attribute.

  8. Set the error attribute to null and the can autoplay flag to true.

  9. Invoke the media element's resource selection algorithm.

  10. Playback of any previously playing media resource for this element stops.

The resource selection algorithm for a media element is as follows. This algorithm is always invoked as part of a task, but one of the first steps in the algorithm is to return and continue running the remaining steps in parallel. In addition, this algorithm interacts closely with the event loop mechanism; in particular, it has synchronous sections (which are triggered as part of the event loop algorithm). Steps in such sections are marked with ⌛.

  1. Set the element's networkState attribute to the NETWORK_NO_SOURCE value.

  2. Set the element's show poster flag to true.

  3. Set the media element's delaying-the-load-event flag to true (this delays the load event).

  4. Await a stable state, allowing the task that invoked this algorithm to continue. The synchronous section consists of all the remaining steps of this algorithm until the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)

  5. ⌛ If the media element's blocked-on-parser flag is false, then populate the list of pending text tracks.

  6. ⌛ If the media element has an assigned media provider object, then let mode be object.

    ⌛ Otherwise, if the media element has no assigned media provider object but has a src attribute, then let mode be attribute.

    ⌛ Otherwise, if the media element does not have an assigned media provider object and does not have a src attribute, but does have a source element child, then let mode be children and let candidate be the first such source element child in tree order.

    ⌛ Otherwise the media element has no assigned media provider object and has neither a src attribute nor a source element child:

    1. ⌛ Set the networkState to NETWORK_EMPTY.

    2. ⌛ Set the element's delaying-the-load-event flag to false. This stops delaying the load event.

    3. End the synchronous section and return.

  7. ⌛ Set the media element's networkState to NETWORK_LOADING.

  8. Queue a media element task given the media element to fire an event named loadstart at the media element.

  9. Run the appropriate steps from the following list:

    If mode is object
    1. ⌛ Set the currentSrc attribute to the empty string.

    2. End the synchronous section, continuing the remaining steps in parallel.

    3. Run the resource fetch algorithm with the assigned media provider object. If that algorithm returns without aborting this one, then the load failed.

    4. Failed with media provider: Reaching this step indicates that the media resource failed to load. Take pending play promises and queue a media element task given the media element to run the dedicated media source failure steps with the result.

    5. Wait for the task queued by the previous step to have executed.

    6. Return. The element won't attempt to load another resource until this algorithm is triggered again.

    If mode is attribute
    1. ⌛ If the src attribute's value is the empty string, then end the synchronous section, and jump down to the failed with attribute step below.

    2. ⌛ Let urlString and urlRecord be the resulting URL string and the resulting URL record, respectively, that would have resulted from parsing the URL specified by the src attribute's value relative to the media element's node document when the src attribute was last changed.

    3. ⌛ If urlString was obtained successfully, set the currentSrc attribute to urlString.

    4. End the synchronous section, continuing the remaining steps in parallel.

    5. If urlRecord was obtained successfully, run the resource fetch algorithm with urlRecord. If that algorithm returns without aborting this one, then the load failed.

    6. Failed with attribute: Reaching this step indicates that the media resource failed to load or that the given URL could not be parsed. Take pending play promises and queue a media element task given the media element to run the dedicated media source failure steps with the result.

    7. Wait for the task queued by the previous step to have executed.

    8. Return. The element won't attempt to load another resource until this algorithm is triggered again.

    Otherwise (mode is children)
    1. ⌛ Let pointer be a position defined by two adjacent nodes in the media element's child list, treating the start of the list (before the first child in the list, if any) and end of the list (after the last child in the list, if any) as nodes in their own right. One node is the node before pointer, and the other node is the node after pointer. Initially, let pointer be the position between the candidate node and the next node, if there are any, or the end of the list, if it is the last node.

      As nodes are inserted and removed into the media element, pointer must be updated as follows:

      If a new node is inserted between the two nodes that define pointer
      Let pointer be the point between the node before pointer and the new node. In other words, insertions at pointer go after pointer.
      If the node before pointer is removed
      Let pointer be the point between the node after pointer and the node before the node after pointer. In other words, pointer doesn't move relative to the remaining nodes.
      If the node after pointer is removed
      Let pointer be the point between the node before pointer and the node after the node before pointer. Just as with the previous case, pointer doesn't move relative to the remaining nodes.

      Other changes don't affect pointer.

    2. Process candidate: If candidate does not have a src attribute, or if its src attribute's value is the empty string, then end the synchronous section, and jump down to the failed with elements step below.

    3. ⌛ Let urlString and urlRecord be the resulting URL string and the resulting URL record, respectively, that would have resulted from parsing the URL specified by candidate's src attribute's value relative to the candidate's node document when the src attribute was last changed.

    4. ⌛ If urlString was not obtained successfully, then end the synchronous section, and jump down to the failed with elements step below.

    5. ⌛ If candidate has a type attribute whose value, when parsed as a MIME type (including any codecs described by the codecs parameter, for types that define that parameter), represents a type that the user agent knows it cannot render, then end the synchronous section, and jump down to the failed with elements step below.

    6. ⌛ Set the currentSrc attribute to urlString.

    7. End the synchronous section, continuing the remaining steps in parallel.

    8. Run the resource fetch algorithm with urlRecord. If that algorithm returns without aborting this one, then the load failed.

    9. Failed with elements: Queue a media element task given the media element to fire an event named error at candidate.

    10. Await a stable state. The synchronous section consists of all the remaining steps of this algorithm until the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)

    11. Forget the media element's media-resource-specific tracks.

    12. Find next candidate: Let candidate be null.

    13. Search loop: If the node after pointer is the end of the list, then jump to the waiting step below.

    14. ⌛ If the node after pointer is a source element, let candidate be that element.

    15. ⌛ Advance pointer so that the node before pointer is now the node that was after pointer, and the node after pointer is the node after the node that used to be after pointer, if any.

    16. ⌛ If candidate is null, jump back to the search loop step. Otherwise, jump back to the process candidate step.

    17. Waiting: Set the element's networkState attribute to the NETWORK_NO_SOURCE value.

    18. ⌛ Set the element's show poster flag to true.

    19. Queue a media element task given the media element given the element to set the element's delaying-the-load-event flag to false. This stops delaying the load event.

    20. End the synchronous section, continuing the remaining steps in parallel.

    21. Wait until the node after pointer is a node other than the end of the list. (This step might wait forever.)

    22. Await a stable state. The synchronous section consists of all the remaining steps of this algorithm until the algorithm says the synchronous section has ended. (Steps in synchronous sections are marked with ⌛.)

    23. ⌛ Set the element's delaying-the-load-event flag back to true (this delays the load event again, in case it hasn't been fired yet).

    24. ⌛ Set the networkState back to NETWORK_LOADING.

    25. ⌛ Jump back to the find next candidate step above.

    The dedicated media source failure steps with a list of promises promises are the following steps:

    1. Set the error attribute to the result of creating a MediaError with MEDIA_ERR_SRC_NOT_SUPPORTED.

    2. Forget the media element's media-resource-specific tracks.

    3. Set the element's networkState attribute to the NETWORK_NO_SOURCE value.

    4. Set the element's show poster flag to true.

    5. Fire an event named error at the media element.

    6. Reject pending play promises with promises and a "NotSupportedError" DOMException.

    7. Set the element's delaying-the-load-event flag to false. This stops delaying the load event.

The resource fetch algorithm for a media element and a given URL record or media provider object is as follows:

  1. If the algorithm was invoked with media provider object or a URL record whose object is a media provider object, then let mode be local. Otherwise let mode be remote.

  2. If mode is remote, then let the current media resource be the resource given by the URL record passed to this algorithm; otherwise, let the current media resource be the resource given by the media provider object. Either way, the current media resource is now the element's media resource.

  3. Remove all media-resource-specific text tracks from the media element's list of pending text tracks, if any.

  4. Run the appropriate steps from the following list:

    If mode is remote
    1. Optionally, run the following substeps. This is the expected behavior if the user agent intends to not attempt to fetch the resource until the user requests it explicitly (e.g. as a way to implement the preload attribute's none keyword).

      1. Set the networkState to NETWORK_IDLE.

      2. Queue a media element task given the media element to fire an event named suspend at the element.

      3. Queue a media element task given the media element to set the element's delaying-the-load-event flag to false. This stops delaying the load event.

      4. Wait for the task to be run.

      5. Wait for an implementation-defined event (e.g., the user requesting that the media element begin playback).

      6. Set the element's delaying-the-load-event flag back to true (this delays the load event again, in case it hasn't been fired yet).

      7. Set the networkState to NETWORK_LOADING.

    2. Let destination be "audio" if the media element is an audio element and to "video" otherwise.

      Let request be the result of creating a potential-CORS request given current media resource's URL record, destination, and the media element's crossorigin content attribute value.

      Set request's client to the media element's node document's relevant settings object.

      Fetch request.

      The response's unsafe response obtained in this fashion, if any, contains the media data. It can be CORS-same-origin or CORS-cross-origin; this affects whether subtitles referenced in the media data are exposed in the API and, for video elements, whether a canvas gets tainted when the video is drawn on it.

      The stall timeout is an implementation-defined length of time, which should be about three seconds. When a media element that is actively attempting to obtain media data has failed to receive any data for a duration equal to the stall timeout, the user agent must queue a media element task given the media element to fire an event named stalled at the element.

      User agents may allow users to selectively block or slow media data downloads. When a media element's download has been blocked altogether, the user agent must act as if it was stalled (as opposed to acting as if the connection was closed). The rate of the download may also be throttled automatically by the user agent, e.g. to balance the download with other connections sharing the same bandwidth.

      User agents may decide to not download more content at any time, e.g. after buffering five minutes of a one hour media resource, while waiting for the user to decide whether to play the resource or not, while waiting for user input in an interactive resource, or when the user navigates away from the page. When a media element's download has been suspended, the user agent must queue a media element task given the media element to set the networkState to NETWORK_IDLE and fire an event named suspend at the element. If and when downloading of the resource resumes, the user agent must queue a media element task given the media element to set the networkState to NETWORK_LOADING. Between the queuing of these tasks, the load is suspended (so progress events don't fire, as described above).

      The preload attribute provides a hint regarding how much buffering the author thinks is advisable, even in the absence of the autoplay attribute.

      When a user agent decides to completely suspend a download, e.g., if it is waiting until the user starts playback before downloading any further content, the user agent must queue a media element task given the media element to set the element's delaying-the-load-event flag to false. This stops delaying the load event.

      The user agent may use whatever means necessary to fetch the resource (within the constraints put forward by this and other specifications); for example, reconnecting to the server in the face of network errors, using HTTP range retrieval requests, or switching to a streaming protocol. The user agent must consider a resource erroneous only if it has given up trying to fetch it.

      To determine the format of the media resource, the user agent must use the rules for sniffing audio and video specifically.

      While the load is not suspended (see below), every 350ms (±200ms) or for every byte received, whichever is least frequent, queue a media element task given the media element to fire an event named progress at the element.

      The networking task source tasks to process the data as it is being fetched must each immediately queue a media element task given the media element to run the first appropriate steps from the media data processing steps list below. (A new task is used for this so that the work described below occurs relative to the appropriate media element event task source rather than using the networking task source.)

      When the networking task source has queued the last task as part of fetching the media resource (i.e. once the download has completed), if the fetching process completes without errors, including decoding the media data, and if all of the data is available to the user agent without network access, then, the user agent must move on to the final step below. This might never happen, e.g. when streaming an infinite resource such as web radio, or if the resource is longer than the user agent's ability to cache data.

      While the user agent might still need network access to obtain parts of the media resource, the user agent must remain on this step.

      For example, if the user agent has discarded the first half of a video, the user agent will remain at this step even once the playback has ended, because there is always the chance the user will seek back to the start. In fact, in this situation, once playback has ended, the user agent will end up firing a suspend event, as described earlier.

    Otherwise (mode is local)

    The resource described by the current media resource, if any, contains the media data. It is CORS-same-origin.

    If the current media resource is a raw data stream (e.g. from a File object), then to determine the format of the media resource, the user agent must use the rules for sniffing audio and video specifically. Otherwise, if the data stream is pre-decoded, then the format is the format given by the relevant specification.

    Whenever new data for the current media resource becomes available, queue a media element task given the media element to run the first appropriate steps from the media data processing steps list below.

    When the current media resource is permanently exhausted (e.g. all the bytes of a Blob have been processed), if there were no decoding errors, then the user agent must move on to the final step below. This might never happen, e.g. if the current media resource is a MediaStream.

    The media data processing steps list is as follows:

    If the media data cannot be fetched at all, due to network errors, causing the user agent to give up trying to fetch the resource
    If the media data can be fetched but is found by inspection to be in an unsupported format, or can otherwise not be rendered at all

    DNS errors, HTTP 4xx and 5xx errors (and equivalents in other protocols), and other fatal network errors that occur before the user agent has established whether the current media resource is usable, as well as the file using an unsupported container format, or using unsupported codecs for all the data, must cause the user agent to execute the following steps:

    1. The user agent should cancel the fetching process.

    2. Abort this subalgorithm, returning to the resource selection algorithm.

    If the media resource is found to have an audio track
    1. Create an AudioTrack object to represent the audio track.

    2. Update the media element's audioTracks attribute's AudioTrackList object with the new AudioTrack object.

    3. Let enable be unknown.

    4. If either the media resource or the URL of the current media resource indicate a particular set of audio tracks to enable, or if the user agent has information that would facilitate the selection of specific audio tracks to improve the user's experience, then: if this audio track is one of the ones to enable, then set enable to true, otherwise, set enable to false.

      This could be triggered by media fragment syntax, but it could also be triggered e.g. by the user agent selecting a 5.1 surround sound audio track over a stereo audio track.

    5. If enable is still unknown, then, if the media element does not yet have an enabled audio track, then set enable to true, otherwise, set enable to false.

    6. If enable is true, then enable this audio track, otherwise, do not enable this audio track.

    7. Fire an event named addtrack at this AudioTrackList object, using TrackEvent, with the track attribute initialized to the new AudioTrack object.

    If the media resource is found to have a video track
    1. Create a VideoTrack object to represent the video track.

    2. Update the media element's videoTracks attribute's VideoTrackList object with the new VideoTrack object.

    3. Let enable be unknown.

    4. If either the media resource or the URL of the current media resource indicate a particular set of video tracks to enable, or if the user agent has information that would facilitate the selection of specific video tracks to improve the user's experience, then: if this video track is the first such video track, then set enable to true, otherwise, set enable to false.

      This could again be triggered by media fragment syntax.

    5. If enable is still unknown, then, if the media element does not yet have a selected video track, then set enable to true, otherwise, set enable to false.

    6. If enable is true, then select this track and unselect any previously selected video tracks, otherwise, do not select this video track. If other tracks are unselected, then a change event will be fired.

    7. Fire an event named addtrack at this VideoTrackList object, using TrackEvent, with the track attribute initialized to the new VideoTrack object.

    Once enough of the media data has been fetched to determine the duration of the media resource, its dimensions, and other metadata

    This indicates that the resource is usable. The user agent must follow these substeps:

    1. Establish the media timeline for the purposes of the current playback position and the earliest possible position, based on the media data.

    2. Update the timeline offset to the date and time that corresponds to the zero time in the media timeline established in the previous step, if any. If no explicit time and date is given by the media resource, the timeline offset must be set to Not-a-Number (NaN).

    3. Set the current playback position and the official playback position to the earliest possible position.

    4. Update the duration attribute with the time of the last frame of the resource, if known, on the media timeline established above. If it is not known (e.g. a stream that is in principle infinite), update the duration attribute to the value positive Infinity.

      The user agent will queue a media element task given the media element to fire an event named durationchange at the element at this point.

    5. For video elements, set the videoWidth and videoHeight attributes, and queue a media element task given the media element to fire an event named resize at the media element.

      Further resize events will be fired if the dimensions subsequently change.

    6. Set the readyState attribute to HAVE_METADATA.

      A loadedmetadata DOM event will be fired as part of setting the readyState attribute to a new value.

    7. Let jumped be false.

    8. If the media element's default playback start position is greater than zero, then seek to that time, and let jumped be true.

    9. Let the media element's default playback start position be zero.

    10. Let the initial playback position be zero.

    11. If either the media resource or the URL of the current media resource indicate a particular start time, then set the initial playback position to that time and, if jumped is still false, seek to that time.

      For example, with media formats that support media fragment syntax, the fragment can be used to indicate a start position.

    12. If there is no enabled audio track, then enable an audio track. This will cause a change event to be fired.

    13. If there is no selected video track, then select a video track. This will cause a change event to be fired.

    Once the readyState attribute reaches HAVE_CURRENT_DATA, after the loadeddata event has been fired, set the element's delaying-the-load-event flag to false. This stops delaying the load event.

    A user agent that is attempting to reduce network usage while still fetching the metadata for each media resource would also stop buffering at this point, following the rules described previously, which involve the networkState attribute switching to the NETWORK_IDLE value and a suspend event firing.

    The user agent is required to determine the duration of the media resource and go through this step before playing.

    Once the entire media resource has been fetched (but potentially before any of it has been decoded)

    Fire an event named progress at the media element.

    Set the networkState to NETWORK_IDLE and fire an event named suspend at the media element.

    If the user agent ever discards any media data and then needs to resume the network activity to obtain it again, then it must queue a media element task given the media element to set the networkState to NETWORK_LOADING.

    If the user agent can keep the media resource loaded, then the algorithm will continue to its final step below, which aborts the algorithm.

    If the connection is interrupted after some media data has been received, causing the user agent to give up trying to fetch the resource

    Fatal network errors that occur after the user agent has established whether the current media resource is usable (i.e. once the media element's readyState attribute is no longer HAVE_NOTHING) must cause the user agent to execute the following steps:

    1. The user agent should cancel the fetching process.

    2. Set the error attribute to the result of creating a MediaError with MEDIA_ERR_NETWORK.

    3. Set the element's networkState attribute to the NETWORK_IDLE value.

    4. Set the element's delaying-the-load-event flag to false. This stops delaying the load event.

    5. Fire an event named error at the media element.

    6. Abort the overall resource selection algorithm.

    If the media data is corrupted

    Fatal errors in decoding the media data that occur after the user agent has established whether the current media resource is usable (i.e. once the media element's readyState attribute is no longer HAVE_NOTHING) must cause the user agent to execute the following steps:

    1. The user agent should cancel the fetching process.

    2. Set the error attribute to the result of creating a MediaError with MEDIA_ERR_DECODE.

    3. Set the element's networkState attribute to the NETWORK_IDLE value.

    4. Set the element's delaying-the-load-event flag to false. This stops delaying the load event.

    5. Fire an event named error at the media element.

    6. Abort the overall resource selection algorithm.

    If the media data fetching process is aborted by the user

    The fetching process is aborted by the user, e.g. because the user pressed a "stop" button, the user agent must execute the following steps. These steps are not followed if the load() method itself is invoked while these steps are running, as the steps above handle that particular kind of abort.

    1. The user agent should cancel the fetching process.

    2. Set the error attribute to the result of creating a MediaError with MEDIA_ERR_ABORTED.

    3. Fire an event named abort at the media element.

    4. If the media element's readyState attribute has a value equal to HAVE_NOTHING, set the element's networkState attribute to the NETWORK_EMPTY value, set the element's show poster flag to true, and fire an event named emptied at the element.

      Otherwise, set the element's networkState attribute to the NETWORK_IDLE value.

    5. Set the element's delaying-the-load-event flag to false. This stops delaying the load event.

    6. Abort the overall resource selection algorithm.

    If the media data can be fetched but has non-fatal errors or uses, in part, codecs that are unsupported, preventing the user agent from rendering the content completely correctly but not preventing playback altogether

    The server returning data that is partially usable but cannot be optimally rendered must cause the user agent to render just the bits it can handle, and ignore the rest.

    If the media resource is found to declare a media-resource-specific text track that the user agent supports

    If the media data is CORS-same-origin, run the steps to expose a media-resource-specific text track with the relevant data.

    Cross-origin videos do not expose their subtitles, since that would allow attacks such as hostile sites reading subtitles from confidential videos on a user's intranet.

  5. Final step: If the user agent ever reaches this step (which can only happen if the entire resource gets loaded and kept available): abort the overall resource selection algorithm.

When a media element is to forget the media element's media-resource-specific tracks, the user agent must remove from the media element's list of text tracks all the media-resource-specific text tracks, then empty the media element's audioTracks attribute's AudioTrackList object, then empty the media element's videoTracks attribute's VideoTrackList object. No events (in particular, no removetrack events) are fired as part of this; the error and emptied events, fired by the algorithms that invoke this one, can be used instead.


The preload attribute is an enumerated attribute. The following table lists the keywords and states for the attribute — the keywords in the left column map to the states in the cell in the second column on the same row as the keyword. The attribute can be changed even once the media resource is being buffered or played; the descriptions in the table below are to be interpreted with that in mind.

Keyword State Brief description
none None Hints to the user agent that either the author does not expect the user to need the media resource, or that the server wants to minimize unnecessary traffic. This state does not provide a hint regarding how aggressively to actually download the media resource if buffering starts anyway (e.g. once the user hits "play").
metadata Metadata Hints to the user agent that the author does not expect the user to need the media resource, but that fetching the resource metadata (dimensions, track list, duration, etc), and maybe even the first few frames, is reasonable. If the user agent precisely fetches no more than the metadata, then the media element will end up with its readyState attribute set to HAVE_METADATA; typically though, some frames will be obtained as well and it will probably be HAVE_CURRENT_DATA or HAVE_FUTURE_DATA. When the media resource is playing, hints to the user agent that bandwidth is to be considered scarce, e.g. suggesting throttling the download so that the media data is obtained at the slowest possible rate that still maintains consistent playback.
auto Automatic Hints to the user agent that the user agent can put the user's needs first without risk to the server, up to and including optimistically downloading the entire resource.

The empty string is also a valid keyword, and maps to the Automatic state. The attribute's missing value default and invalid value default are implementation-defined, though the Metadata state is suggested as a compromise between reducing server load and providing an optimal user experience.

Authors might switch the attribute from "none" or "metadata" to "auto" dynamically once the user begins playback. For example, on a page with many videos this might be used to indicate that the many videos are not to be downloaded unless requested, but that once one is requested it is to be downloaded aggressively.

The preload attribute is intended to provide a hint to the user agent about what the author thinks will lead to the best user experience. The attribute may be ignored altogether, for example based on explicit user preferences or based on the available connectivity.

The preload IDL attribute must reflect the content attribute of the same name, limited to only known values.

The autoplay attribute can override the preload attribute (since if the media plays, it naturally has to buffer first, regardless of the hint given by the preload attribute). Including both is not an error, however.


media . buffered

HTMLMediaElement/buffered

Support in all current engines.

Firefox4+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns a TimeRanges object that represents the ranges of the media resource that the user agent has buffered.

The buffered attribute must return a new static normalized TimeRanges object that represents the ranges of the media resource, if any, that the user agent has buffered, at the time the attribute is evaluated. Users agents must accurately determine the ranges available, even for media streams where this can only be determined by tedious inspection.

Typically this will be a single range anchored at the zero point, but if, e.g. the user agent uses HTTP range requests in response to seeking, then there could be multiple ranges.

User agents may discard previously buffered data.

Thus, a time position included within a range of the objects return by the buffered attribute at one time can end up being not included in the range(s) of objects returned by the same attribute at later times.

Returning a new object each time is a bad pattern for attribute getters and is only enshrined here as it would be costly to change it. It is not to be copied to new APIs.

4.8.12.6 Offsets into the media resource
media . duration

HTMLMediaElement/duration

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the length of the media resource, in seconds, assuming that the start of the media resource is at time zero.

Returns NaN if the duration isn't available.

Returns Infinity for unbounded streams.

media . currentTime [ = value ]

HTMLMediaElement/currentTime

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the official playback position, in seconds.

Can be set, to seek to the given time.

A media resource has a media timeline that maps times (in seconds) to positions in the media resource. The origin of a timeline is its earliest defined position. The duration of a timeline is its last defined position.

Establishing the media timeline: if the media resource somehow specifies an explicit timeline whose origin is not negative (i.e. gives each frame a specific time offset and gives the first frame a zero or positive offset), then the media timeline should be that timeline. (Whether the media resource can specify a timeline or not depends on the media resource's format.) If the media resource specifies an explicit start time and date, then that time and date should be considered the zero point in the media timeline; the timeline offset will be the time and date, exposed using the getStartDate() method.

If the media resource has a discontinuous timeline, the user agent must extend the timeline used at the start of the resource across the entire resource, so that the media timeline of the media resource increases linearly starting from the earliest possible position (as defined below), even if the underlying media data has out-of-order or even overlapping time codes.

For example, if two clips have been concatenated into one video file, but the video format exposes the original times for the two clips, the video data might expose a timeline that goes, say, 00:15..00:29 and then 00:05..00:38. However, the user agent would not expose those times; it would instead expose the times as 00:15..00:29 and 00:29..01:02, as a single video.

(This is a tracking vector.) In the rare case of a media resource that does not have an explicit timeline, the zero time on the media timeline should correspond to the first frame of the media resource. In the even rarer case of a media resource with no explicit timings of any kind, not even frame durations, the user agent must itself determine the time for each frame in an implementation-defined manner.

An example of a file format with no explicit timeline but with explicit frame durations is the Animated GIF format. An example of a file format with no explicit timings at all is the JPEG-push format (multipart/x-mixed-replace with JPEG frames, often used as the format for MJPEG streams).

If, in the case of a resource with no timing information, the user agent will nonetheless be able to seek to an earlier point than the first frame originally provided by the server, then the zero time should correspond to the earliest seekable time of the media resource; otherwise, it should correspond to the first frame received from the server (the point in the media resource at which the user agent began receiving the stream).

At the time of writing, there is no known format that lacks explicit frame time offsets yet still supports seeking to a frame before the first frame sent by the server.

Consider a stream from a TV broadcaster, which begins streaming on a sunny Friday afternoon in October, and always sends connecting user agents the media data on the same media timeline, with its zero time set to the start of this stream. Months later, user agents connecting to this stream will find that the first frame they receive has a time with millions of seconds. The getStartDate() method would always return the date that the broadcast started; this would allow controllers to display real times in their scrubber (e.g. "2:30pm") rather than a time relative to when the broadcast began ("8 months, 4 hours, 12 minutes, and 23 seconds").

Consider a stream that carries a video with several concatenated fragments, broadcast by a server that does not allow user agents to request specific times but instead just streams the video data in a predetermined order, with the first frame delivered always being identified as the frame with time zero. If a user agent connects to this stream and receives fragments defined as covering timestamps 2010-03-20 23:15:00 UTC to 2010-03-21 00:05:00 UTC and 2010-02-12 14:25:00 UTC to 2010-02-12 14:35:00 UTC, it would expose this with a media timeline starting at 0s and extending to 3,600s (one hour). Assuming the streaming server disconnected at the end of the second clip, the duration attribute would then return 3,600. The getStartDate() method would return a Date object with a time corresponding to 2010-03-20 23:15:00 UTC. However, if a different user agent connected five minutes later, it would (presumably) receive fragments covering timestamps 2010-03-20 23:20:00 UTC to 2010-03-21 00:05:00 UTC and 2010-02-12 14:25:00 UTC to 2010-02-12 14:35:00 UTC, and would expose this with a media timeline starting at 0s and extending to 3,300s (fifty five minutes). In this case, the getStartDate() method would return a Date object with a time corresponding to 2010-03-20 23:20:00 UTC.

In both of these examples, the seekable attribute would give the ranges that the controller would want to actually display in its UI; typically, if the servers don't support seeking to arbitrary times, this would be the range of time from the moment the user agent connected to the stream up to the latest frame that the user agent has obtained; however, if the user agent starts discarding earlier information, the actual range might be shorter.

In any case, the user agent must ensure that the earliest possible position (as defined below) using the established media timeline, is greater than or equal to zero.

The media timeline also has an associated clock. Which clock is used is user-agent defined, and may be media resource-dependent, but it should approximate the user's wall clock.

Media elements have a current playback position, which must initially (i.e. in the absence of media data) be zero seconds. The current playback position is a time on the media timeline.

Media elements also have an official playback position, which must initially be set to zero seconds. The official playback position is an approximation of the current playback position that is kept stable while scripts are running.

Media elements also have a default playback start position, which must initially be set to zero seconds. This time is used to allow the element to be seeked even before the media is loaded.

Each media element has a show poster flag. When a media element is created, this flag must be set to true. This flag is used to control when the user agent is to show a poster frame for a video element instead of showing the video contents.

The currentTime attribute must, on getting, return the media element's default playback start position, unless that is zero, in which case it must return the element's official playback position. The returned value must be expressed in seconds. On setting, if the media element's readyState is HAVE_NOTHING, then it must set the media element's default playback start position to the new value; otherwise, it must set the official playback position to the new value and then seek to the new value. The new value must be interpreted as being in seconds.

If the media resource is a streaming resource, then the user agent might be unable to obtain certain parts of the resource after it has expired from its buffer. Similarly, some media resources might have a media timeline that doesn't start at zero. The earliest possible position is the earliest position in the stream or resource that the user agent can ever obtain again. It is also a time on the media timeline.

The earliest possible position is not explicitly exposed in the API; it corresponds to the start time of the first range in the seekable attribute's TimeRanges object, if any, or the current playback position otherwise.

When the earliest possible position changes, then: if the current playback position is before the earliest possible position, the user agent must seek to the earliest possible position; otherwise, if the user agent has not fired a timeupdate event at the element in the past 15 to 250ms and is not still running event handlers for such an event, then the user agent must queue a media element task given the media element to fire an event named timeupdate at the element.

Because of the above requirement and the requirement in the resource fetch algorithm that kicks in when the metadata of the clip becomes known, the current playback position can never be less than the earliest possible position.

If at any time the user agent learns that an audio or video track has ended and all media data relating to that track corresponds to parts of the media timeline that are before the earliest possible position, the user agent may queue a media element task given the media element to run these steps:

  1. Remove the track from the audioTracks attribute's AudioTrackList object or the videoTracks attribute's VideoTrackList object as appropriate.

  2. Fire an event named removetrack at the media element's aforementioned AudioTrackList or VideoTrackList object, using TrackEvent, with the track attribute initialized to the AudioTrack or VideoTrack object representing the track.

The duration attribute must return the time of the end of the media resource, in seconds, on the media timeline. If no media data is available, then the attributes must return the Not-a-Number (NaN) value. If the media resource is not known to be bounded (e.g. streaming radio, or a live event with no announced end time), then the attribute must return the positive Infinity value.

The user agent must determine the duration of the media resource before playing any part of the media data and before setting readyState to a value equal to or greater than HAVE_METADATA, even if doing so requires fetching multiple parts of the resource.

When the length of the media resource changes to a known value (e.g. from being unknown to known, or from a previously established length to a new length) the user agent must queue a media element task given the media element to fire an event named durationchange at the media element. (The event is not fired when the duration is reset as part of loading a new media resource.) If the duration is changed such that the current playback position ends up being greater than the time of the end of the media resource, then the user agent must also seek to the time of the end of the media resource.

If an "infinite" stream ends for some reason, then the duration would change from positive Infinity to the time of the last frame or sample in the stream, and the durationchange event would be fired. Similarly, if the user agent initially estimated the media resource's duration instead of determining it precisely, and later revises the estimate based on new information, then the duration would change and the durationchange event would be fired.

Some video files also have an explicit date and time corresponding to the zero time in the media timeline, known as the timeline offset. Initially, the timeline offset must be set to Not-a-Number (NaN).

The getStartDate() method must return a new Date object representing the current timeline offset.


The loop attribute is a boolean attribute that, if specified, indicates that the media element is to seek back to the start of the media resource upon reaching the end.

HTMLMediaElement/loop

Support in all current engines.

Firefox11+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android14+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The loop IDL attribute must reflect the content attribute of the same name.

4.8.12.7 Ready states
media . readyState

HTMLMediaElement/readyState

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns a value that expresses the current state of the element with respect to rendering the current playback position, from the codes in the list below.

Media elements have a ready state, which describes to what degree they are ready to be rendered at the current playback position. The possible values are as follows; the ready state of a media element at any particular time is the greatest value describing the state of the element:

HAVE_NOTHING (numeric value 0)

No information regarding the media resource is available. No data for the current playback position is available. Media elements whose networkState attribute are set to NETWORK_EMPTY are always in the HAVE_NOTHING state.

HAVE_METADATA (numeric value 1)

Enough of the resource has been obtained that the duration of the resource is available. In the case of a video element, the dimensions of the video are also available. No media data is available for the immediate current playback position.

HAVE_CURRENT_DATA (numeric value 2)

Data for the immediate current playback position is available, but either not enough data is available that the user agent could successfully advance the current playback position in the direction of playback at all without immediately reverting to the HAVE_METADATA state, or there is no more data to obtain in the direction of playback. For example, in video this corresponds to the user agent having data from the current frame, but not the next frame, when the current playback position is at the end of the current frame; and to when playback has ended.

HAVE_FUTURE_DATA (numeric value 3)

Data for the immediate current playback position is available, as well as enough data for the user agent to advance the current playback position in the direction of playback at least a little without immediately reverting to the HAVE_METADATA state, and the text tracks are ready. For example, in video this corresponds to the user agent having data for at least the current frame and the next frame when the current playback position is at the instant in time between the two frames, or to the user agent having the video data for the current frame and audio data to keep playing at least a little when the current playback position is in the middle of a frame. The user agent cannot be in this state if playback has ended, as the current playback position can never advance in this case.

HAVE_ENOUGH_DATA (numeric value 4)

All the conditions described for the HAVE_FUTURE_DATA state are met, and, in addition, either of the following conditions is also true:

In practice, the difference between HAVE_METADATA and HAVE_CURRENT_DATA is negligible. Really the only time the difference is relevant is when painting a video element onto a canvas, where it distinguishes the case where something will be drawn (HAVE_CURRENT_DATA or greater) from the case where nothing is drawn (HAVE_METADATA or less). Similarly, the difference between HAVE_CURRENT_DATA (only the current frame) and HAVE_FUTURE_DATA (at least this frame and the next) can be negligible (in the extreme, only one frame). The only time that distinction really matters is when a page provides an interface for "frame-by-frame" navigation.

When the ready state of a media element whose networkState is not NETWORK_EMPTY changes, the user agent must follow the steps given below:

  1. Apply the first applicable set of substeps from the following list:

    If the previous ready state was HAVE_NOTHING, and the new ready state is HAVE_METADATA

    Queue a media element task given the media element to fire an event named loadedmetadata at the element.

    Before this task is run, as part of the event loop mechanism, the rendering will have been updated to resize the video element if appropriate.

    If the previous ready state was HAVE_METADATA and the new ready state is HAVE_CURRENT_DATA or greater

    If this is the first time this occurs for this media element since the load() algorithm was last invoked, the user agent must queue a media element task given the media element to fire an event named loadeddata at the element.

    If the new ready state is HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA, then the relevant steps below must then be run also.

    If the previous ready state was HAVE_FUTURE_DATA or more, and the new ready state is HAVE_CURRENT_DATA or less

    If the media element was potentially playing before its readyState attribute changed to a value lower than HAVE_FUTURE_DATA, and the element has not ended playback, and playback has not stopped due to errors, paused for user interaction, or paused for in-band content, the user agent must queue a media element task given the media element to fire an event named timeupdate at the element, and queue a media element task given the media element to fire an event named waiting at the element.

    If the previous ready state was HAVE_CURRENT_DATA or less, and the new ready state is HAVE_FUTURE_DATA

    The user agent must queue a media element task given the media element to fire an event named canplay at the element.

    If the element's paused attribute is false, the user agent must notify about playing for the element.

    If the new ready state is HAVE_ENOUGH_DATA

    If the previous ready state was HAVE_CURRENT_DATA or less, the user agent must queue a media element task given the media element to fire an event named canplay at the element, and, if the element's paused attribute is false, notify about playing for the element.

    The user agent must queue a media element task given the media element to fire an event named canplaythrough at the element.

    If the element is not eligible for autoplay, then the user agent must abort these substeps.

    The user agent may run the following substeps:

    1. Set the paused attribute to false.
    2. If the element's show poster flag is true, set it to false and run the time marches on steps.
    3. Queue a media element task given the element to fire an event named play at the element.
    4. Notify about playing for the element.

    Alternatively, if the element is a video element, the user agent may start observing whether the element intersects the viewport. When the element starts intersecting the viewport, if the element is still eligible for autoplay, run the substeps above. Optionally, when the element stops intersecting the viewport, if the can autoplay flag is still true and the autoplay attribute is still specified, run the following substeps:

    1. Run the internal pause steps and set the can autoplay flag to true.
    2. Queue a media element task given the element to fire an event named pause at the element.

    The substeps for playing and pausing can run multiple times as the element starts or stops intersecting the viewport, as long as the can autoplay flag is true.

    User agents do not need to support autoplay, and it is suggested that user agents honor user preferences on the matter. Authors are urged to use the autoplay attribute rather than using script to force the video to play, so as to allow the user to override the behavior if so desired.

It is possible for the ready state of a media element to jump between these states discontinuously. For example, the state of a media element can jump straight from HAVE_METADATA to HAVE_ENOUGH_DATA without passing through the HAVE_CURRENT_DATA and HAVE_FUTURE_DATA states.

The readyState IDL attribute must, on getting, return the value described above that describes the current ready state of the media element.

The autoplay attribute is a boolean attribute. When present, the user agent (as described in the algorithm described herein) will automatically begin playback of the media resource as soon as it can do so without stopping.

Authors are urged to use the autoplay attribute rather than using script to trigger automatic playback, as this allows the user to override the automatic playback when it is not desired, e.g. when using a screen reader. Authors are also encouraged to consider not using the automatic playback behavior at all, and instead to let the user agent wait for the user to start playback explicitly.

HTMLMediaElement/autoplay

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The autoplay IDL attribute must reflect the content attribute of the same name.

4.8.12.8 Playing the media resource
media . paused

HTMLMediaElement/paused

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns true if playback is paused; false otherwise.

media . ended

HTMLMediaElement/ended

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns true if playback has reached the end of the media resource.

media . defaultPlaybackRate [ = value ]

HTMLMediaElement/defaultPlaybackRate

Support in all current engines.

Firefox20+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android20+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the default rate of playback, for when the user is not fast-forwarding or reversing through the media resource.

Can be set, to change the default rate of playback.

The default rate has no direct effect on playback, but if the user switches to a fast-forward mode, when they return to the normal playback mode, it is expected that the rate of playback will be returned to the default rate of playback.

media . playbackRate [ = value ]

HTMLMediaElement/playbackRate

Support in all current engines.

Firefox20+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android20+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the current rate playback, where 1.0 is normal speed.

Can be set, to change the rate of playback.

media . preservesPitch

HTMLMediaElement/preservesPitch

Firefox101+Safari🔰 4+Chrome86+
Opera72+Edge86+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android101+Safari iOS🔰 4+Chrome Android86+WebView Android86+Samsung Internet14.0+Opera Android61+

Returns true if pitch-preserving algorithms are used when the playbackRate is not 1.0. The default value is true.

Can be set to false to have the media resource's audio pitch change up or down depending on the playbackRate. This is useful for aesthetic and performance reasons.

media . played

Returns a TimeRanges object that represents the ranges of the media resource that the user agent has played.

media . play()

HTMLMediaElement/play

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

Sets the paused attribute to false, loading the media resource and beginning playback if necessary. If the playback had ended, will restart it from the start.

media . pause()

HTMLMediaElement/pause

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Sets the paused attribute to true, loading the media resource if necessary.

The paused attribute represents whether the media element is paused or not. The attribute must initially be true.

A media element is a blocked media element if its readyState attribute is in the HAVE_NOTHING state, the HAVE_METADATA state, or the HAVE_CURRENT_DATA state, or if the element has paused for user interaction or paused for in-band content.

A media element is said to be potentially playing when its paused attribute is false, the element has not ended playback, playback has not stopped due to errors, and the element is not a blocked media element.

A waiting DOM event can be fired as a result of an element that is potentially playing stopping playback due to its readyState attribute changing to a value lower than HAVE_FUTURE_DATA.

A media element is said to be eligible for autoplay when all of the following conditions are met:

A media element is said to be allowed to play if the user agent and the system allow media playback in the current context.

For example, a user agent could allow playback only when the media element's Window object has transient activation, but an exception could be made to allow playback while muted.

A media element is said to have ended playback when:

The ended attribute must return true if, the last time the event loop reached step 1, the media element had ended playback and the direction of playback was forwards, and false otherwise.

A media element is said to have stopped due to errors when the element's readyState attribute is HAVE_METADATA or greater, and the user agent encounters a non-fatal error during the processing of the media data, and due to that error, is not able to play the content at the current playback position.

A media element is said to have paused for user interaction when its paused attribute is false, the readyState attribute is either HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA and the user agent has reached a point in the media resource where the user has to make a selection for the resource to continue.

It is possible for a media element to have both ended playback and paused for user interaction at the same time.

When a media element that is potentially playing stops playing because it has paused for user interaction, the user agent must queue a media element task given the media element to fire an event named timeupdate at the element.

A media element is said to have paused for in-band content when its paused attribute is false, the readyState attribute is either HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA and the user agent has suspended playback of the media resource in order to play content that is temporally anchored to the media resource and has a nonzero length, or to play content that is temporally anchored to a segment of the media resource but has a length longer than that segment.

One example of when a media element would be paused for in-band content is when the user agent is playing audio descriptions from an external WebVTT file, and the synthesized speech generated for a cue is longer than the time between the text track cue start time and the text track cue end time.


When the current playback position reaches the end of the media resource when the direction of playback is forwards, then the user agent must follow these steps:

  1. If the media element has a loop attribute specified, then seek to the earliest possible position of the media resource and return.

  2. As defined above, the ended IDL attribute starts returning true once the event loop returns to step 1.

  3. Queue a media element task given the media element and the following steps:

    1. Fire an event named timeupdate at the media element.

    2. If the media element has ended playback, the direction of playback is forwards, and paused is false, then:

      1. Set the paused attribute to true.

      2. Fire an event named pause at the media element.

      3. Take pending play promises and reject pending play promises with the result and an "AbortError" DOMException.

    3. Fire an event named ended at the media element.

When the current playback position reaches the earliest possible position of the media resource when the direction of playback is backwards, then the user agent must only queue a media element task given the media element to fire an event named timeupdate at the element.

The word "reaches" here does not imply that the current playback position needs to have changed during normal playback; it could be via seeking, for instance.


The defaultPlaybackRate attribute gives the desired speed at which the media resource is to play, as a multiple of its intrinsic speed. The attribute is mutable: on getting it must return the last value it was set to, or 1.0 if it hasn't yet been set; on setting the attribute must be set to the new value.

The defaultPlaybackRate is used by the user agent when it exposes a user interface to the user.

The playbackRate attribute gives the effective playback rate, which is the speed at which the media resource plays, as a multiple of its intrinsic speed. If it is not equal to the defaultPlaybackRate, then the implication is that the user is using a feature such as fast forward or slow motion playback. The attribute is mutable: on getting it must return the last value it was set to, or 1.0 if it hasn't yet been set; on setting, the user agent must follow these steps:

  1. If the given value is not supported by the user agent, then throw a "NotSupportedError" DOMException.

  2. Set playbackRate to the new value, and if the element is potentially playing, change the playback speed.

When the defaultPlaybackRate or playbackRate attributes change value (either by being set by script or by being changed directly by the user agent, e.g. in response to user control) the user agent must queue a media element task given the media element to fire an event named ratechange at the media element. The user agent must process attribute changes smoothly and must not introduce any perceivable gaps or muting of playback in response.

The preservesPitch getter steps are to return true if a pitch-preserving algorithm is in effect during playback. The setter steps are to correspondingly switch the pitch-preserving algorithm on or off, without any perceivable gaps or muting of playback. By default, such a pitch-preserving algorithm must be in effect (i.e., the getter will initially return true).


The played attribute must return a new static normalized TimeRanges object that represents the ranges of points on the media timeline of the media resource reached through the usual monotonic increase of the current playback position during normal playback, if any, at the time the attribute is evaluated.

Returning a new object each time is a bad pattern for attribute getters and is only enshrined here as it would be costly to change it. It is not to be copied to new APIs.


Each media element has a list of pending play promises, which must initially be empty.

To take pending play promises for a media element, the user agent must run the following steps:

  1. Let promises be an empty list of promises.

  2. Copy the media element's list of pending play promises to promises.

  3. Clear the media element's list of pending play promises.

  4. Return promises.

To resolve pending play promises for a media element with a list of promises promises, the user agent must resolve each promise in promises with undefined.

To reject pending play promises for a media element with a list of promise promises and an exception name error, the user agent must reject each promise in promises with error.

To notify about playing for a media element, the user agent must run the following steps:

  1. Take pending play promises and let promises be the result.

  2. Queue a media element task given the element and the following steps:

    1. Fire an event named playing at the element.

    2. Resolve pending play promises with promises.

When the play() method on a media element is invoked, the user agent must run the following steps.

  1. If the media element is not allowed to play, return a promise rejected with a "NotAllowedError" DOMException.

  2. If the media element's error attribute is not null and its code is MEDIA_ERR_SRC_NOT_SUPPORTED, return a promise rejected with a "NotSupportedError" DOMException.

    This means that the dedicated media source failure steps have run. Playback is not possible until the media element load algorithm clears the error attribute.

  3. Let promise be a new promise and append promise to the list of pending play promises.

  4. Run the internal play steps for the media element.

  5. Return promise.

The internal play steps for a media element are as follows:

  1. If the media element's networkState attribute has the value NETWORK_EMPTY, invoke the media element's resource selection algorithm.

  2. If the playback has ended and the direction of playback is forwards, seek to the earliest possible position of the media resource.

    This will cause the user agent to queue a media element task given the media element to fire an event named timeupdate at the media element.

  3. If the media element's paused attribute is true, then:

    1. Change the value of paused to false.

    2. If the show poster flag is true, set the element's show poster flag to false and run the time marches on steps.

    3. Queue a media element task given the media element to fire an event named play at the element.

    4. If the media element's readyState attribute has the value HAVE_NOTHING, HAVE_METADATA, or HAVE_CURRENT_DATA, queue a media element task given the media element to fire an event named waiting at the element.

      Otherwise, the media element's readyState attribute has the value HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA: notify about playing for the element.

  4. Otherwise, if the media element's readyState attribute has the value HAVE_FUTURE_DATA or HAVE_ENOUGH_DATA, take pending play promises and queue a media element task given the media element to resolve pending play promises with the result.

    The media element is already playing. However, it's possible that promise will be rejected before the queued task is run.

  5. Set the media element's can autoplay flag to false.


When the pause() method is invoked, and when the user agent is required to pause the media element, the user agent must run the following steps:

  1. If the media element's networkState attribute has the value NETWORK_EMPTY, invoke the media element's resource selection algorithm.

  2. Run the internal pause steps for the media element.

The internal pause steps for a media element are as follows:

  1. Set the media element's can autoplay flag to false.

  2. If the media element's paused attribute is false, run the following steps:

    1. Change the value of paused to true.

    2. Take pending play promises and let promises be the result.

    3. Queue a media element task on the given the media element and the following steps:

      1. Fire an event named timeupdate at the element.

      2. Fire an event named pause at the element.

      3. Reject pending play promises with promises and an "AbortError" DOMException.

    4. Set the official playback position to the current playback position.


If the element's playbackRate is positive or zero, then the direction of playback is forwards. Otherwise, it is backwards.

When a media element is potentially playing and its Document is a fully active Document, its current playback position must increase monotonically at the element's playbackRate units of media time per unit time of the media timeline's clock. (This specification always refers to this as an increase, but that increase could actually be a decrease if the element's playbackRate is negative.)

The element's playbackRate can be 0.0, in which case the current playback position doesn't move, despite playback not being paused (paused doesn't become true, and the pause event doesn't fire).

This specification doesn't define how the user agent achieves the appropriate playback rate — depending on the protocol and media available, it is plausible that the user agent could negotiate with the server to have the server provide the media data at the appropriate rate, so that (except for the period between when the rate is changed and when the server updates the stream's playback rate) the client doesn't actually have to drop or interpolate any frames.

Any time the user agent provides a stable state, the official playback position must be set to the current playback position.

While the direction of playback is backwards, any corresponding audio must be muted. While the element's playbackRate is so low or so high that the user agent cannot play audio usefully, the corresponding audio must also be muted. If the element's playbackRate is not 1.0 and preservesPitch is true, the user agent must apply pitch adjustment to preserve the original pitch of the audio. Otherwise, the user agent must speed up or slow down the audio without any pitch adjustment.

When a media element is potentially playing, its audio data played must be synchronized with the current playback position, at the element's effective media volume. The user agent must play the audio from audio tracks that were enabled when the event loop last reached step 1.

When a media element is not potentially playing, audio must not play for the element.

Media elements that are potentially playing while not in a document must not play any video, but should play any audio component. Media elements must not stop playing just because all references to them have been removed; only once a media element is in a state where no further audio could ever be played by that element may the element be garbage collected.

It is possible for an element to which no explicit references exist to play audio, even if such an element is not still actively playing: for instance, it could be unpaused but stalled waiting for content to buffer, or it could be still buffering, but with a suspend event listener that begins playback. Even a media element whose media resource has no audio tracks could eventually play audio again if it had an event listener that changes the media resource.


Each media element has a list of newly introduced cues, which must be initially empty. Whenever a text track cue is added to the list of cues of a text track that is in the list of text tracks for a media element, that cue must be added to the media element's list of newly introduced cues. Whenever a text track is added to the list of text tracks for a media element, all of the cues in that text track's list of cues must be added to the media element's list of newly introduced cues. When a media element's list of newly introduced cues has new cues added while the media element's show poster flag is not set, then the user agent must run the time marches on steps.

When a text track cue is removed from the list of cues of a text track that is in the list of text tracks for a media element, and whenever a text track is removed from the list of text tracks of a media element, if the media element's show poster flag is not set, then the user agent must run the time marches on steps.

When the current playback position of a media element changes (e.g. due to playback or seeking), the user agent must run the time marches on steps. To support use cases that depend on the timing accuracy of cue event firing, such as synchronizing captions with shot changes in a video, user agents should fire cue events as close as possible to their position on the media timeline, and ideally within 20 milliseconds. If the current playback position changes while the steps are running, then the user agent must wait for the steps to complete, and then must immediately rerun the steps. These steps are thus run as often as possible or needed.

If one iteration takes a long time, this can cause short duration cues to be skipped over as the user agent rushes ahead to "catch up", so these cues will not appear in the activeCues list.

The time marches on steps are as follows:

  1. Let current cues be a list of cues, initialized to contain all the cues of all the hidden or showing text tracks of the media element (not the disabled ones) whose start times are less than or equal to the current playback position and whose end times are greater than the current playback position.

  2. Let other cues be a list of cues, initialized to contain all the cues of hidden and showing text tracks of the media element that are not present in current cues.

  3. Let last time be the current playback position at the time this algorithm was last run for this media element, if this is not the first time it has run.

  4. If the current playback position has, since the last time this algorithm was run, only changed through its usual monotonic increase during normal playback, then let missed cues be the list of cues in other cues whose start times are greater than or equal to last time and whose end times are less than or equal to the current playback position. Otherwise, let missed cues be an empty list.

  5. Remove all the cues in missed cues that are also in the media element's list of newly introduced cues, and then empty the element's list of newly introduced cues.

  6. If the time was reached through the usual monotonic increase of the current playback position during normal playback, and if the user agent has not fired a timeupdate event at the element in the past 15 to 250ms and is not still running event handlers for such an event, then the user agent must queue a media element task given the media element to fire an event named timeupdate at the element. (In the other cases, such as explicit seeks, relevant events get fired as part of the overall process of changing the current playback position.)

    The event thus is not to be fired faster than about 66Hz or slower than 4Hz (assuming the event handlers don't take longer than 250ms to run). User agents are encouraged to vary the frequency of the event based on the system load and the average cost of processing the event each time, so that the UI updates are not any more frequent than the user agent can comfortably handle while decoding the video.

  7. If all of the cues in current cues have their text track cue active flag set, none of the cues in other cues have their text track cue active flag set, and missed cues is empty, then return.

  8. If the time was reached through the usual monotonic increase of the current playback position during normal playback, and there are cues in other cues that have their text track cue pause-on-exit flag set and that either have their text track cue active flag set or are also in missed cues, then immediately pause the media element.

    In the other cases, such as explicit seeks, playback is not paused by going past the end time of a cue, even if that cue has its text track cue pause-on-exit flag set.

  9. Let events be a list of tasks, initially empty. Each task in this list will be associated with a text track, a text track cue, and a time, which are used to sort the list before the tasks are queued.

    Let affected tracks be a list of text tracks, initially empty.

    When the steps below say to prepare an event named event for a text track cue target with a time time, the user agent must run these steps:

    1. Let track be the text track with which the text track cue target is associated.

    2. Create a task to fire an event named event at target.

    3. Add the newly created task to events, associated with the time time, the text track track, and the text track cue target.

    4. Add track to affected tracks.

  10. For each text track cue in missed cues, prepare an event named enter for the TextTrackCue object with the text track cue start time.

  11. For each text track cue in other cues that either has its text track cue active flag set or is in missed cues, prepare an event named exit for the TextTrackCue object with the later of the text track cue end time and the text track cue start time.

  12. For each text track cue in current cues that does not have its text track cue active flag set, prepare an event named enter for the TextTrackCue object with the text track cue start time.

  13. Sort the tasks in events in ascending time order (tasks with earlier times first).

    Further sort tasks in events that have the same time by the relative text track cue order of the text track cues associated with these tasks.

    Finally, sort tasks in events that have the same time and same text track cue order by placing tasks that fire enter events before those that fire exit events.

  14. Queue a media element task given the media element for each task in events, in list order.

  15. Sort affected tracks in the same order as the text tracks appear in the media element's list of text tracks, and remove duplicates.

  16. For each text track in affected tracks, in the list order, queue a media element task given the media element to fire an event named cuechange at the TextTrack object, and, if the text track has a corresponding track element, to then fire an event named cuechange at the track element as well.

  17. Set the text track cue active flag of all the cues in the current cues, and unset the text track cue active flag of all the cues in the other cues.

  18. Run the rules for updating the text track rendering of each of the text tracks in affected tracks that are showing, providing the text track's text track language as the fallback language if it is not the empty string. For example, for text tracks based on WebVTT, the rules for updating the display of WebVTT text tracks. [WEBVTT]

For the purposes of the algorithm above, a text track cue is considered to be part of a text track only if it is listed in the text track list of cues, not merely if it is associated with the text track.

If the media element's node document stops being a fully active document, then the playback will stop until the document is active again.

When a media element is removed from a Document, the user agent must run the following steps:

  1. Await a stable state, allowing the task that removed the media element from the Document to continue. The synchronous section consists of all the remaining steps of this algorithm. (Steps in the synchronous section are marked with ⌛.)

  2. ⌛ If the media element is in a document, return.

  3. ⌛ Run the internal pause steps for the media element.

4.8.12.9 Seeking
media . seeking

Returns true if the user agent is currently seeking.

media . seekable

HTMLMediaElement/seekable

Support in all current engines.

Firefox8+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android8+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns a TimeRanges object that represents the ranges of the media resource to which it is possible for the user agent to seek.

media . fastSeek( time )

HTMLMediaElement/fastSeek

Firefox31+Safari8+ChromeNo
OperaNoEdgeNo
Edge (Legacy)NoInternet ExplorerNo
Firefox Android31+Safari iOS8+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo

Seeks to near the given time as fast as possible, trading precision for speed. (To seek to a precise time, use the currentTime attribute.)

This does nothing if the media resource has not been loaded.

The seeking attribute must initially have the value false.

The fastSeek() method must seek to the time given by the method's argument, with the approximate-for-speed flag set.

When the user agent is required to seek to a particular new playback position in the media resource, optionally with the approximate-for-speed flag set, it means that the user agent must run the following steps. This algorithm interacts closely with the event loop mechanism; in particular, it has a synchronous section (which is triggered as part of the event loop algorithm). Steps in that section are marked with ⌛.

  1. Set the media element's show poster flag to false.

  2. If the media element's readyState is HAVE_NOTHING, return.

  3. If the element's seeking IDL attribute is true, then another instance of this algorithm is already running. Abort that other instance of the algorithm without waiting for the step that it is running to complete.

  4. Set the seeking IDL attribute to true.

  5. If the seek was in response to a DOM method call or setting of an IDL attribute, then continue the script. The remainder of these steps must be run in parallel. With the exception of the steps marked with ⌛, they could be aborted at any time by another instance of this algorithm being invoked.

  6. If the new playback position is later than the end of the media resource, then let it be the end of the media resource instead.

  7. If the new playback position is less than the earliest possible position, let it be that position instead.

  8. If the (possibly now changed) new playback position is not in one of the ranges given in the seekable attribute, then let it be the position in one of the ranges given in the seekable attribute that is the nearest to the new playback position. If two positions both satisfy that constraint (i.e. the new playback position is exactly in the middle between two ranges in the seekable attribute) then use the position that is closest to the current playback position. If there are no ranges given in the seekable attribute then set the seeking IDL attribute to false and return.

  9. If the approximate-for-speed flag is set, adjust the new playback position to a value that will allow for playback to resume promptly. If new playback position before this step is before current playback position, then the adjusted new playback position must also be before the current playback position. Similarly, if the new playback position before this step is after current playback position, then the adjusted new playback position must also be after the current playback position.

    For example, the user agent could snap to a nearby key frame, so that it doesn't have to spend time decoding then discarding intermediate frames before resuming playback.

  10. Queue a media element task given the media element to fire an event named seeking at the element.

  11. Set the current playback position to the new playback position.

    If the media element was potentially playing immediately before it started seeking, but seeking caused its readyState attribute to change to a value lower than HAVE_FUTURE_DATA, then a waiting event will be fired at the element.

    This step sets the current playback position, and thus can immediately trigger other conditions, such as the rules regarding when playback "reaches the end of the media resource" (part of the logic that handles looping), even before the user agent is actually able to render the media data for that position (as determined in the next step).

    The currentTime attribute returns the official playback position, not the current playback position, and therefore gets updated before script execution, separate from this algorithm.

  12. Wait until the user agent has established whether or not the media data for the new playback position is available, and, if it is, until it has decoded enough data to play back that position.

  13. Await a stable state. The synchronous section consists of all the remaining steps of this algorithm. (Steps in the synchronous section are marked with ⌛.)

  14. ⌛ Set the seeking IDL attribute to false.

  15. ⌛ Run the time marches on steps.

  16. Queue a media element task given the media element to fire an event named timeupdate at the element.

  17. Queue a media element task given the media element to fire an event named seeked at the element.


The seekable attribute must return a new static normalized TimeRanges object that represents the ranges of the media resource, if any, that the user agent is able to seek to, at the time the attribute is evaluated.

If the user agent can seek to anywhere in the media resource, e.g. because it is a simple movie file and the user agent and the server support HTTP Range requests, then the attribute would return an object with one range, whose start is the time of the first frame (the earliest possible position, typically zero), and whose end is the same as the time of the first frame plus the duration attribute's value (which would equal the time of the last frame, and might be positive Infinity).

The range might be continuously changing, e.g. if the user agent is buffering a sliding window on an infinite stream. This is the behavior seen with DVRs viewing live TV, for instance.

Returning a new object each time is a bad pattern for attribute getters and is only enshrined here as it would be costly to change it. It is not to be copied to new APIs.

User agents should adopt a very liberal and optimistic view of what is seekable. User agents should also buffer recent content where possible to enable seeking to be fast.

For instance, consider a large video file served on an HTTP server without support for HTTP Range requests. A browser could implement this by only buffering the current frame and data obtained for subsequent frames, never allow seeking, except for seeking to the very start by restarting the playback. However, this would be a poor implementation. A high quality implementation would buffer the last few minutes of content (or more, if sufficient storage space is available), allowing the user to jump back and rewatch something surprising without any latency, and would in addition allow arbitrary seeking by reloading the file from the start if necessary, which would be slower but still more convenient than having to literally restart the video and watch it all the way through just to get to an earlier unbuffered spot.

Media resources might be internally scripted or interactive. Thus, a media element could play in a non-linear fashion. If this happens, the user agent must act as if the algorithm for seeking was used whenever the current playback position changes in a discontinuous fashion (so that the relevant events fire).

4.8.12.10 多媒体轨道的媒体资源

媒体资源 可以内嵌多个音视频轨道。例如, 除了主音视频轨道外,媒体资源 可以有外语配音的对话, 导演评论,语音描述,另外的拍摄角度,符号语言,或者手语叠加层。

media . audioTracks

HTMLMediaElement/audioTracks

Support in all current engines.

Firefox🔰 33+Safari8+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS8+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

返回一个表示该 媒体资源 可用的 音频轨道的 AudioTrackList 对象。

media . videoTracks

HTMLMediaElement/videoTracks

Support in all current engines.

Firefox🔰 33+Safari8+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS8+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

返回一个表示该 媒体资源 可用的 视频轨道的 AudioTrackList 对象。

媒体元素audioTracks 属性必须返回 活的 AudioTrackList 对象,表示 在 媒体元素媒体资源 中可用的音频轨道。

媒体元素videoTracks 属性必须返回 活的 VideoTrackList 对象,表示 在 媒体元素媒体资源 中可用的视频轨道。

每个 媒体元素 永远都只有一个 AudioTrackList 对象和一个 VideoTrackList 对象, 即使元素中加载了另一个 媒体资源: 这两个对象会被复用。(但 AudioTrackVideoTrack 对象不会。)

4.8.12.10.1 AudioTrackList and VideoTrackList objects

AudioTrackList

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

VideoTrackList

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

AudioTrackList

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
caniuse.com table

The AudioTrackList and VideoTrackList interfaces are used by attributes defined in the previous section.

AudioTrack

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

VideoTrack

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
[Exposed=Window]
interface AudioTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter AudioTrack (unsigned long index);
  AudioTrack? getTrackById(DOMString id);

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};

[Exposed=Window]
interface AudioTrack {
  readonly attribute DOMString id;
  readonly attribute DOMString kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;
  attribute boolean enabled;
};

[Exposed=Window]
interface VideoTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter VideoTrack (unsigned long index);
  VideoTrack? getTrackById(DOMString id);
  readonly attribute long selectedIndex;

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};

[Exposed=Window]
interface VideoTrack {
  readonly attribute DOMString id;
  readonly attribute DOMString kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;
  attribute boolean selected;
};
media . audioTracks . length

AudioTrackList/length

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
media . videoTracks . length

VideoTrackList/length

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

Returns the number of tracks in the list.

audioTrack = media . audioTracks[index]
videoTrack = media . videoTracks[index]

Returns the specified AudioTrack or VideoTrack object.

audioTrack = media . audioTracks . getTrackById( id )

AudioTrackList/getTrackById

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
videoTrack = media . videoTracks . getTrackById( id )

VideoTrackList/getTrackById

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

Returns the AudioTrack or VideoTrack object with the given identifier, or null if no track has that identifier.

audioTrack . id

AudioTrack/id

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
videoTrack . id

VideoTrack/id

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

Returns the ID of the given track. This is the ID that can be used with a fragment if the format supports media fragment syntax, and that can be used with the getTrackById() method.

audioTrack . kind

AudioTrack/kind

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
videoTrack . kind

VideoTrack/kind

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

Returns the category the given track falls into. The possible track categories are given below.

audioTrack . label

AudioTrack/label

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
videoTrack . label

VideoTrack/label

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

Returns the label of the given track, if known, or the empty string otherwise.

audioTrack . language

AudioTrack/language

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
videoTrack . language

VideoTrack/language

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

Returns the language of the given track, if known, or the empty string otherwise.

audioTrack . enabled [ = value ]

AudioTrack/enabled

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

Returns true if the given track is active, and false otherwise.

Can be set, to change whether the track is enabled or not. If multiple audio tracks are enabled simultaneously, they are mixed.

media . videoTracks . selectedIndex

VideoTrackList/selectedIndex

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

Returns the index of the currently selected track, if any, or −1 otherwise.

videoTrack . selected [ = value ]

VideoTrack/selected

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

Returns true if the given track is active, and false otherwise.

Can be set, to change whether the track is selected or not. Either zero or one video track is selected; selecting a new track while a previous one is selected will unselect the previous one.

An AudioTrackList object represents a dynamic list of zero or more audio tracks, of which zero or more can be enabled at a time. Each audio track is represented by an AudioTrack object.

A VideoTrackList object represents a dynamic list of zero or more video tracks, of which zero or one can be selected at a time. Each video track is represented by a VideoTrack object.

Tracks in AudioTrackList and VideoTrackList objects must be consistently ordered. If the media resource is in a format that defines an order, then that order must be used; otherwise, the order must be the relative order in which the tracks are declared in the media resource. The order used is called the natural order of the list.

Each track in one of these objects thus has an index; the first has the index 0, and each subsequent track is numbered one higher than the previous one. If a media resource dynamically adds or removes audio or video tracks, then the indices of the tracks will change dynamically. If the media resource changes entirely, then all the previous tracks will be removed and replaced with new tracks.

The AudioTrackList length and VideoTrackList length attribute getters must return the number of tracks represented by their objects at the time of getting.

The supported property indices of AudioTrackList and VideoTrackList objects at any instant are the numbers from zero to the number of tracks represented by the respective object minus one, if any tracks are represented. If an AudioTrackList or VideoTrackList object represents no tracks, it has no supported property indices.

To determine the value of an indexed property for a given index index in an AudioTrackList or VideoTrackList object list, the user agent must return the AudioTrack or VideoTrack object that represents the indexth track in list.

The AudioTrackList getTrackById(id) and VideoTrackList getTrackById(id) methods must return the first AudioTrack or VideoTrack object (respectively) in the AudioTrackList or VideoTrackList object (respectively) whose identifier is equal to the value of the id argument (in the natural order of the list, as defined above). When no tracks match the given argument, the methods must return null.

The AudioTrack and VideoTrack objects represent specific tracks of a media resource. Each track can have an identifier, category, label, and language. These aspects of a track are permanent for the lifetime of the track; even if a track is removed from a media resource's AudioTrackList or VideoTrackList objects, those aspects do not change.

In addition, AudioTrack objects can each be enabled or disabled; this is the audio track's enabled state. When an AudioTrack is created, its enabled state must be set to false (disabled). The resource fetch algorithm can override this.

Similarly, a single VideoTrack object per VideoTrackList object can be selected, this is the video track's selection state. When a VideoTrack is created, its selection state must be set to false (not selected). The resource fetch algorithm can override this.

The AudioTrack id and VideoTrack id attributes must return the identifier of the track, if it has one, or the empty string otherwise. If the media resource is in a format that supports media fragment syntax, the identifier returned for a particular track must be the same identifier that would enable the track if used as the name of a track in the track dimension of such a fragment. [INBAND]

For example, in Ogg files, this would be the Name header field of the track. [OGGSKELETONHEADERS]

The AudioTrack kind and VideoTrack kind attributes must return the category of the track, if it has one, or the empty string otherwise.

The category of a track is the string given in the first column of the table below that is the most appropriate for the track based on the definitions in the table's second and third columns, as determined by the metadata included in the track in the media resource. The cell in the third column of a row says what the category given in the cell in the first column of that row applies to; a category is only appropriate for an audio track if it applies to audio tracks, and a category is only appropriate for video tracks if it applies to video tracks. Categories must only be returned for AudioTrack objects if they are appropriate for audio, and must only be returned for VideoTrack objects if they are appropriate for video.

For Ogg files, the Role header field of the track gives the relevant metadata. For DASH media resources, the Role element conveys the information. For WebM, only the FlagDefault element currently maps to a value. Sourcing In-band Media Resource Tracks from Media Containers into HTML has further details. [OGGSKELETONHEADERS] [DASH] [WEBMCG] [INBAND]

Return values for AudioTrack's kind and VideoTrack's kind
Category Definition Applies to...Examples
"alternative" A possible alternative to the main track, e.g. a different take of a song (audio), or a different angle (video). Audio and video. Ogg: "audio/alternate" or "video/alternate"; DASH: "alternate" without "main" and "commentary" roles, and, for audio, without the "dub" role (other roles ignored).
"captions" A version of the main video track with captions burnt in. (For legacy content; new content would use text tracks.) Video only. DASH: "caption" and "main" roles together (other roles ignored).
"descriptions" An audio description of a video track. Audio only. Ogg: "audio/audiodesc".
"main" The primary audio or video track. Audio and video. Ogg: "audio/main" or "video/main"; WebM: the "FlagDefault" element is set; DASH: "main" role without "caption", "subtitle", and "dub" roles (other roles ignored).
"main-desc" The primary audio track, mixed with audio descriptions. Audio only. AC3 audio in MPEG-2 TS: bsmod=2 and full_svc=1.
"sign" A sign-language interpretation of an audio track. Video only. Ogg: "video/sign".
"subtitles" A version of the main video track with subtitles burnt in. (For legacy content; new content would use text tracks.) Video only. DASH: "subtitle" and "main" roles together (other roles ignored).
"translation" A translated version of the main audio track. Audio only. Ogg: "audio/dub". DASH: "dub" and "main" roles together (other roles ignored).
"commentary" Commentary on the primary audio or video track, e.g. a director's commentary. Audio and video. DASH: "commentary" role without "main" role (other roles ignored).
"" (empty string) No explicit kind, or the kind given by the track's metadata is not recognized by the user agent. Audio and video.

The AudioTrack label and VideoTrack label attributes must return the label of the track, if it has one, or the empty string otherwise. [INBAND]

The AudioTrack language and VideoTrack language attributes must return the BCP 47 language tag of the language of the track, if it has one, or the empty string otherwise. If the user agent is not able to express that language as a BCP 47 language tag (for example because the language information in the media resource's format is a free-form string without a defined interpretation), then the method must return the empty string, as if the track had no language. [INBAND]

The AudioTrack enabled attribute, on getting, must return true if the track is currently enabled, and false otherwise. On setting, it must enable the track if the new value is true, and disable it otherwise. (If the track is no longer in an AudioTrackList object, then the track being enabled or disabled has no effect beyond changing the value of the attribute on the AudioTrack object.)

Whenever an audio track in an AudioTrackList that was disabled is enabled, and whenever one that was enabled is disabled, the user agent must queue a media element task given the media element to fire an event named change at the AudioTrackList object.

An audio track that has no data for a particular position on the media timeline, or that does not exist at that position, must be interpreted as being silent at that point on the timeline.

The VideoTrackList selectedIndex attribute must return the index of the currently selected track, if any. If the VideoTrackList object does not currently represent any tracks, or if none of the tracks are selected, it must instead return −1.

The VideoTrack selected attribute, on getting, must return true if the track is currently selected, and false otherwise. On setting, it must select the track if the new value is true, and unselect it otherwise. If the track is in a VideoTrackList, then all the other VideoTrack objects in that list must be unselected. (If the track is no longer in a VideoTrackList object, then the track being selected or unselected has no effect beyond changing the value of the attribute on the VideoTrack object.)

Whenever a track in a VideoTrackList that was previously not selected is selected, and whenever the selected track in a VideoTrackList is unselected without a new track being selected in its stead, the user agent must queue a media element task given the media element to fire an event named change at the VideoTrackList object. This task must be queued before the task that fires the resize event, if any.

A video track that has no data for a particular position on the media timeline must be interpreted as being transparent black at that point on the timeline, with the same dimensions as the last frame before that position, or, if the position is before all the data for that track, the same dimensions as the first frame for that track. A track that does not exist at all at the current position must be treated as if it existed but had no data.

For instance, if a video has a track that is only introduced after one hour of playback, and the user selects that track then goes back to the start, then the user agent will act as if that track started at the start of the media resource but was simply transparent until one hour in.


The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the AudioTrackList and VideoTrackList interfaces:

Event handler Event handler event type
onchange

AudioTrackList/change_event

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

TextTrackList/change_event

Support in all current engines.

Firefox31+Safari7+Chrome33+
Opera20+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android31+Safari iOS7+Chrome Android33+WebView Android4.4+Samsung Internet2.0+Opera Android20+

VideoTrackList/change_event

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
change
onaddtrack

AudioTrackList/addtrack_event

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

TextTrackList/addtrack_event

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+

VideoTrackList/addtrack_event

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
addtrack
onremovetrack

AudioTrackList/removetrack_event

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

TextTrackList/removetrack_event

Support in all current engines.

Firefox31+Safari7+Chrome33+
Opera20+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android31+Safari iOS7+Chrome Android33+WebView Android4.4+Samsung Internet2.0+Opera Android20+

VideoTrackList/removetrack_event

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
removetrack
4.8.12.10.2 声明式地选择特定的音频和视频轨道

audioTracksvideoTracks 属性使得脚本可以选择应该播放哪个轨道, 但也可以声明式地选择特定的轨道: 在 媒体资源URLfragment 上指定特定的轨道。 fragment 的格式取决于 资源MIME 类型[RFC2046] [URL]

下面例子中嵌入的这个视频使用了支持 媒体片段语法 的媒体格式,启用了标注为 "Alternative" 的轨道,而不是默认视频轨道。

<video src="myvideo#track=Alternative"></video>
4.8.12.11 计时字幕
4.8.12.11.1 Text track model

A media element can have a group of associated text tracks, known as the media element's list of text tracks. The text tracks are sorted as follows:

  1. The text tracks corresponding to track element children of the media element, in tree order.
  2. Any text tracks added using the addTextTrack() method, in the order they were added, oldest first.
  3. Any media-resource-specific text tracks (text tracks corresponding to data in the media resource), in the order defined by the media resource's format specification.

A text track consists of:

The kind of text track

This decides how the track is handled by the user agent. The kind is represented by a string. The possible strings are:

The kind of track can change dynamically, in the case of a text track corresponding to a track element.

A label

This is a human-readable string intended to identify the track for the user.

The label of a track can change dynamically, in the case of a text track corresponding to a track element.

When a text track label is the empty string, the user agent should automatically generate an appropriate label from the text track's other properties (e.g. the kind of text track and the text track's language) for use in its user interface. This automatically-generated label is not exposed in the API.

An in-band metadata track dispatch type

This is a string extracted from the media resource specifically for in-band metadata tracks to enable such tracks to be dispatched to different scripts in the document.

For example, a traditional TV station broadcast streamed on the web and augmented with web-specific interactive features could include text tracks with metadata for ad targeting, trivia game data during game shows, player states during sports games, recipe information during food programs, and so forth. As each program starts and ends, new tracks might be added or removed from the stream, and as each one is added, the user agent could bind them to dedicated script modules using the value of this attribute.

Other than for in-band metadata text tracks, the in-band metadata track dispatch type is the empty string. How this value is populated for different media formats is described in steps to expose a media-resource-specific text track.

A language

This is a string (a BCP 47 language tag) representing the language of the text track's cues. [BCP47]

The language of a text track can change dynamically, in the case of a text track corresponding to a track element.

A readiness state

One of the following:

Not loaded

Indicates that the text track's cues have not been obtained.

Loading

Indicates that the text track is loading and there have been no fatal errors encountered so far. Further cues might still be added to the track by the parser.

Loaded

Indicates that the text track has been loaded with no fatal errors.

Failed to load

Indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way (e.g. URL could not be parsed, network error, unknown text track format). Some or all of the cues are likely missing and will not be obtained.

The readiness state of a text track changes dynamically as the track is obtained.

A mode

One of the following:

Disabled

Indicates that the text track is not active. Other than for the purposes of exposing the track in the DOM, the user agent is ignoring the text track. No cues are active, no events are fired, and the user agent will not attempt to obtain the track's cues.

Hidden

Indicates that the text track is active, but that the user agent is not actively displaying the cues. If no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily. The user agent is maintaining a list of which cues are active, and events are being fired accordingly.

Showing

Indicates that the text track is active. If no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily. The user agent is maintaining a list of which cues are active, and events are being fired accordingly. In addition, for text tracks whose kind is subtitles or captions, the cues are being overlaid on the video as appropriate; for text tracks whose kind is descriptions, the user agent is making the cues available to the user in a non-visual fashion; and for text tracks whose kind is chapters, the user agent is making available to the user a mechanism by which the user can navigate to any point in the media resource by selecting a cue.

A list of zero or more cues

A list of text track cues, along with rules for updating the text track rendering. For example, for WebVTT, the rules for updating the display of WebVTT text tracks. [WEBVTT]

The list of cues of a text track can change dynamically, either because the text track has not yet been loaded or is still loading, or due to DOM manipulation.

Each text track has a corresponding TextTrack object.


Each media element has a list of pending text tracks, which must initially be empty, a blocked-on-parser flag, which must initially be false, and a did-perform-automatic-track-selection flag, which must also initially be false.

When the user agent is required to populate the list of pending text tracks of a media element, the user agent must add to the element's list of pending text tracks each text track in the element's list of text tracks whose text track mode is not disabled and whose text track readiness state is loading.

Whenever a track element's parent node changes, the user agent must remove the corresponding text track from any list of pending text tracks that it is in.

Whenever a text track's text track readiness state changes to either loaded or failed to load, the user agent must remove it from any list of pending text tracks that it is in.

When a media element is created by an HTML parser or XML parser, the user agent must set the element's blocked-on-parser flag to true. When a media element is popped off the stack of open elements of an HTML parser or XML parser, the user agent must honor user preferences for automatic text track selection, populate the list of pending text tracks, and set the element's blocked-on-parser flag to false.

The text tracks of a media element are ready when both the element's list of pending text tracks is empty and the element's blocked-on-parser flag is false.

Each media element has a pending text track change notification flag, which must initially be unset.

Whenever a text track that is in a media element's list of text tracks has its text track mode change value, the user agent must run the following steps for the media element:

  1. If the media element's pending text track change notification flag is set, return.

  2. Set the media element's pending text track change notification flag.

  3. Queue a media element task given the media element to run these steps:

    1. Unset the media element's pending text track change notification flag.

    2. Fire an event named change at the media element's textTracks attribute's TextTrackList object.

  4. If the media element's show poster flag is not set, run the time marches on steps.

The task source for the tasks listed in this section is the DOM manipulation task source.


A text track cue is the unit of time-sensitive data in a text track, corresponding for instance for subtitles and captions to the text that appears at a particular time and disappears at another time.

Each text track cue consists of:

An identifier

An arbitrary string.

A start time

The time, in seconds and fractions of a second, that describes the beginning of the range of the media data to which the cue applies.

An end time

The time, in seconds and fractions of a second, that describes the end of the range of the media data to which the cue applies.

A pause-on-exit flag

A boolean indicating whether playback of the media resource is to pause when the end of the range to which the cue applies is reached.

Some additional format-specific data

Additional fields, as needed for the format, including the actual data of the cue. For example, WebVTT has a text track cue writing direction and so forth. [WEBVTT]

The text track cue start time and text track cue end time can be negative. (The current playback position can never be negative, though, so cues entirely before time zero cannot be active.)

Each text track cue has a corresponding TextTrackCue object (or more specifically, an object that inherits from TextTrackCue — for example, WebVTT cues use the VTTCue interface). A text track cue's in-memory representation can be dynamically changed through this TextTrackCue API. [WEBVTT]

A text track cue is associated with rules for updating the text track rendering, as defined by the specification for the specific kind of text track cue. These rules are used specifically when the object representing the cue is added to a TextTrack object using the addCue() method.

In addition, each text track cue has two pieces of dynamic information:

The active flag

This flag must be initially unset. The flag is used to ensure events are fired appropriately when the cue becomes active or inactive, and to make sure the right cues are rendered.

The user agent must synchronously unset this flag whenever the text track cue is removed from its text track's text track list of cues; whenever the text track itself is removed from its media element's list of text tracks or has its text track mode changed to disabled; and whenever the media element's readyState is changed back to HAVE_NOTHING. When the flag is unset in this way for one or more cues in text tracks that were showing prior to the relevant incident, the user agent must, after having unset the flag for all the affected cues, apply the rules for updating the text track rendering of those text tracks. For example, for text tracks based on WebVTT, the rules for updating the display of WebVTT text tracks. [WEBVTT]

The display state

This is used as part of the rendering model, to keep cues in a consistent position. It must initially be empty. Whenever the text track cue active flag is unset, the user agent must empty the text track cue display state.

The text track cues of a media element's text tracks are ordered relative to each other in the text track cue order, which is determined as follows: first group the cues by their text track, with the groups being sorted in the same order as their text tracks appear in the media element's list of text tracks; then, within each group, cues must be sorted by their start time, earliest first; then, any cues with the same start time must be sorted by their end time, latest first; and finally, any cues with identical end times must be sorted in the order they were last added to their respective text track list of cues, oldest first (so e.g. for cues from a WebVTT file, that would initially be the order in which the cues were listed in the file). [WEBVTT]

4.8.12.11.2 Sourcing in-band text tracks

A media-resource-specific text track is a text track that corresponds to data found in the media resource.

Rules for processing and rendering such data are defined by the relevant specifications, e.g. the specification of the video format if the media resource is a video. Details for some legacy formats can be found in Sourcing In-band Media Resource Tracks from Media Containers into HTML. [INBAND]

When a media resource contains data that the user agent recognizes and supports as being equivalent to a text track, the user agent runs the steps to expose a media-resource-specific text track with the relevant data, as follows.

  1. Associate the relevant data with a new text track and its corresponding new TextTrack object. The text track is a media-resource-specific text track.

  2. Set the new text track's kind, label, and language based on the semantics of the relevant data, as defined by the relevant specification. If there is no label in that data, then the label must be set to the empty string.

  3. Associate the text track list of cues with the rules for updating the text track rendering appropriate for the format in question.

  4. If the new text track's kind is chapters or metadata, then set the text track in-band metadata track dispatch type as follows, based on the type of the media resource:

    If the media resource is an Ogg file
    The text track in-band metadata track dispatch type must be set to the value of the Name header field. [OGGSKELETONHEADERS]
    If the media resource is a WebM file
    The text track in-band metadata track dispatch type must be set to the value of the CodecID element. [WEBMCG]
    If the media resource is an MPEG-2 file
    Let stream type be the value of the "stream_type" field describing the text track's type in the file's program map section, interpreted as an 8-bit unsigned integer. Let length be the value of the "ES_info_length" field for the track in the same part of the program map section, interpreted as an integer as defined by Generic coding of moving pictures and associated audio information. Let descriptor bytes be the length bytes following the "ES_info_length" field. The text track in-band metadata track dispatch type must be set to the concatenation of the stream type byte and the zero or more descriptor bytes bytes, expressed in hexadecimal using ASCII upper hex digits. [MPEG2]
    If the media resource is an MPEG-4 file
    Let the first stsd box of the first stbl box of the first minf box of the first mdia box of the text track's trak box in the first moov box of the file be the stsd box, if any. If the file has no stsd box, or if the stsd box has neither a mett box nor a metx box, then the text track in-band metadata track dispatch type must be set to the empty string. Otherwise, if the stsd box has a mett box then the text track in-band metadata track dispatch type must be set to the concatenation of the string "mett", a U+0020 SPACE character, and the value of the first mime_format field of the first mett box of the stsd box, or the empty string if that field is absent in that box. Otherwise, if the stsd box has no mett box but has a metx box then the text track in-band metadata track dispatch type must be set to the concatenation of the string "metx", a U+0020 SPACE character, and the value of the first namespace field of the first metx box of the stsd box, or the empty string if that field is absent in that box. [MPEG4]
  5. Populate the new text track's list of cues with the cues parsed so far, following the guidelines for exposing cues, and begin updating it dynamically as necessary.

  6. Set the new text track's readiness state to loaded.

  7. Set the new text track's mode to the mode consistent with the user's preferences and the requirements of the relevant specification for the data.

    For instance, if there are no other active subtitles, and this is a forced subtitle track (a subtitle track giving subtitles in the audio track's primary language, but only for audio that is actually in another language), then those subtitles might be activated here.

  8. Add the new text track to the media element's list of text tracks.

  9. Fire an event named addtrack at the media element's textTracks attribute's TextTrackList object, using TrackEvent, with the track attribute initialized to the text track's TextTrack object.

4.8.12.11.3 Sourcing out-of-band text tracks

When a track element is created, it must be associated with a new text track (with its value set as defined below) and its corresponding new TextTrack object.

The text track kind is determined from the state of the element's kind attribute according to the following table; for a state given in a cell of the first column, the kind is the string given in the second column:

State String
Subtitles subtitles
Captions captions
Descriptions descriptions
Chapters metadata chapters
Metadata metadata

The text track label is the element's track label.

The text track language is the element's track language, if any, or the empty string otherwise.

As the kind, label, and srclang attributes are set, changed, or removed, the text track must update accordingly, as per the definitions above.

Changes to the track URL are handled in the algorithm below.

The text track readiness state is initially not loaded, and the text track mode is initially disabled.

The text track list of cues is initially empty. It is dynamically modified when the referenced file is parsed. Associated with the list are the rules for updating the text track rendering appropriate for the format in question; for WebVTT, this is the rules for updating the display of WebVTT text tracks. [WEBVTT]

When a track element's parent element changes and the new parent is a media element, then the user agent must add the track element's corresponding text track to the media element's list of text tracks, and then queue a media element task given the media element to fire an event named addtrack at the media element's textTracks attribute's TextTrackList object, using TrackEvent, with the track attribute initialized to the text track's TextTrack object.

When a track element's parent element changes and the old parent was a media element, then the user agent must remove the track element's corresponding text track from the media element's list of text tracks, and then queue a media element task given the media element to fire an event named removetrack at the media element's textTracks attribute's TextTrackList object, using TrackEvent, with the track attribute initialized to the text track's TextTrack object.


When a text track corresponding to a track element is added to a media element's list of text tracks, the user agent must queue a media element task given the media element to run the following steps for the media element:

  1. If the element's blocked-on-parser flag is true, then return.

  2. If the element's did-perform-automatic-track-selection flag is true, then return.

  3. Honor user preferences for automatic text track selection for this element.

When the user agent is required to honor user preferences for automatic text track selection for a media element, the user agent must run the following steps:

  1. Perform automatic text track selection for subtitles and captions.

  2. Perform automatic text track selection for descriptions.

  3. If there are any text tracks in the media element's list of text tracks whose text track kind is chapters or metadata that correspond to track elements with a default attribute set whose text track mode is set to disabled, then set the text track mode of all such tracks to hidden

  4. Set the element's did-perform-automatic-track-selection flag to true.

When the steps above say to perform automatic text track selection for one or more text track kinds, it means to run the following steps:

  1. Let candidates be a list consisting of the text tracks in the media element's list of text tracks whose text track kind is one of the kinds that were passed to the algorithm, if any, in the order given in the list of text tracks.

  2. If candidates is empty, then return.

  3. If any of the text tracks in candidates have a text track mode set to showing, return.

  4. If the user has expressed an interest in having a track from candidates enabled based on its text track kind, text track language, and text track label, then set its text track mode to showing.

    For example, the user could have set a browser preference to the effect of "I want French captions whenever possible", or "If there is a subtitle track with 'Commentary' in the title, enable it", or "If there are audio description tracks available, enable one, ideally in Swiss German, but failing that in Standard Swiss German or Standard German".

    Otherwise, if there are any text tracks in candidates that correspond to track elements with a default attribute set whose text track mode is set to disabled, then set the text track mode of the first such track to showing.

When a text track corresponding to a track element experiences any of the following circumstances, the user agent must start the track processing model for that text track and its track element:

When a user agent is to start the track processing model for a text track and its track element, it must run the following algorithm. This algorithm interacts closely with the event loop mechanism; in particular, it has a synchronous section (which is triggered as part of the event loop algorithm). The steps in that section are marked with ⌛.

  1. If another occurrence of this algorithm is already running for this text track and its track element, return, letting that other algorithm take care of this element.

  2. If the text track's text track mode is not set to one of hidden or showing, then return.

  3. If the text track's track element does not have a media element as a parent, return.

  4. Run the remainder of these steps in parallel, allowing whatever caused these steps to run to continue.

  5. Top: Await a stable state. The synchronous section consists of the following steps. (The steps in the synchronous section are marked with ⌛.)

  6. ⌛ Set the text track readiness state to loading.

  7. ⌛ Let URL be the track URL of the track element.

  8. ⌛ If the track element's parent is a media element then let corsAttributeState be the state of the parent media element's crossorigin content attribute. Otherwise, let corsAttributeState be No CORS.

  9. End the synchronous section, continuing the remaining steps in parallel.

  10. If URL is not the empty string, then:

    1. Let request be the result of creating a potential-CORS request given URL, "track", and corsAttributeState, and with the same-origin fallback flag set.

    2. Set request's client to the track element's node document's relevant settings object.

    3. Fetch request.

    The tasks queued by the fetching algorithm on the networking task source to process the data as it is being fetched must determine the type of the resource. If the type of the resource is not a supported text track format, the load will fail, as described below. Otherwise, the resource's data must be passed to the appropriate parser (e.g., the WebVTT parser) as it is received, with the text track list of cues being used for that parser's output. [WEBVTT]

    The appropriate parser will incrementally update the text track list of cues during these networking task source tasks, as each such task is run with whatever data has been received from the network).

    This specification does not currently say whether or how to check the MIME types of text tracks, or whether or how to perform file type sniffing using the actual file data. Implementors differ in their intentions on this matter and it is therefore unclear what the right solution is. In the absence of any requirement here, the HTTP specifications' strict requirement to follow the Content-Type header prevails ("Content-Type specifies the media type of the underlying data." ... "If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource.").

    If fetching fails for any reason (network error, the server returns an error code, CORS fails, etc), or if URL is the empty string, then queue an element task on the DOM manipulation task source given the media element to first change the text track readiness state to failed to load and then fire an event named error at the track element.

    If fetching does not fail, but the type of the resource is not a supported text track format, or the file was not successfully processed (e.g., the format in question is an XML format and the file contained a well-formedness error that XML requires be detected and reported to the application), then the task that is queued on the networking task source in which the aforementioned problem is found must change the text track readiness state to failed to load and fire an event named error at the track element.

    If fetching does not fail, and the file was successfully processed, then the final task that is queued by the networking task source, after it has finished parsing the data, must change the text track readiness state to loaded, and fire an event named load at the track element.

    If, while fetching is ongoing, either:

    ...then the user agent must abort fetching, discarding any pending tasks generated by that algorithm (and in particular, not adding any cues to the text track list of cues after the moment the URL changed), and then queue an element task on the DOM manipulation task source given the track element that first changes the text track readiness state to failed to load and then fires an event named error at the track element.

  11. Wait until the text track readiness state is no longer set to loading.

  12. Wait until the track URL is no longer equal to URL, at the same time as the text track mode is set to hidden or showing.

  13. Jump to the step labeled top.

Whenever a track element has its src attribute set, changed, or removed, the user agent must immediately empty the element's text track's text track list of cues. (This also causes the algorithm above to stop adding cues from the resource being obtained using the previously given URL, if any.)

4.8.12.11.4 显示各种格式的 字幕提示指南

HTML 用户代理如何处理和解释字幕提示取决于特定格式的定义。 如果没有这样一个规范,那么本小节提供了一些约束,实现方可以尝试一致地显示这种格式。

为了支持 HTML 的 字幕 模型,每个计时数据单元都被转化为一个 字幕提示。 在本规范中定义的格式特征与 字幕提示 的各方面的映射没有被定义的情况下, 实现必须确保映射与上面定义的 字幕提示 的各方面的定义一致,并满足以下约束:

字幕提示 ID

如果格式没有为每个字幕提示提供明显的 ID 类似物的话,应该设为空字符串。

字幕提示 pause-on-exit 标志

应该设为 false。

4.8.12.11.5 Text track API

TextTrackList

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+
[Exposed=Window]
interface TextTrackList : EventTarget {
  readonly attribute unsigned long length;
  getter TextTrack (unsigned long index);
  TextTrack? getTrackById(DOMString id);

  attribute EventHandler onchange;
  attribute EventHandler onaddtrack;
  attribute EventHandler onremovetrack;
};
media . textTracks . length

HTMLMediaElement/textTracks

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS6+Chrome Android25+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

Returns the number of text tracks associated with the media element (e.g. from track elements). This is the number of text tracks in the media element's list of text tracks.

media . textTracks[ n ]

Returns the TextTrack object representing the nth text track in the media element's list of text tracks.

textTrack = media . textTracks . getTrackById( id )

TextTrackList/getTrackById

Support in all current engines.

Firefox31+Safari7+Chrome33+
Opera20+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android31+Safari iOS8+Chrome Android33+WebView Android4.4.3+Samsung Internet2.0+Opera Android20+

Returns the TextTrack object with the given identifier, or null if no track has that identifier.

A TextTrackList object represents a dynamically updating list of text tracks in a given order.

The textTracks attribute of media elements must return a TextTrackList object representing the TextTrack objects of the text tracks in the media element's list of text tracks, in the same order as in the list of text tracks.

TextTrackList/length

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android37+Samsung Internet1.5+Opera Android12.1+

The length attribute of a TextTrackList object must return the number of text tracks in the list represented by the TextTrackList object.

The supported property indices of a TextTrackList object at any instant are the numbers from zero to the number of text tracks in the list represented by the TextTrackList object minus one, if any. If there are no text tracks in the list, there are no supported property indices.

To determine the value of an indexed property of a TextTrackList object for a given index index, the user agent must return the indexth text track in the list represented by the TextTrackList object.

The getTrackById(id) method must return the first TextTrack in the TextTrackList object whose id IDL attribute would return a value equal to the value of the id argument. When no tracks match the given argument, the method must return null.


TextTrack

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+
enum TextTrackMode { "disabled",  "hidden",  "showing" };
enum TextTrackKind { "subtitles",  "captions",  "descriptions",  "chapters",  "metadata" };

[Exposed=Window]
interface TextTrack : EventTarget {
  readonly attribute TextTrackKind kind;
  readonly attribute DOMString label;
  readonly attribute DOMString language;

  readonly attribute DOMString id;
  readonly attribute DOMString inBandMetadataTrackDispatchType;

  attribute TextTrackMode mode;

  readonly attribute TextTrackCueList? cues;
  readonly attribute TextTrackCueList? activeCues;

  undefined addCue(TextTrackCue cue);
  undefined removeCue(TextTrackCue cue);

  attribute EventHandler oncuechange;
};
textTrack = media . addTextTrack( kind [, label [, language ] ] )

Creates and returns a new TextTrack object, which is also added to the media element's list of text tracks.

textTrack . kind

Returns the text track kind string.

textTrack . label

Returns the text track label, if there is one, or the empty string otherwise (indicating that a custom label probably needs to be generated from the other attributes of the object if the object is exposed to the user).

textTrack . language

Returns the text track language string.

textTrack . id

Returns the ID of the given track.

For in-band tracks, this is the ID that can be used with a fragment if the format supports media fragment syntax, and that can be used with the getTrackById() method.

For TextTrack objects corresponding to track elements, this is the ID of the track element.

textTrack . inBandMetadataTrackDispatchType

Returns the text track in-band metadata track dispatch type string.

textTrack . mode [ = value ]

TextTrack/mode

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+

Returns the text track mode, represented by a string from the following list:

"disabled"

The text track disabled mode.

"hidden"

The text track hidden mode.

"showing"

The text track showing mode.

Can be set, to change the mode.

textTrack . cues

Returns the text track list of cues, as a TextTrackCueList object.

textTrack . activeCues

Returns the text track cues from the text track list of cues that are currently active (i.e. that start before the current playback position and end after it), as a TextTrackCueList object.

textTrack . addCue( cue )

Adds the given cue to textTrack's text track list of cues.

textTrack . removeCue( cue )

Removes the given cue from textTrack's text track list of cues.

The addTextTrack(kind, label, language) method of media elements, when invoked, must run the following steps:

  1. Create a new TextTrack object.

  2. Create a new text track corresponding to the new object, and set its text track kind to kind, its text track label to label, its text track language to language, its text track readiness state to the text track loaded state, its text track mode to the text track hidden mode, and its text track list of cues to an empty list.

    Initially, the text track list of cues is not associated with any rules for updating the text track rendering. When a text track cue is added to it, the text track list of cues has its rules permanently set accordingly.

  3. Add the new text track to the media element's list of text tracks.

  4. Queue a media element task given the media element to fire an event named addtrack at the media element's textTracks attribute's TextTrackList object, using TrackEvent, with the track attribute initialized to the new text track's TextTrack object.

  5. Return the new TextTrack object.


The kind attribute must return the text track kind of the text track that the TextTrack object represents.

The label attribute must return the text track label of the text track that the TextTrack object represents.

The language attribute must return the text track language of the text track that the TextTrack object represents.

The id attribute returns the track's identifier, if it has one, or the empty string otherwise. For tracks that correspond to track elements, the track's identifier is the value of the element's id attribute, if any. For in-band tracks, the track's identifier is specified by the media resource. If the media resource is in a format that supports media fragment syntax, the identifier returned for a particular track must be the same identifier that would enable the track if used as the name of a track in the track dimension of such a fragment.

The inBandMetadataTrackDispatchType attribute must return the text track in-band metadata track dispatch type of the text track that the TextTrack object represents.

The mode attribute, on getting, must return the string corresponding to the text track mode of the text track that the TextTrack object represents, as defined by the following list:

"disabled"
The text track disabled mode.
"hidden"
The text track hidden mode.
"showing"
The text track showing mode.

On setting, if the new value isn't equal to what the attribute would currently return, the new value must be processed as follows:

If the new value is "disabled"

Set the text track mode of the text track that the TextTrack object represents to the text track disabled mode.

If the new value is "hidden"

Set the text track mode of the text track that the TextTrack object represents to the text track hidden mode.

If the new value is "showing"

Set the text track mode of the text track that the TextTrack object represents to the text track showing mode.

If the text track mode of the text track that the TextTrack object represents is not the text track disabled mode, then the cues attribute must return a live TextTrackCueList object that represents the subset of the text track list of cues of the text track that the TextTrack object represents whose end times occur at or after the earliest possible position when the script started, in text track cue order. Otherwise, it must return null. For each TextTrack object, when an object is returned, the same TextTrackCueList object must be returned each time.

The earliest possible position when the script started is whatever the earliest possible position was the last time the event loop reached step 1.

If the text track mode of the text track that the TextTrack object represents is not the text track disabled mode, then the activeCues attribute must return a live TextTrackCueList object that represents the subset of the text track list of cues of the text track that the TextTrack object represents whose active flag was set when the script started, in text track cue order. Otherwise, it must return null. For each TextTrack object, when an object is returned, the same TextTrackCueList object must be returned each time.

A text track cue's active flag was set when the script started if its text track cue active flag was set the last time the event loop reached step 1.


The addCue(cue) method of TextTrack objects, when invoked, must run the following steps:

  1. If the text track list of cues does not yet have any associated rules for updating the text track rendering, then associate the text track list of cues with the rules for updating the text track rendering appropriate to cue.

  2. If text track list of cues' associated rules for updating the text track rendering are not the same rules for updating the text track rendering as appropriate for cue, then throw an "InvalidStateError" DOMException.

  3. If the given cue is in a text track list of cues, then remove cue from that text track list of cues.

  4. Add cue to the TextTrack object's text track's text track list of cues.

The removeCue(cue) method of TextTrack objects, when invoked, must run the following steps:

  1. If the given cue is not in the TextTrack object's text track's text track list of cues, then throw a "NotFoundError" DOMException.

  2. Remove cue from the TextTrack object's text track's text track list of cues.

In this example, an audio element is used to play a specific sound-effect from a sound file containing many sound effects. A cue is used to pause the audio, so that it ends exactly at the end of the clip, even if the browser is busy running some script. If the page had relied on script to pause the audio, then the start of the next clip might be heard if the browser was not able to run the script at the exact time specified.

var sfx = new Audio('sfx.wav');
var sounds = sfx.addTextTrack('metadata');

// add sounds we care about
function addFX(start, end, name) {
  var cue = new VTTCue(start, end, '');
  cue.id = name;
  cue.pauseOnExit = true;
  sounds.addCue(cue);
}
addFX(12.783, 13.612, 'dog bark');
addFX(13.612, 15.091, 'kitten mew'))

function playSound(id) {
  sfx.currentTime = sounds.getCueById(id).startTime;
  sfx.play();
}

// play a bark as soon as we can
sfx.oncanplaythrough = function () {
  playSound('dog bark');
}
// meow when the user tries to leave,
// and have the browser ask them to stay
window.onbeforeunload = function (e) {
  playSound('kitten mew');
  e.preventDefault();
}

TextTrackCueList

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS6+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+
[Exposed=Window]
interface TextTrackCueList {
  readonly attribute unsigned long length;
  getter TextTrackCue (unsigned long index);
  TextTrackCue? getCueById(DOMString id);
};
cuelist . length

Returns the number of cues in the list.

cuelist[index]

Returns the text track cue with index index in the list. The cues are sorted in text track cue order.

cuelist . getCueById( id )

Returns the first text track cue (in text track cue order) with text track cue identifier id.

Returns null if none of the cues have the given identifier or if the argument is the empty string.

A TextTrackCueList object represents a dynamically updating list of text track cues in a given order.

TextTrackCueList/length

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS6+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+

The length attribute must return the number of cues in the list represented by the TextTrackCueList object.

The supported property indices of a TextTrackCueList object at any instant are the numbers from zero to the number of cues in the list represented by the TextTrackCueList object minus one, if any. If there are no cues in the list, there are no supported property indices.

To determine the value of an indexed property for a given index index, the user agent must return the indexth text track cue in the list represented by the TextTrackCueList object.

TextTrackCueList/getCueById

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS6+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+

The getCueById(id) method, when called with an argument other than the empty string, must return the first text track cue in the list represented by the TextTrackCueList object whose text track cue identifier is id, if any, or null otherwise. If the argument is the empty string, then the method must return null.


TextTrackCue

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+
[Exposed=Window]
interface TextTrackCue : EventTarget {
  readonly attribute TextTrack? track;

  attribute DOMString id;
  attribute double startTime;
  attribute double endTime;
  attribute boolean pauseOnExit;

  attribute EventHandler onenter;
  attribute EventHandler onexit;
};
cue . track

Returns the TextTrack object to which this text track cue belongs, if any, or null otherwise.

cue . id [ = value ]

Returns the text track cue identifier.

Can be set.

cue . startTime [ = value ]

Returns the text track cue start time, in seconds.

Can be set.

cue . endTime [ = value ]

Returns the text track cue end time, in seconds.

Can be set.

cue . pauseOnExit [ = value ]

Returns true if the text track cue pause-on-exit flag is set, false otherwise.

Can be set.

TextTrackCue/track

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+

The track attribute, on getting, must return the TextTrack object of the text track in whose list of cues the text track cue that the TextTrackCue object represents finds itself, if any; or null otherwise.

TextTrackCue/id

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+

The id attribute, on getting, must return the text track cue identifier of the text track cue that the TextTrackCue object represents. On setting, the text track cue identifier must be set to the new value.

TextTrackCue/startTime

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+

The startTime attribute, on getting, must return the text track cue start time of the text track cue that the TextTrackCue object represents, in seconds. On setting, the text track cue start time must be set to the new value, interpreted in seconds; then, if the TextTrackCue object's text track cue is in a text track's list of cues, and that text track is in a media element's list of text tracks, and the media element's show poster flag is not set, then run the time marches on steps for that media element.

TextTrackCue/endTime

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+

The endTime attribute, on getting, must return the text track cue end time of the text track cue that the TextTrackCue object represents, in seconds. On setting, the text track cue end time must be set to the new value, interpreted in seconds; then, if the TextTrackCue object's text track cue is in a text track's list of cues, and that text track is in a media element's list of text tracks, and the media element's show poster flag is not set, then run the time marches on steps for that media element.

TextTrackCue/pauseOnExit

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+

The pauseOnExit attribute, on getting, must return true if the text track cue pause-on-exit flag of the text track cue that the TextTrackCue object represents is set; or false otherwise. On setting, the text track cue pause-on-exit flag must be set if the new value is true, and must be unset otherwise.

4.8.12.11.6 Event handlers for objects of the text track APIs

The following are the event handlers that (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the TextTrackList interface:

Event handler Event handler event type
onchange change
onaddtrack addtrack
onremovetrack removetrack

The following are the event handlers that (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the TextTrack interface:

Event handler Event handler event type
oncuechange

TextTrack/cuechange_event

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+
cuechange

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the TextTrackCue interface:

Event handler Event handler event type
onenter

TextTrackCue/enter_event

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+
enter
onexit

TextTrackCue/exit_event

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+
exit
4.8.12.11.7 元数据字幕的最佳实践

This section is non-normative.

字幕可用于存储与多媒体数据相关的数据,用来做交互式的,增强的视图。

例如,一个显示体育播报的页面可能会包含当前分数信息。 假设正在直播一个机器人比赛。图片上可能会覆盖上分数,像这样:

为了让用户回放到视频任意位置时分数都能正确地呈现,元数据字幕提示需要达到那个分数适用的长度。 例如在上面这一帧,显示比赛序号的字幕提示可能持续整场比赛,显示蓝队分数的字幕提示持续到蓝队得分变化, 显示红队分数的字幕提示持续到红队得分变化。如果这个视频只是事件的直播流, 右下角的时间可能会自动从当前视频时间得出,而不是通过字幕提示显示。 但如果视频只是精彩回放,那么它可能也会通过字幕给出。

在 WebVTT 文件中,这些字幕提示的片段可能像这样:

WEBVTT

...

05:10:00.000 --> 05:12:15.000
matchtype:qual
matchnumber:37

...

05:11:02.251 --> 05:11:17.198
red:78

05:11:03.672 --> 05:11:54.198
blue:66

05:11:17.198 --> 05:11:25.912
red:80

05:11:25.912 --> 05:11:26.522
red:83

05:11:26.522 --> 05:11:26.982
red:86

05:11:26.982 --> 05:11:27.499
red:89

...

这里的关键在于字幕提示给出的信息覆盖了相关事件的时间长度。 如果得分变化时得分以 0 长度(或非常短的,近乎 0 的长度)的字幕给出, 比如在 05:11:17.198 时 "red+2",在 05:11:25.912 时 "red+3",问题就会出现: 回放寻找会很难实现,因为脚本必须遍历整个字幕提示列表来确保没有错过任何通知; 但同时,如果字幕提示很短,脚本也可能永远不会看到它们被激活,除非脚本明确地监听了它。

当这样使用字幕时,鼓励作者使用 cuechange 事件来更新当前提示。 (典型地,使用 timeupdate 事件不太合适, 因为即使字幕提示没变也要进行计算,更重要的是这会在元数据字幕提示激活与显示更新之间引入更高的延迟, 因为 timeupdate 事件是限制速率的。)

4.8.12.12 通过 URL 识别轨道类型

需要通过 URL 来识别 AudioTrack.kindVideoTrack.kind IDL 属性的返回值, 或识别 字幕类型 的其他规范或格式, 必须使用 about:html-kind URL

4.8.12.13 User interface

The controls attribute is a boolean attribute. If present, it indicates that the author has not provided a scripted controller and would like the user agent to provide its own set of controls.

If the attribute is present, or if scripting is disabled for the media element, then the user agent should expose a user interface to the user. This user interface should include features to begin playback, pause playback, seek to an arbitrary position in the content (if the content supports arbitrary seeking), change the volume, change the display of closed captions or embedded sign-language tracks, select different audio tracks or turn on audio descriptions, and show the media content in manners more suitable to the user (e.g. fullscreen video or in an independent resizable window). Other controls may also be made available.

Even when the attribute is absent, however, user agents may provide controls to affect playback of the media resource (e.g. play, pause, seeking, track selection, and volume controls), but such features should not interfere with the page's normal rendering. For example, such features could be exposed in the media element's context menu, platform media keys, or a remote control. The user agent may implement this simply by exposing a user interface to the user as described above (as if the controls attribute was present).

If the user agent exposes a user interface to the user by displaying controls over the media element, then the user agent should suppress any user interaction events while the user agent is interacting with this interface. (For example, if the user clicks on a video's playback control, mousedown events and so forth would not simultaneously be fired at elements on the page.)

Where possible (specifically, for starting, stopping, pausing, and unpausing playback, for seeking, for changing the rate of playback, for fast-forwarding or rewinding, for listing, enabling, and disabling text tracks, and for muting or changing the volume of the audio), user interface features exposed by the user agent must be implemented in terms of the DOM API described above, so that, e.g., all the same events fire.

Features such as fast-forward or rewind must be implemented by only changing the playbackRate attribute (and not the defaultPlaybackRate attribute).

Seeking must be implemented in terms of seeking to the requested position in the media element's media timeline. For media resources where seeking to an arbitrary position would be slow, user agents are encouraged to use the approximate-for-speed flag when seeking in response to the user manipulating an approximate position interface such as a seek bar.

HTMLMediaElement/controls

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The controls IDL attribute must reflect the content attribute of the same name.


media . volume [ = value ]

HTMLMediaElement/volume

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the current playback volume, as a number in the range 0.0 to 1.0, where 0.0 is the quietest and 1.0 the loudest.

Can be set, to change the volume.

Throws an "IndexSizeError" DOMException if the new value is not in the range 0.0 .. 1.0.

media . muted [ = value ]

HTMLMediaElement/muted

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns true if audio is muted, overriding the volume attribute, and false if the volume attribute is being honored.

Can be set, to change whether the audio is muted or not.

A media element has a playback volume, which is a fraction in the range 0.0 (silent) to 1.0 (loudest). Initially, the volume should be 1.0, but user agents may remember the last set value across sessions, on a per-site basis or otherwise, so the volume may start at other values.

The volume IDL attribute must return the playback volume of any audio portions of the media element. On setting, if the new value is in the range 0.0 to 1.0 inclusive, the media element's playback volume must be set to the new value. If the new value is outside the range 0.0 to 1.0 inclusive, then, on setting, an "IndexSizeError" DOMException must be thrown instead.

A media element can also be muted. If anything is muting the element, then it is muted. (For example, when the direction of playback is backwards, the element is muted.)

The muted IDL attribute must return the value to which it was last set. When a media element is created, if the element has a muted content attribute specified, then the muted IDL attribute should be set to true; otherwise, the user agents may set the value to the user's preferred value (e.g. remembering the last set value across sessions, on a per-site basis or otherwise). While the muted IDL attribute is set to true, the media element must be muted.

Whenever either of the values that would be returned by the volume and muted IDL attributes change, the user agent must queue a media element task given the media element to fire an event named volumechange at the media element. Then, if the media element is not allowed to play, the user agent must run the internal pause steps for the media element.

An element's effective media volume is determined as follows:

  1. If the user has indicated that the user agent is to override the volume of the element, then return the volume desired by the user.

  2. If the element's audio output is muted, then return zero.

  3. Let volume be the playback volume of the audio portions of the media element, in range 0.0 (silent) to 1.0 (loudest).

  4. Return volume, interpreted relative to the range 0.0 to 1.0, with 0.0 being silent, and 1.0 being the loudest setting, values in between increasing in loudness. The range need not be linear. The loudest setting may be lower than the system's loudest possible setting; for example the user could have set a maximum volume.

The muted content attribute on media elements is a boolean attribute that controls the default state of the audio output of the media resource, potentially overriding user preferences.

HTMLMediaElement/defaultMuted

Support in all current engines.

Firefox11+Safari6+Chrome15+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android14+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The defaultMuted IDL attribute must reflect the muted content attribute.

This attribute has no dynamic effect (it only controls the default state of the element).

This video (an advertisement) autoplays, but to avoid annoying users, it does so without sound, and allows the user to turn the sound on. The user agent can pause the video if it's unmuted without a user interaction.

<video src="adverts.cgi?kind=video" controls autoplay loop muted></video>
4.8.12.14 Time ranges

TimeRanges

Support in all current engines.

Firefox4+Safari3.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Objects implementing the TimeRanges interface represent a list of ranges (periods) of time.

[Exposed=Window]
interface TimeRanges {
  readonly attribute unsigned long length;
  double start(unsigned long index);
  double end(unsigned long index);
};
media . length

TimeRanges/length

Support in all current engines.

Firefox4+Safari3.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the number of ranges in the object.

time = media . start(index)

TimeRanges/start

Support in all current engines.

Firefox4+Safari3.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the time for the start of the range with the given index.

Throws an "IndexSizeError" DOMException if the index is out of range.

time = media . end(index)

TimeRanges/end

Support in all current engines.

Firefox4+Safari3.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the time for the end of the range with the given index.

Throws an "IndexSizeError" DOMException if the index is out of range.

The length IDL attribute must return the number of ranges represented by the object.

The start(index) method must return the position of the start of the indexth range represented by the object, in seconds measured from the start of the timeline that the object covers.

The end(index) method must return the position of the end of the indexth range represented by the object, in seconds measured from the start of the timeline that the object covers.

These methods must throw "IndexSizeError" DOMExceptions if called with an index argument greater than or equal to the number of ranges represented by the object.

When a TimeRanges object is said to be a normalized TimeRanges object, the ranges it represents must obey the following criteria:

In other words, the ranges in such an object are ordered, don't overlap, and don't touch (adjacent ranges are folded into one bigger range). A range can be empty (referencing just a single moment in time), e.g. to indicate that only one frame is currently buffered in the case that the user agent has discarded the entire media resource except for the current frame, when a media element is paused.

Ranges in a TimeRanges object must be inclusive.

Thus, the end of a range would be equal to the start of a following adjacent (touching but not overlapping) range. Similarly, a range covering a whole timeline anchored at zero would have a start equal to zero and an end equal to the duration of the timeline.

The timelines used by the objects returned by the buffered, seekable and played IDL attributes of media elements must be that element's media timeline.

4.8.12.15 The TrackEvent interface

TrackEvent

Support in all current engines.

Firefox27+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android27+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+
[Exposed=Window]
interface TrackEvent : Event {
  constructor(DOMString type, optional TrackEventInit eventInitDict = {});

  readonly attribute (VideoTrack or AudioTrack or TextTrack)? track;
};

dictionary TrackEventInit : EventInit {
  (VideoTrack or AudioTrack or TextTrack)? track = null;
};
event . track

TrackEvent/track

Support in all current engines.

Firefox27+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android27+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+

Returns the track object (TextTrack, AudioTrack, or VideoTrack) to which the event relates.

The track attribute must return the value it was initialized to. It represents the context information for the event.

4.8.12.16 Events summary

This section is non-normative.

The following events fire on media elements as part of the processing model described above:

Event name Interface Fired when... Preconditions
loadstart

HTMLMediaElement/loadstart_event

Support in all current engines.

Firefox6+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android6+Safari iOS3+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Event The user agent begins looking for media data, as part of the resource selection algorithm. networkState equals NETWORK_LOADING
progress

HTMLMediaElement/progress_event

Support in all current engines.

Firefox6+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android6+Safari iOS3+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Event The user agent is fetching media data. networkState equals NETWORK_LOADING
suspend

HTMLMediaElement/suspend_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event The user agent is intentionally not currently fetching media data. networkState equals NETWORK_IDLE
abort

HTMLMediaElement/abort_event

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS3+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Event The user agent stops fetching the media data before it is completely downloaded, but not due to an error. error is an object with the code MEDIA_ERR_ABORTED. networkState equals either NETWORK_EMPTY or NETWORK_IDLE, depending on when the download was aborted.
error

HTMLMediaElement/error_event

Support in all current engines.

Firefox6+Safari3.1+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android6+Safari iOS3+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
Event An error occurs while fetching the media data or the type of the resource is not supported media format. error is an object with the code MEDIA_ERR_NETWORK or higher. networkState equals either NETWORK_EMPTY or NETWORK_IDLE, depending on when the download was aborted.
emptied

HTMLMediaElement/emptied_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event A media element whose networkState was previously not in the NETWORK_EMPTY state has just switched to that state (either because of a fatal error during load that's about to be reported, or because the load() method was invoked while the resource selection algorithm was already running). networkState is NETWORK_EMPTY; all the IDL attributes are in their initial states.
stalled

HTMLMediaElement/stalled_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event The user agent is trying to fetch media data, but data is unexpectedly not forthcoming. networkState is NETWORK_LOADING.
loadedmetadata

HTMLMediaElement/loadedmetadata_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event The user agent has just determined the duration and dimensions of the media resource and the text tracks are ready. readyState is newly equal to HAVE_METADATA or greater for the first time.
loadeddata

HTMLMediaElement/loadeddata_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event The user agent can render the media data at the current playback position for the first time. readyState newly increased to HAVE_CURRENT_DATA or greater for the first time.
canplay

HTMLMediaElement/canplay_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event The user agent can resume playback of the media data, but estimates that if playback were to be started now, the media resource could not be rendered at the current playback rate up to its end without having to stop for further buffering of content. readyState newly increased to HAVE_FUTURE_DATA or greater.
canplaythrough

HTMLMediaElement/canplaythrough_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event The user agent estimates that if playback were to be started now, the media resource could be rendered at the current playback rate all the way to its end without having to stop for further buffering. readyState is newly equal to HAVE_ENOUGH_DATA.
playing

HTMLMediaElement/playing_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event Playback is ready to start after having been paused or delayed due to lack of media data. readyState is newly equal to or greater than HAVE_FUTURE_DATA and paused is false, or paused is newly false and readyState is equal to or greater than HAVE_FUTURE_DATA. Even if this event fires, the element might still not be potentially playing, e.g. if the element is paused for user interaction or paused for in-band content.
waiting

HTMLMediaElement/waiting_event

Support in all current engines.

Firefox6+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android6+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
Event Playback has stopped because the next frame is not available, but the user agent expects that frame to become available in due course. readyState is equal to or less than HAVE_CURRENT_DATA, and paused is false. Either seeking is true, or the current playback position is not contained in any of the ranges in buffered. It is possible for playback to stop for other reasons without paused being false, but those reasons do not fire this event (and when those situations resolve, a separate playing event is not fired either): e.g., playback has ended, or playback stopped due to errors, or the element has paused for user interaction or paused for in-band content.
seeking

HTMLMediaElement/seeking_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event The seeking IDL attribute changed to true, and the user agent has started seeking to a new position.
seeked

HTMLMediaElement/seeked_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event The seeking IDL attribute changed to false after the current playback position was changed.
ended

HTMLMediaElement/ended_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event Playback has stopped because the end of the media resource was reached. currentTime equals the end of the media resource; ended is true.
durationchange

HTMLMediaElement/durationchange_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event The duration attribute has just been updated.
timeupdate

HTMLMediaElement/timeupdate_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event The current playback position changed as part of normal playback or in an especially interesting way, for example discontinuously.
play

HTMLMediaElement/play_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event The element is no longer paused. Fired after the play() method has returned, or when the autoplay attribute has caused playback to begin. paused is newly false.
pause

HTMLMediaElement/pause_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event The element has been paused. Fired after the pause() method has returned. paused is newly true.
ratechange

HTMLMediaElement/ratechange_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
Event Either the defaultPlaybackRate or the playbackRate attribute has just been updated.
resize Event One or both of the videoWidth and videoHeight attributes have just been updated. Media element is a video element; readyState is not HAVE_NOTHING
volumechange

HTMLMediaElement/volumechange_event

Support in all current engines.

Firefox6+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android6+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
Event Either the volume attribute or the muted attribute has changed. Fired after the relevant attribute's setter has returned.

The following event fires on source element:

Event name Interface Fired when...
error Event An error occurs while fetching the media data or the type of the resource is not supported media format.

The following events fire on AudioTrackList, VideoTrackList, and TextTrackList objects:

Event name Interface Fired when...
change

AudioTrackList/change_event

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

TextTrackList/change_event

Support in all current engines.

Firefox31+Safari7+Chrome33+
Opera20+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android31+Safari iOS7+Chrome Android33+WebView Android4.4+Samsung Internet2.0+Opera Android20+

VideoTrackList/change_event

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
Event One or more tracks in the track list have been enabled or disabled.
addtrack

AudioTrackList/addtrack_event

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

TextTrackList/addtrack_event

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+

VideoTrackList/addtrack_event

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
TrackEvent A track has been added to the track list.
removetrack

AudioTrackList/removetrack_event

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo

TextTrackList/removetrack_event

Support in all current engines.

Firefox31+Safari7+Chrome33+
Opera20+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android31+Safari iOS7+Chrome Android33+WebView Android4.4+Samsung Internet2.0+Opera Android20+

VideoTrackList/removetrack_event

Support in all current engines.

Firefox🔰 33+Safari7+Chrome🔰 37+
Opera🔰 24+Edge🔰 79+
Edge (Legacy)NoInternet Explorer10+
Firefox AndroidNoSafari iOS7+Chrome Android🔰 37+WebView AndroidNoSamsung InternetNoOpera AndroidNo
TrackEvent A track has been removed from the track list.

The following event fires on TextTrack objects and track elements:

Event name Interface Fired when...
cuechange

HTMLTrackElement/cuechange_event

Support in all current engines.

Firefox68+Safari10+Chrome32+
Opera19+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android68+Safari iOS10+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+

TextTrack/cuechange_event

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+
Event One or more cues in the track have become active or stopped being active.

The following events fire on track elements:

Event name Interface Fired when...
error Event An error occurs while fetching the track data or the type of the resource is not supported text track format.
load Event A track data has been fetched and successfully processed.

The following events fire on TextTrackCue objects:

Event name Interface Fired when...
enter

TextTrackCue/enter_event

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+
Event The cue has become active.
exit

TextTrackCue/exit_event

Support in all current engines.

Firefox31+Safari6+Chrome23+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android31+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+
Event The cue has stopped being active.
4.8.12.17 Security and privacy considerations

The main security and privacy implications of the video and audio elements come from the ability to embed media cross-origin. There are two directions that threats can flow: from hostile content to a victim page, and from a hostile page to victim content.


If a victim page embeds hostile content, the threat is that the content might contain scripted code that attempts to interact with the Document that embeds the content. To avoid this, user agents must ensure that there is no access from the content to the embedding page. In the case of media content that uses DOM concepts, the embedded content must be treated as if it was in its own unrelated top-level browsing context.

For instance, if an SVG animation was embedded in a video element, the user agent would not give it access to the DOM of the outer page. From the perspective of scripts in the SVG resource, the SVG file would appear to be in a lone top-level browsing context with no parent.


If a hostile page embeds victim content, the threat is that the embedding page could obtain information from the content that it would not otherwise have access to. The API does expose some information: the existence of the media, its type, its duration, its size, and the performance characteristics of its host. Such information is already potentially problematic, but in practice the same information can more or less be obtained using the img element, and so it has been deemed acceptable.

However, significantly more sensitive information could be obtained if the user agent further exposes metadata within the content, such as subtitles. That information is therefore only exposed if the video resource uses CORS. The crossorigin attribute allows authors to enable CORS. [FETCH]

Without this restriction, an attacker could trick a user running within a corporate network into visiting a site that attempts to load a video from a previously leaked location on the corporation's intranet. If such a video included confidential plans for a new product, then being able to read the subtitles would present a serious confidentiality breach.

4.8.12.18 作者使用媒体元素的最佳实践

This section is non-normative.

在机顶盒和手机的小型设备上播放音视频资源经常会受到有限的硬件资源的限制, 比如一个机器可能只支持同时播放三个视频。 因此好的实践是在 媒体元素 播放完后立即释放资源。 做法可以是移除所有对这个元素的引用让它被垃圾回收,或者更好的方式是, 移除元素的的 src 属性和所有后代 source 元素,然后调用元素的 load() 方法。

类似地,当回放速率不是 1.0 时,软硬件和格式限制会造成视频丢帧或音频卡顿和静音。

4.8.12.19 Best practices for implementers of media elements

This section is non-normative.

How accurately various aspects of the media element API are implemented is considered a quality-of-implementation issue.

For example, when implementing the buffered attribute, how precise an implementation reports the ranges that have been buffered depends on how carefully the user agent inspects the data. Since the API reports ranges as times, but the data is obtained in byte streams, a user agent receiving a variable-bitrate stream might only be able to determine precise times by actually decoding all of the data. User agents aren't required to do this, however; they can instead return estimates (e.g. based on the average bitrate seen so far) which get revised as more information becomes available.

As a general rule, user agents are urged to be conservative rather than optimistic. For example, it would be bad to report that everything had been buffered when it had not.

Another quality-of-implementation issue would be playing a video backwards when the codec is designed only for forward playback (e.g. there aren't many key frames, and they are far apart, and the intervening frames only have deltas from the previous frame). User agents could do a poor job, e.g. only showing key frames; however, better implementations would do more work and thus do a better job, e.g. actually decoding parts of the video forwards, storing the complete frames, and then playing the frames backwards.

Similarly, while implementations are allowed to drop buffered data at any time (there is no requirement that a user agent keep all the media data obtained for the lifetime of the media element), it is again a quality of implementation issue: user agents with sufficient resources to keep all the data around are encouraged to do so, as this allows for a better user experience. For example, if the user is watching a live stream, a user agent could allow the user only to view the live video; however, a better user agent would buffer everything and allow the user to seek through the earlier material, pause it, play it forwards and backwards, etc.


When a media element that is paused is removed from a document and not reinserted before the next time the event loop reaches step 1, implementations that are resource constrained are encouraged to take that opportunity to release all hardware resources (like video planes, networking resources, and data buffers) used by the media element. (User agents still have to keep track of the playback position and so forth, though, in case playback is later restarted.)

4.8.13 The map element

Element/map

Support in all current engines.

Firefox1+Safari1+Chrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome Android18+WebView Android1+Samsung Internet1.0+Opera AndroidYes

HTMLMapElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Phrasing content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Transparent.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
name — Name of image map to reference from the usemap attribute
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLMapElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString name;
  [SameObject] readonly attribute HTMLCollection areas;
};

The map element, in conjunction with an img element and any area element descendants, defines an image map. The element represents its children.

The name attribute gives the map a name so that it can be referenced. The attribute must be present and must have a non-empty value with no ASCII whitespace. The value of the name attribute must not be equal to the value of the name attribute of another map element in the same tree. If the id attribute is also specified, both attributes must have the same value.

map . areas

Returns an HTMLCollection of the area elements in the map.

The areas attribute must return an HTMLCollection rooted at the map element, whose filter matches only area elements.

The IDL attribute name must reflect the content attribute of the same name.

Image maps can be defined in conjunction with other content on the page, to ease maintenance. This example is of a page with an image map at the top of the page and a corresponding set of text links at the bottom.

<!DOCTYPE HTML>
<HTML LANG="EN">
<TITLE>Babies™: Toys</TITLE>
<HEADER>
 <H1>Toys</H1>
 <IMG SRC="/images/menu.gif"
      ALT="Babies™ navigation menu. Select a department to go to its page."
      USEMAP="#NAV">
</HEADER>
 ...
<FOOTER>
 <MAP NAME="NAV">
  <P>
   <A HREF="/clothes/">Clothes</A>
   <AREA ALT="Clothes" COORDS="0,0,100,50" HREF="/clothes/"> |
   <A HREF="/toys/">Toys</A>
   <AREA ALT="Toys" COORDS="100,0,200,50" HREF="/toys/"> |
   <A HREF="/food/">Food</A>
   <AREA ALT="Food" COORDS="200,0,300,50" HREF="/food/"> |
   <A HREF="/books/">Books</A>
   <AREA ALT="Books" COORDS="300,0,400,50" HREF="/books/">
  </P>
 </MAP>
</FOOTER>

4.8.14 The area element

Element/area

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLAreaElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Phrasing content.
Contexts in which this element can be used:
Where phrasing content is expected, but only if there is a map element ancestor.
Content model:
Nothing.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
alt — Replacement text for use when images are not available
coords — Coordinates for the shape to be created in an image map
shape — The kind of shape to be created in an image map
href — Address of the hyperlink
targetBrowsing context for hyperlink navigation
download — Whether to download the resource instead of navigating to it, and its file name if so
pingURLs to ping
rel — Relationship between the location in the document containing the hyperlink and the destination resource
referrerpolicyReferrer policy for fetches initiated by the element
Accessibility considerations:
If the element has an href attribute: for authors; for implementers.
Otherwise: for authors; for implementers.
DOM interface:
[Exposed=Window]
interface HTMLAreaElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString alt;
  [CEReactions] attribute DOMString coords;
  [CEReactions] attribute DOMString shape;
  [CEReactions] attribute DOMString target;
  [CEReactions] attribute DOMString download;
  [CEReactions] attribute USVString ping;
  [CEReactions] attribute DOMString rel;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList relList;
  [CEReactions] attribute DOMString referrerPolicy;

  // also has obsolete members
};
HTMLAreaElement includes HTMLHyperlinkElementUtils;

The area element represents either a hyperlink with some text and a corresponding area on an image map, or a dead area on an image map.

An area element with a parent node must have a map element ancestor.

If the area element has an href attribute, then the area element represents a hyperlink. In this case, the alt attribute must be present. It specifies the text of the hyperlink. Its value must be text that, when presented with the texts specified for the other hyperlinks of the image map, and with the alternative text of the image, but without the image itself, provides the user with the same kind of choice as the hyperlink would when used without its text but with its shape applied to the image. The alt attribute may be left blank if there is another area element in the same image map that points to the same resource and has a non-blank alt attribute.

If the area element has no href attribute, then the area represented by the element cannot be selected, and the alt attribute must be omitted.

In both cases, the shape and coords attributes specify the area.

The shape attribute is an enumerated attribute. The following table lists the keywords defined for this attribute. The states given in the first cell of the rows with keywords give the states to which those keywords map. Some of the keywords are non-conforming, as noted in the last column.

State Keywords Notes
Circle state circle
circ Non-conforming
Default state default
Polygon state poly
polygon Non-conforming
Rectangle state rect
rectangle Non-conforming

The attribute may be omitted. The missing value default and invalid value default are the rectangle state.

The coords attribute must, if specified, contain a valid list of floating-point numbers. This attribute gives the coordinates for the shape described by the shape attribute. The processing for this attribute is described as part of the image map processing model.

In the circle state, area elements must have a coords attribute present, with three integers, the last of which must be non-negative. The first integer must be the distance in CSS pixels from the left edge of the image to the center of the circle, the second integer must be the distance in CSS pixels from the top edge of the image to the center of the circle, and the third integer must be the radius of the circle, again in CSS pixels.

In the default state state, area elements must not have a coords attribute. (The area is the whole image.)

In the polygon state, area elements must have a coords attribute with at least six integers, and the number of integers must be even. Each pair of integers must represent a coordinate given as the distances from the left and the top of the image in CSS pixels respectively, and all the coordinates together must represent the points of the polygon, in order.

In the rectangle state, area elements must have a coords attribute with exactly four integers, the first of which must be less than the third, and the second of which must be less than the fourth. The four points must represent, respectively, the distance from the left edge of the image to the left side of the rectangle, the distance from the top edge to the top side, the distance from the left edge to the right side, and the distance from the top edge to the bottom side, all in CSS pixels.

When user agents allow users to follow hyperlinks or download hyperlinks created using the area element, as described in the next section, the href, target, download, and ping attributes decide how the link is followed. The rel attribute may be used to indicate to the user the likely nature of the target resource before the user follows the link.

The target, download, ping, rel, and referrerpolicy attributes must be omitted if the href attribute is not present.

If the itemprop attribute is specified on an area element, then the href attribute must also be specified.

The activation behavior of area elements is to follow the hyperlink or download the hyperlink created by the area element, if any, and as determined by the download attribute and any expressed user preference.

HTMLAreaElement/rel

Support in all current engines.

Firefox30+Safari9+Chrome54+
Opera41+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android30+Safari iOS9+Chrome Android54+WebView Android54+Samsung Internet6.0+Opera Android41+

The IDL attributes alt, coords, target, download, ping, and rel, each must reflect the respective content attributes of the same name.

The IDL attribute shape must reflect the shape content attribute.

HTMLAreaElement/relList

Support in all current engines.

Firefox30+Safari9+Chrome65+
Opera41+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android30+Safari iOS9+Chrome Android65+WebView Android65+Samsung Internet9.0+Opera Android41+

The IDL attribute relList must reflect the rel content attribute.

HTMLAreaElement/referrerPolicy

Support in all current engines.

Firefox50+Safari14.1+Chrome53+
Opera40+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android50+Safari iOS14.5+Chrome Android53+WebView Android53+Samsung Internet7.2+Opera Android41+

The IDL attribute referrerPolicy must reflect the referrerpolicy content attribute, limited to only known values.

4.8.15 图片映射

4.8.15.1 编写

图片映射 可以让图片的几何区域与 超链接 相关联。

img 元素或 object 元素表示的图片可以通过在该元素上指定一个 usemap 属性来与一个图片映射相关联 (以 map 元素的形式)。如果指定了 usemap 属性,它必须是一个对 map 元素的 合法的哈希名引用

考虑下面这样的图片:

A line with four shapes in it, equally spaced: a red hollow box, a green circle, a blue triangle, and a yellow four-pointed star.

我们想只让有颜色的区域可点,可以这样做:

<p>
 Please select a shape:
 <img src="shapes.png" usemap="#shapes"
      alt="Four shapes are available: a red hollow box, a green circle, a blue triangle, and a yellow four-pointed star.">
 <map name="shapes">
  <area shape=rect coords="50,50,100,100"> <!-- the hole in the red box -->
  <area shape=rect coords="25,25,125,125" href="red.html" alt="Red box.">
  <area shape=circle coords="200,75,50" href="green.html" alt="Green circle.">
  <area shape=poly coords="325,25,262,125,388,125" href="blue.html" alt="Blue triangle.">
  <area shape=poly coords="450,25,435,60,400,75,435,90,450,125,465,90,500,75,465,60"
        href="yellow.html" alt="Yellow star.">
 </map>
</p>
4.8.15.2 Processing model

If an img element or an object element representing an image has a usemap attribute specified, user agents must process it as follows:

  1. Parse the attribute's value using the rules for parsing a hash-name reference to a map element, with the element as the context node. This will return either an element (the map) or null.

  2. If that returned null, then return. The image is not associated with an image map after all.

  3. Otherwise, the user agent must collect all the area elements that are descendants of the map. Let those be the areas.

Having obtained the list of area elements that form the image map (the areas), interactive user agents must process the list in one of two ways.

If the user agent intends to show the text that the img element represents, then it must use the following steps.

In user agents that do not support images, or that have images disabled, object elements cannot represent images, and thus this section never applies (the fallback content is shown instead). The following steps therefore only apply to img elements.

  1. Remove all the area elements in areas that have no href attribute.

  2. Remove all the area elements in areas that have no alt attribute, or whose alt attribute's value is the empty string, if there is another area element in areas with the same value in the href attribute and with a non-empty alt attribute.

  3. Each remaining area element in areas represents a hyperlink. Those hyperlinks should all be made available to the user in a manner associated with the text of the img.

    In this context, user agents may represent area and img elements with no specified alt attributes, or whose alt attributes are the empty string or some other non-visible text, in an implementation-defined fashion intended to indicate the lack of suitable author-provided text.

If the user agent intends to show the image and allow interaction with the image to select hyperlinks, then the image must be associated with a set of layered shapes, taken from the area elements in areas, in reverse tree order (so the last specified area element in the map is the bottom-most shape, and the first element in the map, in tree order, is the top-most shape).

Each area element in areas must be processed as follows to obtain a shape to layer onto the image:

  1. Find the state that the element's shape attribute represents.

  2. Use the rules for parsing a list of floating-point numbers to parse the element's coords attribute, if it is present, and let the result be the coords list. If the attribute is absent, let the coords list be the empty list.

  3. If the number of items in the coords list is less than the minimum number given for the area element's current state, as per the following table, then the shape is empty; return.

    State Minimum number of items
    Circle state 3
    Default state 0
    Polygon state 6
    Rectangle state 4
  4. Check for excess items in the coords list as per the entry in the following list corresponding to the shape attribute's state:

    Circle state
    Drop any items in the list beyond the third.
    Default state
    Drop all items in the list.
    Polygon state
    Drop the last item if there's an odd number of items.
    Rectangle state
    Drop any items in the list beyond the fourth.
  5. If the shape attribute represents the rectangle state, and the first number in the list is numerically greater than the third number in the list, then swap those two numbers around.

  6. If the shape attribute represents the rectangle state, and the second number in the list is numerically greater than the fourth number in the list, then swap those two numbers around.

  7. If the shape attribute represents the circle state, and the third number in the list is less than or equal to zero, then the shape is empty; return.

  8. Now, the shape represented by the element is the one described for the entry in the list below corresponding to the state of the shape attribute:

    Circle state

    Let x be the first number in coords, y be the second number, and r be the third number.

    The shape is a circle whose center is x CSS pixels from the left edge of the image and y CSS pixels from the top edge of the image, and whose radius is r CSS pixels.

    Default state

    The shape is a rectangle that exactly covers the entire image.

    Polygon state

    Let xi be the (2i)th entry in coords, and yi be the (2i+1)th entry in coords (the first entry in coords being the one with index 0).

    Let the coordinates be (xi, yi), interpreted in CSS pixels measured from the top left of the image, for all integer values of i from 0 to (N/2)-1, where N is the number of items in coords.

    The shape is a polygon whose vertices are given by the coordinates, and whose interior is established using the even-odd rule. [GRAPHICS]

    Rectangle state

    Let x1 be the first number in coords, y1 be the second number, x2 be the third number, and y2 be the fourth number.

    The shape is a rectangle whose top-left corner is given by the coordinate (x1, y1) and whose bottom right corner is given by the coordinate (x2, y2), those coordinates being interpreted as CSS pixels from the top left corner of the image.

    For historical reasons, the coordinates must be interpreted relative to the displayed image after any stretching caused by the CSS 'width' and 'height' properties (or, for non-CSS browsers, the image element's width and height attributes — CSS browsers map those attributes to the aforementioned CSS properties).

    Browser zoom features and transforms applied using CSS or SVG do not affect the coordinates.

Pointing device interaction with an image associated with a set of layered shapes per the above algorithm must result in the relevant user interaction events being first fired to the top-most shape covering the point that the pointing device indicated, if any, or to the image element itself, if there is no shape covering that point. User agents may also allow individual area elements representing hyperlinks to be selected and activated (e.g. using a keyboard).

Because a map element (and its area elements) can be associated with multiple img and object elements, it is possible for an area element to correspond to multiple focusable areas of the document.

Image maps are live; if the DOM is mutated, then the user agent must act as if it had rerun the algorithms for image maps.

4.8.16 MathML

HTML/HTML5/HTML5_Parser#Inline_SVG_and_MathML_support

Support in all current engines.

Firefox4+Safari5.1+Chrome7+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android5+Safari iOS5+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android12+

The MathML math element falls into the embedded content, phrasing content, flow content, and palpable content categories for the purposes of the content models in this specification.

When the MathML annotation-xml element contains elements from the HTML namespace, such elements must all be flow content.

When the MathML token elements (mi, mo, mn, ms, and mtext) are descendants of HTML elements, they may contain phrasing content elements from the HTML namespace.

User agents must handle text other than inter-element whitespace found in MathML elements whose content models do not allow straight text by pretending for the purposes of MathML content models, layout, and rendering that the text is actually wrapped in a MathML mtext element. (Such text is not, however, conforming.)

User agents must act as if any MathML element whose contents does not match the element's content model was replaced, for the purposes of MathML layout and rendering, by a MathML merror element containing some appropriate error message.

The semantics of MathML elements are defined by MathML and other applicable specifications. [MATHML]

Here is an example of the use of MathML in an HTML document:

<!DOCTYPE html>
<html lang="en">
 <head>
  <title>The quadratic formula</title>
 </head>
 <body>
  <h1>The quadratic formula</h1>
  <p>
   <math>
    <mi>x</mi>
    <mo>=</mo>
    <mfrac>
     <mrow>
      <mo form="prefix">−</mo> <mi>b</mi>
      <mo>±</mo>
      <msqrt>
       <msup> <mi>b</mi> <mn>2</mn> </msup>
       <mo>−</mo>
       <mn>4</mn> <mo>⁢</mo> <mi>a</mi> <mo>⁢</mo> <mi>c</mi>
      </msqrt>
     </mrow>
     <mrow>
      <mn>2</mn> <mo>⁢</mo> <mi>a</mi>
     </mrow>
    </mfrac>
   </math>
  </p>
 </body>
</html>

4.8.17 SVG

HTML/HTML5/HTML5_Parser#Inline_SVG_and_MathML_support

Support in all current engines.

Firefox37+Safari11.1+Chrome7+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android37+Safari iOS11.3+Chrome Android18+WebView Android4.4+Samsung Internet4+Opera Android15+

The SVG svg element falls into the embedded content, phrasing content, flow content, and palpable content categories for the purposes of the content models in this specification.

When the SVG foreignObject element contains elements from the HTML namespace, such elements must all be flow content.

The content model for the SVG title element inside HTML documents is phrasing content. (This further constrains the requirements given in SVG 2.)

The semantics of SVG elements are defined by SVG 2 and other applicable specifications. [SVG]


doc = iframe . getSVGDocument()
doc = embed . getSVGDocument()
doc = object . getSVGDocument()

Returns the Document object, in the case of iframe, embed, or object elements being used to embed SVG.

The getSVGDocument() method must run the following steps:

  1. Let document be this element's content document.

  2. If document is non-null and was created by the page load processing model for XML files section because the computed type of the resource in the navigate algorithm was image/svg+xml, then return document.

  3. Return null.

4.8.18 Dimension attributes

Author requirements: The width and height attributes on img, iframe, embed, object, video, and, when their type attribute is in the Image Button state, input elements may be specified to give the dimensions of the visual content of the element (the width and height respectively, relative to the nominal direction of the output medium), in CSS pixels. The attributes, if specified, must have values that are valid non-negative integers.

The specified dimensions given may differ from the dimensions specified in the resource itself, since the resource may have a resolution that differs from the CSS pixel resolution. (On screens, CSS pixels have a resolution of 96ppi, but in general the CSS pixel resolution depends on the reading distance.) If both attributes are specified, then one of the following statements must be true:

The target ratio is the ratio of the intrinsic width to the intrinsic height in the resource. The specified width and specified height are the values of the width and height attributes respectively.

The two attributes must be omitted if the resource in question does not have both an intrinsic width and an intrinsic height.

If the two attributes are both zero, it indicates that the element is not intended for the user (e.g. it might be a part of a service to count page views).

The dimension attributes are not intended to be used to stretch the image.

User agent requirements: User agents are expected to use these attributes as hints for the rendering.

HTMLObjectElement/width

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLObjectElement/height

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The width and height IDL attributes on the iframe, embed, object, and video elements must reflect the respective content attributes of the same name.

For iframe, embed, and object the IDL attributes are DOMString; for video the IDL attributes are unsigned long.

The corresponding IDL attributes for img and input elements are defined in those respective elements' sections, as they are slightly more specific to those elements' other behaviors.

4.9 表格数据

4.9.1 The table element

Element/table

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome Android18+WebView Android1+Samsung Internet1.0+Opera AndroidYes

HTMLTableElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
In this order: optionally a caption element, followed by zero or more colgroup elements, followed optionally by a thead element, followed by either zero or more tbody elements or one or more tr elements, followed optionally by a tfoot element, optionally intermixed with one or more script-supporting elements.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLTableElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute HTMLTableCaptionElement? caption;
  HTMLTableCaptionElement createCaption();
  [CEReactions] undefined deleteCaption();

  [CEReactions] attribute HTMLTableSectionElement? tHead;
  HTMLTableSectionElement createTHead();
  [CEReactions] undefined deleteTHead();

  [CEReactions] attribute HTMLTableSectionElement? tFoot;
  HTMLTableSectionElement createTFoot();
  [CEReactions] undefined deleteTFoot();

  [SameObject] readonly attribute HTMLCollection tBodies;
  HTMLTableSectionElement createTBody();

  [SameObject] readonly attribute HTMLCollection rows;
  HTMLTableRowElement insertRow(optional long index = -1);
  [CEReactions] undefined deleteRow(long index);

  // also has obsolete members
};

The table element represents data with more than one dimension, in the form of a table.

The table element takes part in the table model. Tables have rows, columns, and cells given by their descendants. The rows and columns form a grid; a table's cells must completely cover that grid without overlap.

Precise rules for determining whether this conformance requirement is met are described in the description of the table model.

Authors are encouraged to provide information describing how to interpret complex tables. Guidance on how to provide such information is given below.

Tables must not be used as layout aids. Historically, some web authors have misused tables in HTML as a way to control their page layout. This usage is non-conforming, because tools attempting to extract tabular data from such documents would obtain very confusing results. In particular, users of accessibility tools like screen readers are likely to find it very difficult to navigate pages with tables used for layout.

There are a variety of alternatives to using HTML tables for layout, primarily using CSS positioning and the CSS table model. [CSS]


Tables can be complicated to understand and navigate. To help users with this, user agents should clearly delineate cells in a table from each other, unless the user agent has classified the table as a (non-conforming) layout table.

Authors and implementers are encouraged to consider using some of the table design techniques described below to make tables easier to navigate for users.

User agents, especially those that do table analysis on arbitrary content, are encouraged to find heuristics to determine which tables actually contain data and which are merely being used for layout. This specification does not define a precise heuristic, but the following are suggested as possible indicators:

Feature Indication
The use of the role attribute with the value presentation Probably a layout table
The use of the non-conforming border attribute with the non-conforming value 0 Probably a layout table
The use of the non-conforming cellspacing and cellpadding attributes with the value 0 Probably a layout table
The use of caption, thead, or th elements Probably a non-layout table
The use of the headers and scope attributes Probably a non-layout table
The use of the non-conforming border attribute with a value other than 0 Probably a non-layout table
Explicit visible borders set using CSS Probably a non-layout table
The use of the summary attribute Not a good indicator (both layout and non-layout tables have historically been given this attribute)

It is quite possible that the above suggestions are wrong. Implementors are urged to provide feedback elaborating on their experiences with trying to create a layout table detection heuristic.

If a table element has a (non-conforming) summary attribute, and the user agent has not classified the table as a layout table, the user agent may report the contents of that attribute to the user.


table . caption [ = value ]

HTMLTableElement/caption

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the table's caption element.

Can be set, to replace the caption element.

caption = table . createCaption()

HTMLTableElement/createCaption

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Ensures the table has a caption element, and returns it.

table . deleteCaption()

HTMLTableElement/deleteCaption

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Ensures the table does not have a caption element.

table . tHead [ = value ]

HTMLTableElement/tHead

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the table's thead element.

Can be set, to replace the thead element. If the new value is not a thead element, throws a "HierarchyRequestError" DOMException.

thead = table . createTHead()

HTMLTableElement/createTHead

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Ensures the table has a thead element, and returns it.

table . deleteTHead()

HTMLTableElement/deleteTHead

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Ensures the table does not have a thead element.

table . tFoot [ = value ]

HTMLTableElement/tFoot

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the table's tfoot element.

Can be set, to replace the tfoot element. If the new value is not a tfoot element, throws a "HierarchyRequestError" DOMException.

tfoot = table . createTFoot()

HTMLTableElement/createTFoot

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Ensures the table has a tfoot element, and returns it.

table . deleteTFoot()

HTMLTableElement/deleteTFoot

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Ensures the table does not have a tfoot element.

table . tBodies

HTMLTableElement/tBodies

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns an HTMLCollection of the tbody elements of the table.

tbody = table . createTBody()

HTMLTableElement/createTBody

Support in all current engines.

Firefox25+Safari6+Chrome20+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android25+Safari iOS6+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android14+

Creates a tbody element, inserts it into the table, and returns it.

table . rows

HTMLTableElement/rows

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns an HTMLCollection of the tr elements of the table.

tr = table . insertRow( [ index ] )

HTMLTableElement/insertRow

Support in all current engines.

Firefox1+Safari4+Chrome1+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

Creates a tr element, along with a tbody if required, inserts them into the table at the position given by the argument, and returns the tr.

The position is relative to the rows in the table. The index −1, which is the default if the argument is omitted, is equivalent to inserting at the end of the table.

If the given position is less than −1 or greater than the number of rows, throws an "IndexSizeError" DOMException.

table . deleteRow(index)

HTMLTableElement/deleteRow

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Removes the tr element with the given position in the table.

The position is relative to the rows in the table. The index −1 is equivalent to deleting the last row of the table.

If the given position is less than −1 or greater than the index of the last row, or if there are no rows, throws an "IndexSizeError" DOMException.

In all of the following attribute and method definitions, when an element is to be table-created, that means to create an element given the table element's node document, the given local name, and the HTML namespace.

The caption IDL attribute must return, on getting, the first caption element child of the table element, if any, or null otherwise. On setting, the first caption element child of the table element, if any, must be removed, and the new value, if not null, must be inserted as the first node of the table element.

The createCaption() method must return the first caption element child of the table element, if any; otherwise a new caption element must be table-created, inserted as the first node of the table element, and then returned.

The deleteCaption() method must remove the first caption element child of the table element, if any.

The tHead IDL attribute must return, on getting, the first thead element child of the table element, if any, or null otherwise. On setting, if the new value is null or a thead element, the first thead element child of the table element, if any, must be removed, and the new value, if not null, must be inserted immediately before the first element in the table element that is neither a caption element nor a colgroup element, if any, or at the end of the table if there are no such elements. If the new value is neither null nor a thead element, then a "HierarchyRequestError" DOMException must be thrown instead.

The createTHead() method must return the first thead element child of the table element, if any; otherwise a new thead element must be table-created and inserted immediately before the first element in the table element that is neither a caption element nor a colgroup element, if any, or at the end of the table if there are no such elements, and then that new element must be returned.

The deleteTHead() method must remove the first thead element child of the table element, if any.

The tFoot IDL attribute must return, on getting, the first tfoot element child of the table element, if any, or null otherwise. On setting, if the new value is null or a tfoot element, the first tfoot element child of the table element, if any, must be removed, and the new value, if not null, must be inserted at the end of the table. If the new value is neither null nor a tfoot element, then a "HierarchyRequestError" DOMException must be thrown instead.

The createTFoot() method must return the first tfoot element child of the table element, if any; otherwise a new tfoot element must be table-created and inserted at the end of the table, and then that new element must be returned.

The deleteTFoot() method must remove the first tfoot element child of the table element, if any.

The tBodies attribute must return an HTMLCollection rooted at the table node, whose filter matches only tbody elements that are children of the table element.

The createTBody() method must table-create a new tbody element, insert it immediately after the last tbody element child in the table element, if any, or at the end of the table element if the table element has no tbody element children, and then must return the new tbody element.

The rows attribute must return an HTMLCollection rooted at the table node, whose filter matches only tr elements that are either children of the table element, or children of thead, tbody, or tfoot elements that are themselves children of the table element. The elements in the collection must be ordered such that those elements whose parent is a thead are included first, in tree order, followed by those elements whose parent is either a table or tbody element, again in tree order, followed finally by those elements whose parent is a tfoot element, still in tree order.

The behavior of the insertRow(index) method depends on the state of the table. When it is called, the method must act as required by the first item in the following list of conditions that describes the state of the table and the index argument:

If index is less than −1 or greater than the number of elements in rows collection:
The method must throw an "IndexSizeError" DOMException.
If the rows collection has zero elements in it, and the table has no tbody elements in it:
The method must table-create a tbody element, then table-create a tr element, then append the tr element to the tbody element, then append the tbody element to the table element, and finally return the tr element.
If the rows collection has zero elements in it:
The method must table-create a tr element, append it to the last tbody element in the table, and return the tr element.
If index is −1 or equal to the number of items in rows collection:
The method must table-create a tr element, and append it to the parent of the last tr element in the rows collection. Then, the newly created tr element must be returned.
Otherwise:
The method must table-create a tr element, insert it immediately before the indexth tr element in the rows collection, in the same parent, and finally must return the newly created tr element.

When the deleteRow(index) method is called, the user agent must run the following steps:

  1. If index is less than −1 or greater than or equal to the number of elements in the rows collection, then throw an "IndexSizeError" DOMException.

  2. If index is −1, then remove the last element in the rows collection from its parent, or do nothing if the rows collection is empty.

  3. Otherwise, remove the indexth element in the rows collection from its parent.

Here is an example of a table being used to mark up a Sudoku puzzle. Observe the lack of headers, which are not necessary in such a table.

<style>
 #sudoku { border-collapse: collapse; border: solid thick; }
 #sudoku colgroup, table#sudoku tbody { border: solid medium; }
 #sudoku td { border: solid thin; height: 1.4em; width: 1.4em; text-align: center; padding: 0; }
</style>
<h1>Today's Sudoku</h1>
<table id="sudoku">
 <colgroup><col><col><col>
 <colgroup><col><col><col>
 <colgroup><col><col><col>
 <tbody>
  <tr> <td> 1 <td>   <td> 3 <td> 6 <td>   <td> 4 <td> 7 <td>   <td> 9
  <tr> <td>   <td> 2 <td>   <td>   <td> 9 <td>   <td>   <td> 1 <td>
  <tr> <td> 7 <td>   <td>   <td>   <td>   <td>   <td>   <td>   <td> 6
 <tbody>
  <tr> <td> 2 <td>   <td> 4 <td>   <td> 3 <td>   <td> 9 <td>   <td> 8
  <tr> <td>   <td>   <td>   <td>   <td>   <td>   <td>   <td>   <td>
  <tr> <td> 5 <td>   <td>   <td> 9 <td>   <td> 7 <td>   <td>   <td> 1
 <tbody>
  <tr> <td> 6 <td>   <td>   <td>   <td> 5 <td>   <td>   <td>   <td> 2
  <tr> <td>   <td>   <td>   <td>   <td> 7 <td>   <td>   <td>   <td>
  <tr> <td> 9 <td>   <td>   <td> 8 <td>   <td> 2 <td>   <td>   <td> 5
</table>
4.9.1.1 描述表格的技术

如果一个表格不以第一行和第一列作为标题,或着其他难以理解的情况,作者引入介绍该表格的解释性信息。 该信息对所有用户都很有用,尤其是对于无法看到该表的用户,例如屏幕阅读器的用户。

这样的解释性信息应该介绍表格的目的,概述其基本单元格结构, 突出显示任何趋势或模式,通常用来教会用户如何使用这个表格。

例如下面的表格:

Characteristics with positive and negative sides
Negative Characteristic Positive
Sad Mood Happy
Failing Grade Passing

如果有一段描述来解释该表格的布局就很有用,比如 “性格在第二列给出,左侧一列是缺点,右侧一列是优点”。

有很多种方式引入这个信息,比如:

在环绕表格的段落中
<p>In the following table, characteristics are given in the second
column, with the negative side in the left column and the positive
side in the right column.</p>
<table>
 <caption>Characteristics with positive and negative sides</caption>
 <thead>
  <tr>
   <th id="n"> Negative
   <th> Characteristic
   <th> Positive
 <tbody>
  <tr>
   <td headers="n r1"> Sad
   <th id="r1"> Mood
   <td> Happy
  <tr>
   <td headers="n r2"> Failing
   <th id="r2"> Grade
   <td> Passing
</table>
在表格的 caption
<table>
 <caption>
  <strong>Characteristics with positive and negative sides.</strong>
  <p>Characteristics are given in the second column, with the
  negative side in the left column and the positive side in the right
  column.</p>
 </caption>
 <thead>
  <tr>
   <th id="n"> Negative
   <th> Characteristic
   <th> Positive
 <tbody>
  <tr>
   <td headers="n r1"> Sad
   <th id="r1"> Mood
   <td> Happy
  <tr>
   <td headers="n r2"> Failing
   <th id="r2"> Grade
   <td> Passing
</table>
在表格的 caption 中,用一个 details 元素
<table>
 <caption>
  <strong>Characteristics with positive and negative sides.</strong>
  <details>
   <summary>Help</summary>
   <p>Characteristics are given in the second column, with the
   negative side in the left column and the positive side in the right
   column.</p>
  </details>
 </caption>
 <thead>
  <tr>
   <th id="n"> Negative
   <th> Characteristic
   <th> Positive
 <tbody>
  <tr>
   <td headers="n r1"> Sad
   <th id="r1"> Mood
   <td> Happy
  <tr>
   <td headers="n r2"> Failing
   <th id="r2"> Grade
   <td> Passing
</table>
在同一 figure 中在表格的旁边
<figure>
 <figcaption>Characteristics with positive and negative sides</figcaption>
 <p>Characteristics are given in the second column, with the
 negative side in the left column and the positive side in the right
 column.</p>
 <table>
  <thead>
   <tr>
    <th id="n"> Negative
    <th> Characteristic
    <th> Positive
  <tbody>
   <tr>
    <td headers="n r1"> Sad
    <th id="r1"> Mood
    <td> Happy
   <tr>
    <td headers="n r2"> Failing
    <th id="r2"> Grade
    <td> Passing
 </table>
</figure>
在同一 figurefigcaption 中,表格的旁边
<figure>
 <figcaption>
  <strong>Characteristics with positive and negative sides</strong>
  <p>Characteristics are given in the second column, with the
  negative side in the left column and the positive side in the right
  column.</p>
 </figcaption>
 <table>
  <thead>
   <tr>
    <th id="n"> Negative
    <th> Characteristic
    <th> Positive
  <tbody>
   <tr>
    <td headers="n r1"> Sad
    <th id="r1"> Mood
    <td> Happy
   <tr>
    <td headers="n r2"> Failing
    <th id="r2"> Grade
    <td> Passing
 </table>
</figure>

作者也可以使用其他技术,或适当地结合上述技术。

相比于编写一段描述来解释表格的布局,最佳的选择当然还是调整好表格使得不再有解释的必要。

对于上面示例中使用的表格,对表格进行简单的重新排列使标题位于顶部和左侧。 这样就消除了解释的必要,也不需要使用 headers 属性了:

<table>
 <caption>Characteristics with positive and negative sides</caption>
 <thead>
  <tr>
   <th> Characteristic
   <th> Negative
   <th> Positive
 <tbody>
  <tr>
   <th> Mood
   <td> Sad
   <td> Happy
  <tr>
   <th> Grade
   <td> Failing
   <td> Passing
</table>
4.9.1.2 表格设计技术

好的表格设计是让表格更加可读和可用的关键

在视觉媒体中,提供行列边框和修改行的背景对于制作可读性强的表格非常有效。

对于具有大量数字内容的表格,使用等宽字体可以帮助用户看到其中的模式, 特别是在用户代理未呈现边界的情况下。(不幸的是,由于历史原因,不在表格上渲染边界是常见的默认设置。)

在语音媒体中,单元格使得媒体能够在读取单元格的内容之前报告相应的标题, 以及允许用户以网格方式来浏览表格,而不需要按源格式序列化表格的全部内容。

鼓励作者使用 CSS 来实现这些效果。

鼓励用户代理在页面不使用 CSS 并且该表格不是用来布局的时候,使用这些技术来呈现表格。

4.9.2 The caption element

Element/caption

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLTableCaptionElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
None.
Contexts in which this element can be used:
As the first element child of a table element.
Content model:
Flow content, but with no descendant table elements.
text/html 中的标签省略
A caption element's end tag can be omitted if the caption element is not immediately followed by ASCII whitespace or a comment.
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLTableCaptionElement : HTMLElement {
  [HTMLConstructor] constructor();

  // also has obsolete members
};

The caption element represents the title of the table that is its parent, if it has a parent and that is a table element.

The caption element takes part in the table model.

When a table element is the only content in a figure element other than the figcaption, the caption element should be omitted in favor of the figcaption.

A caption can introduce context for a table, making it significantly easier to understand.

Consider, for instance, the following table:

1 2 3 4 5 6
1 2 3 4 5 6 7
2 3 4 5 6 7 8
3 4 5 6 7 8 9
4 5 6 7 8 9 10
5 6 7 8 9 10 11
6 7 8 9 10 11 12

In the abstract, this table is not clear. However, with a caption giving the table's number (for reference in the main prose) and explaining its use, it makes more sense:

<caption>
<p>Table 1.
<p>This table shows the total score obtained from rolling two
six-sided dice. The first row represents the value of the first die,
the first column the value of the second die. The total is given in
the cell that corresponds to the values of the two dice.
</caption>

This provides the user with more context:

Table 1.

This table shows the total score obtained from rolling two six-sided dice. The first row represents the value of the first die, the first column the value of the second die. The total is given in the cell that corresponds to the values of the two dice.

1 2 3 4 5 6
1 2 3 4 5 6 7
2 3 4 5 6 7 8
3 4 5 6 7 8 9
4 5 6 7 8 9 10
5 6 7 8 9 10 11
6 7 8 9 10 11 12

4.9.3 The colgroup element

Element/colgroup

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLTableColElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
None.
Contexts in which this element can be used:
As a child of a table element, after any caption elements and before any thead, tbody, tfoot, and tr elements.
Content model:
If the span attribute is present: Nothing.
If the span attribute is absent: Zero or more col and template elements.
text/html 中的标签省略
A colgroup element's start tag can be omitted if the first thing inside the colgroup element is a col element, and if the element is not immediately preceded by another colgroup element whose end tag has been omitted. (It can't be omitted if the element is empty.)
A colgroup element's end tag can be omitted if the colgroup element is not immediately followed by ASCII whitespace or a comment.
Content attributes:
Global attributes
span — Number of columns spanned by the element
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLTableColElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute unsigned long span;

  // also has obsolete members
};

The colgroup element represents a group of one or more columns in the table that is its parent, if it has a parent and that is a table element.

If the colgroup element contains no col elements, then the element may have a span content attribute specified, whose value must be a valid non-negative integer greater than zero and less than or equal to 1000.

The colgroup element and its span attribute take part in the table model.

The span IDL attribute must reflect the content attribute of the same name. It is clamped to the range [1, 1000], and its default value is 1.

4.9.4 The col element

Element/col

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
None.
Contexts in which this element can be used:
As a child of a colgroup element that doesn't have a span attribute.
Content model:
Nothing.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
span — Number of columns spanned by the element
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLTableColElement, as defined for colgroup elements.

If a col element has a parent and that is a colgroup element that itself has a parent that is a table element, then the col element represents one or more columns in the column group represented by that colgroup.

The element may have a span content attribute specified, whose value must be a valid non-negative integer greater than zero and less than or equal to 1000.

The col element and its span attribute take part in the table model.

The span IDL attribute must reflect the content attribute of the same name. It is clamped to the range [1, 1000], and its default value is 1.

4.9.5 The tbody element

Element/tbody

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLTableSectionElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
None.
Contexts in which this element can be used:
As a child of a table element, after any caption, colgroup, and thead elements, but only if there are no tr elements that are children of the table element.
Content model:
Zero or more tr and script-supporting elements.
text/html 中的标签省略
A tbody element's start tag can be omitted if the first thing inside the tbody element is a tr element, and if the element is not immediately preceded by a tbody, thead, or tfoot element whose end tag has been omitted. (It can't be omitted if the element is empty.)
A tbody element's end tag can be omitted if the tbody element is immediately followed by a tbody or tfoot element, or if there is no more content in the parent element.
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLTableSectionElement : HTMLElement {
  [HTMLConstructor] constructor();

  [SameObject] readonly attribute HTMLCollection rows;
  HTMLTableRowElement insertRow(optional long index = -1);
  [CEReactions] undefined deleteRow(long index);

  // also has obsolete members
};

The HTMLTableSectionElement interface is also used for thead and tfoot elements.

The tbody element represents a block of rows that consist of a body of data for the parent table element, if the tbody element has a parent and it is a table.

The tbody element takes part in the table model.

tbody . rows

Returns an HTMLCollection of the tr elements of the table section.

tr = tbody . insertRow( [ index ] )

Creates a tr element, inserts it into the table section at the position given by the argument, and returns the tr.

The position is relative to the rows in the table section. The index −1, which is the default if the argument is omitted, is equivalent to inserting at the end of the table section.

If the given position is less than −1 or greater than the number of rows, throws an "IndexSizeError" DOMException.

tbody . deleteRow(index)

Removes the tr element with the given position in the table section.

The position is relative to the rows in the table section. The index −1 is equivalent to deleting the last row of the table section.

If the given position is less than −1 or greater than the index of the last row, or if there are no rows, throws an "IndexSizeError" DOMException.

The rows attribute must return an HTMLCollection rooted at this element, whose filter matches only tr elements that are children of this element.

The insertRow(index) method must act as follows:

  1. If index is less than −1 or greater than the number of elements in the rows collection, throw an "IndexSizeError" DOMException.

  2. Let table row be the result of creating an element given this element's node document, tr, and the HTML namespace.

  3. If index is −1 or equal to the number of items in the rows collection, then append table row to this element.

  4. Otherwise, insert table row as a child of this element, immediately before the indexth tr element in the rows collection.

  5. Return table row.

The deleteRow(index) method must, when invoked, act as follows:

  1. If index is less than −1 or greater than or equal to the number of elements in the rows collection, then throw an "IndexSizeError" DOMException.

  2. If index is −1, then remove the last element in the rows collection from this element, or do nothing if the rows collection is empty.

  3. Otherwise, remove the indexth element in the rows collection from this element.

4.9.6 The thead element

Element/thead

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
None.
Contexts in which this element can be used:
As a child of a table element, after any caption, and colgroup elements and before any tbody, tfoot, and tr elements, but only if there are no other thead elements that are children of the table element.
Content model:
Zero or more tr and script-supporting elements.
text/html 中的标签省略
A thead element's end tag can be omitted if the thead element is immediately followed by a tbody or tfoot element.
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLTableSectionElement, as defined for tbody elements.

The thead element represents the block of rows that consist of the column labels (headers) for the parent table element, if the thead element has a parent and it is a table.

The thead element takes part in the table model.

This example shows a thead element being used. Notice the use of both th and td elements in the thead element: the first row is the headers, and the second row is an explanation of how to fill in the table.

<table>
 <caption> School auction sign-up sheet </caption>
 <thead>
  <tr>
   <th><label for=e1>Name</label>
   <th><label for=e2>Product</label>
   <th><label for=e3>Picture</label>
   <th><label for=e4>Price</label>
  <tr>
   <td>Your name here
   <td>What are you selling?
   <td>Link to a picture
   <td>Your reserve price
 <tbody>
  <tr>
   <td>Ms Danus
   <td>Doughnuts
   <td><img src="https://example.com/mydoughnuts.png" title="Doughnuts from Ms Danus">
   <td>$45
  <tr>
   <td><input id=e1 type=text name=who required form=f>
   <td><input id=e2 type=text name=what required form=f>
   <td><input id=e3 type=url name=pic form=f>
   <td><input id=e4 type=number step=0.01 min=0 value=0 required form=f>
</table>
<form id=f action="/auction.cgi">
 <input type=button name=add value="Submit">
</form>

4.9.7 The tfoot element

Element/tfoot

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
None.
Contexts in which this element can be used:
As a child of a table element, after any caption, colgroup, thead, tbody, and tr elements, but only if there are no other tfoot elements that are children of the table element.
Content model:
Zero or more tr and script-supporting elements.
text/html 中的标签省略
A tfoot element's end tag can be omitted if there is no more content in the parent element.
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLTableSectionElement, as defined for tbody elements.

The tfoot element represents the block of rows that consist of the column summaries (footers) for the parent table element, if the tfoot element has a parent and it is a table.

The tfoot element takes part in the table model.

4.9.8 The tr element

Element/tr

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLTableRowElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
None.
Contexts in which this element can be used:
As a child of a thead element.
As a child of a tbody element.
As a child of a tfoot element.
As a child of a table element, after any caption, colgroup, and thead elements, but only if there are no tbody elements that are children of the table element.
Content model:
Zero or more td, th, and script-supporting elements.
text/html 中的标签省略
A tr element's end tag can be omitted if the tr element is immediately followed by another tr element, or if there is no more content in the parent element.
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLTableRowElement : HTMLElement {
  [HTMLConstructor] constructor();

  readonly attribute long rowIndex;
  readonly attribute long sectionRowIndex;
  [SameObject] readonly attribute HTMLCollection cells;
  HTMLTableCellElement insertCell(optional long index = -1);
  [CEReactions] undefined deleteCell(long index);

  // also has obsolete members
};

The tr element represents a row of cells in a table.

The tr element takes part in the table model.

tr . rowIndex

HTMLTableRowElement/rowIndex

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the position of the row in the table's rows list.

Returns −1 if the element isn't in a table.

tr . sectionRowIndex

Returns the position of the row in the table section's rows list.

Returns −1 if the element isn't in a table section.

tr . cells

Returns an HTMLCollection of the td and th elements of the row.

cell = tr . insertCell( [ index ] )

HTMLTableRowElement/insertCell

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Creates a td element, inserts it into the table row at the position given by the argument, and returns the td.

The position is relative to the cells in the row. The index −1, which is the default if the argument is omitted, is equivalent to inserting at the end of the row.

If the given position is less than −1 or greater than the number of cells, throws an "IndexSizeError" DOMException.

tr . deleteCell(index)

Removes the td or th element with the given position in the row.

The position is relative to the cells in the row. The index −1 is equivalent to deleting the last cell of the row.

If the given position is less than −1 or greater than the index of the last cell, or if there are no cells, throws an "IndexSizeError" DOMException.

The rowIndex attribute must, if this element has a parent table element, or a parent tbody, thead, or tfoot element and a grandparent table element, return the index of this tr element in that table element's rows collection. If there is no such table element, then the attribute must return −1.

The sectionRowIndex attribute must, if this element has a parent table, tbody, thead, or tfoot element, return the index of the tr element in the parent element's rows collection (for tables, that's HTMLTableElement's rows collection; for table sections, that's HTMLTableSectionElement's rows collection). If there is no such parent element, then the attribute must return −1.

The cells attribute must return an HTMLCollection rooted at this tr element, whose filter matches only td and th elements that are children of the tr element.

The insertCell(index) method must act as follows:

  1. If index is less than −1 or greater than the number of elements in the cells collection, then throw an "IndexSizeError" DOMException.

  2. Let table cell be the result of creating an element given this tr element's node document, td, and the HTML namespace.

  3. If index is equal to −1 or equal to the number of items in cells collection, then append table cell to this tr element.

  4. Otherwise, insert table cell as a child of this tr element, immediately before the indexth td or th element in the cells collection.

  5. Return table cell.

The deleteCell(index) method must act as follows:

  1. If index is less than −1 or greater than or equal to the number of elements in the cells collection, then throw an "IndexSizeError" DOMException.

  2. If index is −1, then remove the last element in the cells collection from its parent, or do nothing if the cells collection is empty.

  3. Otherwise, remove the indexth element in the cells collection from its parent.

4.9.9 The td element

Element/td

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLTableCellElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Sectioning root.
Contexts in which this element can be used:
As a child of a tr element.
Content model:
Flow content.
text/html 中的标签省略
A td element's end tag can be omitted if the td element is immediately followed by a td or th element, or if there is no more content in the parent element.
Content attributes:
Global attributes
colspan — Number of columns that the cell is to span
rowspan — Number of rows that the cell is to span
headers — The header cells for this cell
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLTableCellElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute unsigned long colSpan;
  [CEReactions] attribute unsigned long rowSpan;
  [CEReactions] attribute DOMString headers;
  readonly attribute long cellIndex;

  [CEReactions] attribute DOMString scope; // only conforming for th elements
  [CEReactions] attribute DOMString abbr;  // only conforming for th elements

  // also has obsolete members
};

The HTMLTableCellElement interface is also used for th elements.

The td element represents a data cell in a table.

The td element and its colspan, rowspan, and headers attributes take part in the table model.

User agents, especially in non-visual environments or where displaying the table as a 2D grid is impractical, may give the user context for the cell when rendering the contents of a cell; for instance, giving its position in the table model, or listing the cell's header cells (as determined by the algorithm for assigning header cells). When a cell's header cells are being listed, user agents may use the value of abbr attributes on those header cells, if any, instead of the contents of the header cells themselves.

In this example, we see a snippet of a web application consisting of a grid of editable cells (essentially a simple spreadsheet). One of the cells has been configured to show the sum of the cells above it. Three have been marked as headings, which use th elements instead of td elements. A script would attach event handlers to these elements to maintain the total.

<table>
 <tr>
  <th><input value="Name">
  <th><input value="Paid ($)">
 <tr>
  <td><input value="Jeff">
  <td><input value="14">
 <tr>
  <td><input value="Britta">
  <td><input value="9">
 <tr>
  <td><input value="Abed">
  <td><input value="25">
 <tr>
  <td><input value="Shirley">
  <td><input value="2">
 <tr>
  <td><input value="Annie">
  <td><input value="5">
 <tr>
  <td><input value="Troy">
  <td><input value="5">
 <tr>
  <td><input value="Pierce">
  <td><input value="1000">
 <tr>
  <th><input value="Total">
  <td><output value="1060">
</table>

4.9.10 The th element

Element/th

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
None.
Contexts in which this element can be used:
As a child of a tr element.
Content model:
Flow content, but with no header, footer, sectioning content, or heading content descendants.
text/html 中的标签省略
A th element's end tag can be omitted if the th element is immediately followed by a td or th element, or if there is no more content in the parent element.
Content attributes:
Global attributes
colspan — Number of columns that the cell is to span
rowspan — Number of rows that the cell is to span
headers — The header cells for this cell
scope — Specifies which cells the header cell applies to
abbr — Alternative label to use for the header cell when referencing the cell in other contexts
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLTableCellElement, as defined for td elements.

The th element represents a header cell in a table.

The th element may have a scope content attribute specified. The scope attribute is an enumerated attribute with five states, four of which have explicit keywords:

The row keyword, which maps to the row state
The row state means the header cell applies to some of the subsequent cells in the same row(s).
The col keyword, which maps to the column state
The column state means the header cell applies to some of the subsequent cells in the same column(s).
The rowgroup keyword, which maps to the row group state
The row group state means the header cell applies to all the remaining cells in the row group. A th element's scope attribute must not be in the row group state if the element is not anchored in a row group.
The colgroup keyword, which maps to the column group state
The column group state means the header cell applies to all the remaining cells in the column group. A th element's scope attribute must not be in the column group state if the element is not anchored in a column group.
The auto state
The auto state makes the header cell apply to a set of cells selected based on context.

The scope attribute's missing value default and invalid value default are the auto state.

The th element may have an abbr content attribute specified. Its value must be an alternative label for the header cell, to be used when referencing the cell in other contexts (e.g. when describing the header cells that apply to a data cell). It is typically an abbreviated form of the full header cell, but can also be an expansion, or merely a different phrasing.

The th element and its colspan, rowspan, headers, and scope attributes take part in the table model.

The following example shows how the scope attribute's rowgroup value affects which data cells a header cell applies to.

Here is a markup fragment showing a table:

<table>
 <thead>
  <tr> <th> ID <th> Measurement <th> Average <th> Maximum
 <tbody>
  <tr> <td> <th scope=rowgroup> Cats <td> <td>
  <tr> <td> 93 <th scope=row> Legs <td> 3.5 <td> 4
  <tr> <td> 10 <th scope=row> Tails <td> 1 <td> 1
 <tbody>
  <tr> <td> <th scope=rowgroup> English speakers <td> <td>
  <tr> <td> 32 <th scope=row> Legs <td> 2.67 <td> 4
  <tr> <td> 35 <th scope=row> Tails <td> 0.33 <td> 1
</table>

This would result in the following table:

ID Measurement Average Maximum
Cats
93 Legs 3.5 4
10 Tails 1 1
English speakers
32 Legs 2.67 4
35 Tails 0.33 1

The headers in the first row all apply directly down to the rows in their column.

The headers with the explicit scope attributes apply to all the cells in their row group other than the cells in the first column.

The remaining headers apply just to the cells to the right of them.

4.9.11 Attributes common to td and th elements

The td and th elements may have a colspan content attribute specified, whose value must be a valid non-negative integer greater than zero and less than or equal to 1000.

The td and th elements may also have a rowspan content attribute specified, whose value must be a valid non-negative integer less than or equal to 65534. For this attribute, the value zero means that the cell is to span all the remaining rows in the row group.

These attributes give the number of columns and rows respectively that the cell is to span. These attributes must not be used to overlap cells, as described in the description of the table model.


The td and th element may have a headers content attribute specified. The headers attribute, if specified, must contain a string consisting of an unordered set of unique space-separated tokens, none of which are identical to another token and each of which must have the value of an ID of a th element taking part in the same table as the td or th element (as defined by the table model).

A th element with ID id is said to be directly targeted by all td and th elements in the same table that have headers attributes whose values include as one of their tokens the ID id. A th element A is said to be targeted by a th or td element B if either A is directly targeted by B or if there exists an element C that is itself targeted by the element B and A is directly targeted by C.

A th element must not be targeted by itself.

The colspan, rowspan, and headers attributes take part in the table model.


cell . cellIndex

Returns the position of the cell in the row's cells list. This does not necessarily correspond to the x-position of the cell in the table, since earlier cells might cover multiple rows or columns.

Returns −1 if the element isn't in a row.

The colSpan IDL attribute must reflect the colspan content attribute. It is clamped to the range [1, 1000], and its default value is 1.

The rowSpan IDL attribute must reflect the rowspan content attribute. It is clamped to the range [0, 65534], and its default value is 1.

The headers IDL attribute must reflect the content attribute of the same name.

The cellIndex IDL attribute must, if the element has a parent tr element, return the index of the cell's element in the parent element's cells collection. If there is no such parent element, then the attribute must return −1.

The scope IDL attribute must reflect the content attribute of the same name, limited to only known values.

The abbr IDL attribute must reflect the content attribute of the same name.

4.9.12 Processing model

The various table elements and their content attributes together define the table model.

A table consists of cells aligned on a two-dimensional grid of slots with coordinates (x, y). The grid is finite, and is either empty or has one or more slots. If the grid has one or more slots, then the x coordinates are always in the range 0 ≤ x < xwidth, and the y coordinates are always in the range 0 ≤ y < yheight. If one or both of xwidth and yheight are zero, then the table is empty (has no slots). Tables correspond to table elements.

A cell is a set of slots anchored at a slot (cellx, celly), and with a particular width and height such that the cell covers all the slots with coordinates (x, y) where cellx ≤ x < cellx+width and celly ≤ y < celly+height. Cells can either be data cells or header cells. Data cells correspond to td elements, and header cells correspond to th elements. Cells of both types can have zero or more associated header cells.

It is possible, in certain error cases, for two cells to occupy the same slot.

A row is a complete set of slots from x=0 to x=xwidth-1, for a particular value of y. Rows usually correspond to tr elements, though a row group can have some implied rows at the end in some cases involving cells spanning multiple rows.

A column is a complete set of slots from y=0 to y=yheight-1, for a particular value of x. Columns can correspond to col elements. In the absence of col elements, columns are implied.

A row group is a set of rows anchored at a slot (0, groupy) with a particular height such that the row group covers all the slots with coordinates (x, y) where 0 ≤ x < xwidth and groupy ≤ y < groupy+height. Row groups correspond to tbody, thead, and tfoot elements. Not every row is necessarily in a row group.

A column group is a set of columns anchored at a slot (groupx, 0) with a particular width such that the column group covers all the slots with coordinates (x, y) where groupx ≤ x < groupx+width and 0 ≤ y < yheight. Column groups correspond to colgroup elements. Not every column is necessarily in a column group.

Row groups cannot overlap each other. Similarly, column groups cannot overlap each other.

A cell cannot cover slots that are from two or more row groups. It is, however, possible for a cell to be in multiple column groups. All the slots that form part of one cell are part of zero or one row groups and zero or more column groups.

In addition to cells, columns, rows, row groups, and column groups, tables can have a caption element associated with them. This gives the table a heading, or legend.

A table model error is an error with the data represented by table elements and their descendants. Documents must not have table model errors.

4.9.12.1 Forming a table

To determine which elements correspond to which slots in a table associated with a table element, to determine the dimensions of the table (xwidth and yheight), and to determine if there are any table model errors, user agents must use the following algorithm:

  1. Let xwidth be zero.

  2. Let yheight be zero.

  3. Let pending tfoot elements be a list of tfoot elements, initially empty.

  4. Let the table be the table represented by the table element. The xwidth and yheight variables give the table's dimensions. The table is initially empty.

  5. If the table element has no children elements, then return the table (which will be empty).

  6. Associate the first caption element child of the table element with the table. If there are no such children, then it has no associated caption element.

  7. Let the current element be the first element child of the table element.

    If a step in this algorithm ever requires the current element to be advanced to the next child of the table when there is no such next child, then the user agent must jump to the step labeled end, near the end of this algorithm.

  8. While the current element is not one of the following elements, advance the current element to the next child of the table:

  9. If the current element is a colgroup, follow these substeps:

    1. Column groups: Process the current element according to the appropriate case below:

      If the current element has any col element children

      Follow these steps:

      1. Let xstart have the value of xwidth.

      2. Let the current column be the first col element child of the colgroup element.

      3. Columns: If the current column col element has a span attribute, then parse its value using the rules for parsing non-negative integers.

        If the result of parsing the value is not an error or zero, then let span be that value.

        Otherwise, if the col element has no span attribute, or if trying to parse the attribute's value resulted in an error or zero, then let span be 1.

        If span is greater than 1000, let it be 1000 instead.

      4. Increase xwidth by span.

      5. Let the last span columns in the table correspond to the current column col element.

      6. If current column is not the last col element child of the colgroup element, then let the current column be the next col element child of the colgroup element, and return to the step labeled columns.

      7. Let all the last columns in the table from x=xstart to x=xwidth-1 form a new column group, anchored at the slot (xstart, 0), with width xwidth-xstart, corresponding to the colgroup element.

      If the current element has no col element children
      1. If the colgroup element has a span attribute, then parse its value using the rules for parsing non-negative integers.

        If the result of parsing the value is not an error or zero, then let span be that value.

        Otherwise, if the colgroup element has no span attribute, or if trying to parse the attribute's value resulted in an error or zero, then let span be 1.

        If span is greater than 1000, let it be 1000 instead.

      2. Increase xwidth by span.

      3. Let the last span columns in the table form a new column group, anchored at the slot (xwidth-span, 0), with width span, corresponding to the colgroup element.

    2. Advance the current element to the next child of the table.

    3. While the current element is not one of the following elements, advance the current element to the next child of the table:

    4. If the current element is a colgroup element, jump to the step labeled column groups above.

  10. Let ycurrent be zero.

  11. Let the list of downward-growing cells be an empty list.

  12. Rows: While the current element is not one of the following elements, advance the current element to the next child of the table:

  13. If the current element is a tr, then run the algorithm for processing rows, advance the current element to the next child of the table, and return to the step labeled rows.

  14. Run the algorithm for ending a row group.

  15. If the current element is a tfoot, then add that element to the list of pending tfoot elements, advance the current element to the next child of the table, and return to the step labeled rows.

  16. The current element is either a thead or a tbody.

    Run the algorithm for processing row groups.

  17. Advance the current element to the next child of the table.

  18. Return to the step labeled rows.

  19. End: For each tfoot element in the list of pending tfoot elements, in tree order, run the algorithm for processing row groups.

  20. If there exists a row or column in the table containing only slots that do not have a cell anchored to them, then this is a table model error.

  21. Return the table.

The algorithm for processing row groups, which is invoked by the set of steps above for processing thead, tbody, and tfoot elements, is:

  1. Let ystart have the value of yheight.

  2. For each tr element that is a child of the element being processed, in tree order, run the algorithm for processing rows.

  3. If yheight > ystart, then let all the last rows in the table from y=ystart to y=yheight-1 form a new row group, anchored at the slot with coordinate (0, ystart), with height yheight-ystart, corresponding to the element being processed.

  4. Run the algorithm for ending a row group.

The algorithm for ending a row group, which is invoked by the set of steps above when starting and ending a block of rows, is:

  1. While ycurrent is less than yheight, follow these steps:

    1. Run the algorithm for growing downward-growing cells.

    2. Increase ycurrent by 1.

  2. Empty the list of downward-growing cells.

The algorithm for processing rows, which is invoked by the set of steps above for processing tr elements, is:

  1. If yheight is equal to ycurrent, then increase yheight by 1. (ycurrent is never greater than yheight.)

  2. Let xcurrent be 0.

  3. Run the algorithm for growing downward-growing cells.

  4. If the tr element being processed has no td or th element children, then increase ycurrent by 1, abort this set of steps, and return to the algorithm above.

  5. Let current cell be the first td or th element child in the tr element being processed.

  6. Cells: While xcurrent is less than xwidth and the slot with coordinate (xcurrent, ycurrent) already has a cell assigned to it, increase xcurrent by 1.

  7. If xcurrent is equal to xwidth, increase xwidth by 1. (xcurrent is never greater than xwidth.)

  8. If the current cell has a colspan attribute, then parse that attribute's value, and let colspan be the result.

    If parsing that value failed, or returned zero, or if the attribute is absent, then let colspan be 1, instead.

    If colspan is greater than 1000, let it be 1000 instead.

  9. If the current cell has a rowspan attribute, then parse that attribute's value, and let rowspan be the result.

    If parsing that value failed or if the attribute is absent, then let rowspan be 1, instead.

    If rowspan is greater than 65534, let it be 65534 instead.

  10. If rowspan is zero and the table element's node document is not set to quirks mode, then let cell grows downward be true, and set rowspan to 1. Otherwise, let cell grows downward be false.

  11. If xwidth < xcurrent+colspan, then let xwidth be xcurrent+colspan.

  12. If yheight < ycurrent+rowspan, then let yheight be ycurrent+rowspan.

  13. Let the slots with coordinates (x, y) such that xcurrent ≤ x < xcurrent+colspan and ycurrent ≤ y < ycurrent+rowspan be covered by a new cell c, anchored at (xcurrent, ycurrent), which has width colspan and height rowspan, corresponding to the current cell element.

    If the current cell element is a th element, let this new cell c be a header cell; otherwise, let it be a data cell.

    To establish which header cells apply to the current cell element, use the algorithm for assigning header cells described in the next section.

    If any of the slots involved already had a cell covering them, then this is a table model error. Those slots now have two cells overlapping.

  14. If cell grows downward is true, then add the tuple {c, xcurrent, colspan} to the list of downward-growing cells.

  15. Increase xcurrent by colspan.

  16. If current cell is the last td or th element child in the tr element being processed, then increase ycurrent by 1, abort this set of steps, and return to the algorithm above.

  17. Let current cell be the next td or th element child in the tr element being processed.

  18. Return to the step labeled cells.

When the algorithms above require the user agent to run the algorithm for growing downward-growing cells, the user agent must, for each {cell, cellx, width} tuple in the list of downward-growing cells, if any, extend the cell cell so that it also covers the slots with coordinates (x, ycurrent), where cellx ≤ x < cellx+width.

4.9.12.2 Forming relationships between data cells and header cells

Each cell can be assigned zero or more header cells. The algorithm for assigning header cells to a cell principal cell is as follows.

  1. Let header list be an empty list of cells.

  2. Let (principalx, principaly) be the coordinate of the slot to which the principal cell is anchored.

  3. If the principal cell has a headers attribute specified
    1. Take the value of the principal cell's headers attribute and split it on ASCII whitespace, letting id list be the list of tokens obtained.

    2. For each token in the id list, if the first element in the Document with an ID equal to the token is a cell in the same table, and that cell is not the principal cell, then add that cell to header list.

    If principal cell does not have a headers attribute specified
    1. Let principalwidth be the width of the principal cell.

    2. Let principalheight be the height of the principal cell.

    3. For each value of y from principaly to principaly+principalheight-1, run the internal algorithm for scanning and assigning header cells, with the principal cell, the header list, the initial coordinate (principalx,y), and the increments Δx=−1 and Δy=0.

    4. For each value of x from principalx to principalx+principalwidth-1, run the internal algorithm for scanning and assigning header cells, with the principal cell, the header list, the initial coordinate (x,principaly), and the increments Δx=0 and Δy=−1.

    5. If the principal cell is anchored in a row group, then add all header cells that are row group headers and are anchored in the same row group with an x-coordinate less than or equal to principalx+principalwidth-1 and a y-coordinate less than or equal to principaly+principalheight-1 to header list.

    6. If the principal cell is anchored in a column group, then add all header cells that are column group headers and are anchored in the same column group with an x-coordinate less than or equal to principalx+principalwidth-1 and a y-coordinate less than or equal to principaly+principalheight-1 to header list.

  4. Remove all the empty cells from the header list.

  5. Remove any duplicates from the header list.

  6. Remove principal cell from the header list if it is there.

  7. Assign the headers in the header list to the principal cell.

The internal algorithm for scanning and assigning header cells, given a principal cell, a header list, an initial coordinate (initialx, initialy), and Δx and Δy increments, is as follows:

  1. Let x equal initialx.

  2. Let y equal initialy.

  3. Let opaque headers be an empty list of cells.

  4. If principal cell is a header cell

    Let in header block be true, and let headers from current header block be a list of cells containing just the principal cell.

    Otherwise

    Let in header block be false and let headers from current header block be an empty list of cells.

  5. Loop: Increment x by Δx; increment y by Δy.

    For each invocation of this algorithm, one of Δx and Δy will be −1, and the other will be 0.

  6. If either x or y are less than 0, then abort this internal algorithm.

  7. If there is no cell covering slot (x, y), or if there is more than one cell covering slot (x, y), return to the substep labeled loop.

  8. Let current cell be the cell covering slot (x, y).

  9. If current cell is a header cell
    1. Set in header block to true.

    2. Add current cell to headers from current header block.

    3. Let blocked be false.

    4. If Δx is 0

      If there are any cells in the opaque headers list anchored with the same x-coordinate as the current cell, and with the same width as current cell, then let blocked be true.

      If the current cell is not a column header, then let blocked be true.

      If Δy is 0

      If there are any cells in the opaque headers list anchored with the same y-coordinate as the current cell, and with the same height as current cell, then let blocked be true.

      If the current cell is not a row header, then let blocked be true.

    5. If blocked is false, then add the current cell to the headers list.

    If current cell is a data cell and in header block is true

    Set in header block to false. Add all the cells in headers from current header block to the opaque headers list, and empty the headers from current header block list.

  10. Return to the step labeled loop.

A header cell anchored at the slot with coordinate (x, y) with width width and height height is said to be a column header if any of the following conditions are true:

A header cell anchored at the slot with coordinate (x, y) with width width and height height is said to be a row header if any of the following conditions are true:

A header cell is said to be a column group header if its scope attribute is in the column group state.

A header cell is said to be a row group header if its scope attribute is in the row group state.

A cell is said to be an empty cell if it contains no elements and its child text content, if any, consists only of ASCII whitespace.

4.9.13 示例

This section is non-normative.

下面的例子是 Smithsonian physical tables, Volume 71 中的表 45 后半部分的标记:

<table>
 <caption>Specification values: <b>Steel</b>, <b>Castings</b>,
 Ann. A.S.T.M. A27-16, Class B;* P max. 0.06; S max. 0.05.</caption>
 <thead>
  <tr>
   <th rowspan=2>Grade.</th>
   <th rowspan=2>Yield Point.</th>
   <th colspan=2>Ultimate tensile strength</th>
   <th rowspan=2>Per cent elong. 50.8mm or 2 in.</th>
   <th rowspan=2>Per cent reduct. area.</th>
  </tr>
  <tr>
   <th>kg/mm<sup>2</sup></th>
   <th>lb/in<sup>2</sup></th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>Hard</td>
   <td>0.45 ultimate</td>
   <td>56.2</td>
   <td>80,000</td>
   <td>15</td>
   <td>20</td>
  </tr>
  <tr>
   <td>Medium</td>
   <td>0.45 ultimate</td>
   <td>49.2</td>
   <td>70,000</td>
   <td>18</td>
   <td>25</td>
  </tr>
  <tr>
   <td>Soft</td>
   <td>0.45 ultimate</td>
   <td>42.2</td>
   <td>60,000</td>
   <td>22</td>
   <td>30</td>
  </tr>
 </tbody>
</table>

这个表格看起来可能是这样:

Specification values: Steel, Castings, Ann. A.S.T.M. A27-16, Class B;* P max. 0.06; S max. 0.05.
Grade.Yield Point.Ultimate tensile strengthPer cent elong. 50.8 mm or 2 in.Per cent reduct. area.
kg/mm2lb/in2
Hard0.45 ultimate56.280,0001520
Medium0.45 ultimate49.270,0001825
Soft0.45 ultimate42.260,0002230

以下显示的是 Apple 公司 2008 财年 10-K 文件的第 46 页的毛利润表的标记:

<table>
 <thead>
  <tr>
   <th>
   <th>2008
   <th>2007
   <th>2006
 <tbody>
  <tr>
   <th>Net sales
   <td>$ 32,479
   <td>$ 24,006
   <td>$ 19,315
  <tr>
   <th>Cost of sales
   <td>  21,334
   <td>  15,852
   <td>  13,717
 <tbody>
  <tr>
   <th>Gross margin
   <td>$ 11,145
   <td>$  8,154
   <td>$  5,598
 <tfoot>
  <tr>
   <th>Gross margin percentage
   <td>34.3%
   <td>34.0%
   <td>29.0%
</table>

这个表格看起来可能是这样:

2008 2007 2006
Net sales $ 32,479 $ 24,006 $ 19,315
Cost of sales 21,334 15,852 13,717
Gross margin $ 11,145 $ 8,154 $ 5,598
Gross margin percentage 34.3% 34.0% 29.0%

下面是该文档中同一页下方的经营费用表的标记:

<table>
 <colgroup> <col>
 <colgroup> <col> <col> <col>
 <thead>
  <tr> <th> <th>2008 <th>2007 <th>2006
 <tbody>
  <tr> <th scope=rowgroup> Research and development
       <td> $ 1,109 <td> $ 782 <td> $ 712
  <tr> <th scope=row> Percentage of net sales
       <td> 3.4% <td> 3.3% <td> 3.7%
 <tbody>
  <tr> <th scope=rowgroup> Selling, general, and administrative
       <td> $ 3,761 <td> $ 2,963 <td> $ 2,433
  <tr> <th scope=row> Percentage of net sales
       <td> 11.6% <td> 12.3% <td> 12.6%
</table>

这个表格看起来可能是这样:

2008 2007 2006
Research and development $ 1,109 $ 782 $ 712
Percentage of net sales 3.4% 3.3% 3.7%
Selling, general, and administrative $ 3,761 $ 2,963 $ 2,433
Percentage of net sales 11.6% 12.3% 12.6%

4.10 表单

Element#Forms

Support in all current engines.

Firefox4+Safari4+Chrome61+
Opera52+Edge79+
Edge (Legacy)16+Internet Explorer10+
Firefox Android5+Safari iOS3.2+Chrome Android61+WebView Android61+Samsung Internet8.0+Opera Android47+

4.10.1 概述

This section is non-normative.

表单是一种网页组件,可以包含表单控件如文本,按钮,复选框,范围或颜色选择器控件。 用户可以与这样的表单进行交互并提供数据,随后这些数据被发送到服务器用于进一步处理 (例如返回搜索或计算结果)。在许多情况下都不需要客户端脚本,尽管提供了这样的 API, 脚本可以用这些 API 增强用户体验,或者将表单用于提交数据之外的用途。

编写一个表单包含几个步骤,可以按任意顺序进行: 编写用户界面,实现服务器端处理以及配置用户界面以与服务器进行通信。

4.10.1.1 编写表单的用户界面

This section is non-normative.

为了这个简短的介绍,我们将创建一个 Pizza 订购表单。

表单都以 form 元素开始,其中可以放置一些控件。 多数控件都由 input 元素表示,它默认提供一个文本控件。 使用 label 元素来描述控件;标签文本和控件自己都会进入 label 元素内。表单的每一部分都是一个 段落,一般会用 p 元素来与其他部分分隔。 放到一起,可以这样询问顾客的名字:

<form>
 <p><label>Customer name: <input></label></p>
</form>

为了让用户选择 Pizza 的大小,我们可以使用一组单选按钮。 单选按钮也是用 input 元素,这次设置一个 type 属性,值为 radio。 为了让单选按钮成组,要使用 name 属性给它们一样的名字。 为了让一批控件成为一组,比如这个例子中的单选按钮,可以使用 fieldset 元素。这样的控件组的标题由 fieldset 中的第一个元素给出, 这个元素必须是一个 legend 元素。

<form>
 <p><label>Customer name: <input></label></p>
 <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size> Small </label></p>
  <p><label> <input type=radio name=size> Medium </label></p>
  <p><label> <input type=radio name=size> Large </label></p>
 </fieldset>
</form>

我们高亮了上一个步骤中的改变。

我们可以使用复选框来选择配料。这些复选框也使用 input 元素, 它们的 type 属性值为 checkbox

<form>
 <p><label>Customer name: <input></label></p>
 <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size> Small </label></p>
  <p><label> <input type=radio name=size> Medium </label></p>
  <p><label> <input type=radio name=size> Large </label></p>
 </fieldset>
 <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox> Bacon </label></p>
  <p><label> <input type=checkbox> Extra Cheese </label></p>
  <p><label> <input type=checkbox> Onion </label></p>
  <p><label> <input type=checkbox> Mushroom </label></p>
 </fieldset>
</form>

这个 pizza 店总会犯一些错误,因此需要顾客的联系方式。 为此我们可以使用电话号码的表单控件(type 属性设为 telinput 元素), 以及 e-mail 地址(type 属性设为 emailinput 元素):

<form>
 <p><label>Customer name: <input></label></p>
 <p><label>Telephone: <input type=tel></label></p>
 <p><label>E-mail address: <input type=email></label></p>
 <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size> Small </label></p>
  <p><label> <input type=radio name=size> Medium </label></p>
  <p><label> <input type=radio name=size> Large </label></p>
 </fieldset>
 <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox> Bacon </label></p>
  <p><label> <input type=checkbox> Extra Cheese </label></p>
  <p><label> <input type=checkbox> Onion </label></p>
  <p><label> <input type=checkbox> Mushroom </label></p>
 </fieldset>
</form>

我们可以使用 type 属性设为 timeinput 元素来询问配送时间。 很多控件都可以设置可选值的范围;这个例子中我们关心的属性是 min, maxstep。这些属性分别用来设置最小时间,最大时间, 以及允许的值之间的间隔(单位为秒)。这个 pizza 店只在 11am 到 9pm 之间配送, 而且不保证精确到 15 分钟以内,我们可以这样写:

<form>
 <p><label>Customer name: <input></label></p>
 <p><label>Telephone: <input type=tel></label></p>
 <p><label>E-mail address: <input type=email></label></p>
 <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size> Small </label></p>
  <p><label> <input type=radio name=size> Medium </label></p>
  <p><label> <input type=radio name=size> Large </label></p>
 </fieldset>
 <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox> Bacon </label></p>
  <p><label> <input type=checkbox> Extra Cheese </label></p>
  <p><label> <input type=checkbox> Onion </label></p>
  <p><label> <input type=checkbox> Mushroom </label></p>
 </fieldset>
 <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></p>
</form>

textarea 元素可以用来提供多行文本。例如我们要用它来给顾客提供一个地方,编写配送备注:

<form>
 <p><label>Customer name: <input></label></p>
 <p><label>Telephone: <input type=tel></label></p>
 <p><label>E-mail address: <input type=email></label></p>
 <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size> Small </label></p>
  <p><label> <input type=radio name=size> Medium </label></p>
  <p><label> <input type=radio name=size> Large </label></p>
 </fieldset>
 <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox> Bacon </label></p>
  <p><label> <input type=checkbox> Extra Cheese </label></p>
  <p><label> <input type=checkbox> Onion </label></p>
  <p><label> <input type=checkbox> Mushroom </label></p>
 </fieldset>
 <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></p>
 <p><label>Delivery instructions: <textarea></textarea></label></p>
</form>

最后,为了让表单可以提交我们要用一个 button 元素:

<form>
 <p><label>Customer name: <input></label></p>
 <p><label>Telephone: <input type=tel></label></p>
 <p><label>E-mail address: <input type=email></label></p>
 <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size> Small </label></p>
  <p><label> <input type=radio name=size> Medium </label></p>
  <p><label> <input type=radio name=size> Large </label></p>
 </fieldset>
 <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox> Bacon </label></p>
  <p><label> <input type=checkbox> Extra Cheese </label></p>
  <p><label> <input type=checkbox> Onion </label></p>
  <p><label> <input type=checkbox> Mushroom </label></p>
 </fieldset>
 <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900"></label></p>
 <p><label>Delivery instructions: <textarea></textarea></label></p>
 <p><button>Submit order</button></p>
</form>
4.10.1.2 实现服务器端表单处理

This section is non-normative.

编写服务器端处理程序的具体的细节超出了本规范的范围。 这个概述中我们会假设 https://pizza.example.com/order.cgi 处的脚本已经配置为接受 application/x-www-form-urlencoded 格式的表单提交, 而且 HTTP POST 消息体中会包含以下参数:

custname
顾客的名字
custtel
顾客的手机号
custemail
顾客的 e-mail 地址
size
Pizza 大小,可以是 small, mediumlarge
topping
选中的每个配料,允许的值包括 bacon, cheese, onionmushroom
delivery
配送时间
comments
配送备注
4.10.1.3 配置表单与服务器通信

This section is non-normative.

表单提交以多种方式暴露给服务器,通常是 HTTP GET 或 POST 请求。 在 form 元素上使用 method 属性来指定使用哪种方法。 这还没有指定表单数据的编码方式,指定编码方式要使用 enctype 属性。你还需要使用 action 属性来指定 处理提交的数据的服务的 URL

每个需要提交的表单控件都要有一个名字来对应提交的数据。 我们已经为单选按钮组指定了名字;这个属性(name)也指定了提交的名字。 单选按钮可以之间可以通过(使用 value 属性) 给它们不同的值来区分。

多个控件可以有同样的名字;例如我们给所有复选框一样的名字,服务器检查那个名字的哪些值提交了上来。 — 像单选按钮一样,也通过 value 属性给它们不重复的值。

鉴于上一小节的设置,表单现在变成了:

<form method="post"
      enctype="application/x-www-form-urlencoded"
      action="https://pizza.example.com/order.cgi">
 <p><label>Customer name: <input name="custname"></label></p>
 <p><label>Telephone: <input type=tel name="custtel"></label></p>
 <p><label>E-mail address: <input type=email name="custemail"></label></p>
 <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size value="small"> Small </label></p>
  <p><label> <input type=radio name=size value="medium"> Medium </label></p>
  <p><label> <input type=radio name=size value="large"> Large </label></p>
 </fieldset>
 <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p>
  <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p>
  <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p>
  <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p>
 </fieldset>
 <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery"></label></p>
 <p><label>Delivery instructions: <textarea name="comments"></textarea></label></p>
 <p><button>Submit order</button></p>
</form>

有些属性的值用引号包含,有些没有,但这没有特别的含义。 HTML 语法允许很多种合法的方式来指定属性,如 语法部分 所述。

例如,如果顾客输入 "Denise Lawrence" 作为名字,"555-321-8642" 作为电话号,没有指定 e-mail 地址, 要一个中等大小的 Pizza,选择了 Extra Cheese 和 Mushroom 配料, 输入的配送时间是 7pm 并在配送备注部分留空,用户代理会提交下面内容到在线 Web 服务:

custname=Denise+Lawrence&custtel=555-321-8642&custemail=&size=medium&topping=cheese&topping=mushroom&delivery=19%3A00&comments=
4.10.1.4 客户端表单验证

Form_validation

Support in all current engines.

Firefox4+Safari5+Chrome4+
Opera≤12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS4+Chrome Android18+WebView Android≤37+Samsung Internet1.0+Opera Android≤12.1+

This section is non-normative.

可以通过表单标记使得用户代理可以在表单提交之前检查用户输入。 服务器仍然必须校验输入是有效的(因为恶意用户可以很容易绕过表单验证), 但这使我们可以避免因为只能在服务器上检查而造成用户等待。

最简单的标记是 required 属性, 可以在 input 元素上指定,表示只有给出值之后表单才可以提交。 把这个属性添加到顾客名字、Pizza 大小和配送时间字段,在用户没填写这些字段就提交表单时, 我们可以让用户代理提示用户。

<form method="post"
      enctype="application/x-www-form-urlencoded"
      action="https://pizza.example.com/order.cgi">
 <p><label>Customer name: <input name="custname" required></label></p>
 <p><label>Telephone: <input type=tel name="custtel"></label></p>
 <p><label>E-mail address: <input type=email name="custemail"></label></p>
 <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size required value="small"> Small </label></p>
  <p><label> <input type=radio name=size required value="medium"> Medium </label></p>
  <p><label> <input type=radio name=size required value="large"> Large </label></p>
 </fieldset>
 <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p>
  <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p>
  <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p>
  <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p>
 </fieldset>
 <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p>
 <p><label>Delivery instructions: <textarea name="comments"></textarea></label></p>
 <p><button>Submit order</button></p>
</form>

也可以使用 maxlength 属性来限制输入的长度。 把这个属性添加到 textarea 元素上,我们可以限制用户输入到 1000 字符, 防止他们给配送员编写长文而不聚焦重点。

<form method="post"
      enctype="application/x-www-form-urlencoded"
      action="https://pizza.example.com/order.cgi">
 <p><label>Customer name: <input name="custname" required></label></p>
 <p><label>Telephone: <input type=tel name="custtel"></label></p>
 <p><label>E-mail address: <input type=email name="custemail"></label></p>
 <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size required value="small"> Small </label></p>
  <p><label> <input type=radio name=size required value="medium"> Medium </label></p>
  <p><label> <input type=radio name=size required value="large"> Large </label></p>
 </fieldset>
 <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p>
  <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p>
  <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p>
  <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p>
 </fieldset>
 <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p>
 <p><label>Delivery instructions: <textarea name="comments" maxlength=1000></textarea></label></p>
 <p><button>Submit order</button></p>
</form>

提交表单时,每个不合法的表单控件上,以及 form 元素上都会触发 invalid 事件, 这个事件可以用来显示表单存在哪些问题的一个描述,因为浏览器自己只会逐个报告问题。

4.10.1.5 启用表单控件的客户端自动填充

This section is non-normative.

有些浏览器尝试帮助用户自动填充表单控件,避免让用户每次重新输入。例如询问用户电话号码的字段就可以自动填充为用户的手机号码。

为了帮助用户代理做自动填充,可以使用 autocomplete 属性来描述字段的用途。下面这个表单的例子,Pizza 配送的用户信息中三个字段都可以这样自动填充: 添加相应的信息后看起来是这样的:

<form method="post"
      enctype="application/x-www-form-urlencoded"
      action="https://pizza.example.com/order.cgi">
 <p><label>Customer name: <input name="custname" required autocomplete="shipping name"></label></p>
 <p><label>Telephone: <input type=tel name="custtel" autocomplete="shipping tel"></label></p>
 <p><label>E-mail address: <input type=email name="custemail" autocomplete="shipping email"></label></p>
 <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size required value="small"> Small </label></p>
  <p><label> <input type=radio name=size required value="medium"> Medium </label></p>
  <p><label> <input type=radio name=size required value="large"> Large </label></p>
 </fieldset>
 <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p>
  <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p>
  <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p>
  <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p>
 </fieldset>
 <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p>
 <p><label>Delivery instructions: <textarea name="comments" maxlength=1000></textarea></label></p>
 <p><button>Submit order</button></p>
</form>
4.10.1.6 Improving the user experience on mobile devices

This section is non-normative.

Some devices, in particular those with virtual keyboards can provide the user with multiple input modalities. For example, when typing in a credit card number the user may wish to only see keys for digits 0-9, while when typing in their name they may wish to see a form field that by default capitalizes each word.

Using the inputmode attribute we can select appropriate input modalities:

<form method="post"
      enctype="application/x-www-form-urlencoded"
      action="https://pizza.example.com/order.cgi">
 <p><label>Customer name: <input name="custname" required autocomplete="shipping name"></label></p>
 <p><label>Telephone: <input type=tel name="custtel" autocomplete="shipping tel"></label></p>
 <p><label>Buzzer code: <input name="custbuzz" inputmode="numeric"></label></p>
 <p><label>Email address: <input type=email name="custemail" autocomplete="shipping email"></label></p>
 <fieldset>
  <legend> Pizza Size </legend>
  <p><label> <input type=radio name=size required value="small"> Small </label></p>
  <p><label> <input type=radio name=size required value="medium"> Medium </label></p>
  <p><label> <input type=radio name=size required value="large"> Large </label></p>
 </fieldset>
 <fieldset>
  <legend> Pizza Toppings </legend>
  <p><label> <input type=checkbox name="topping" value="bacon"> Bacon </label></p>
  <p><label> <input type=checkbox name="topping" value="cheese"> Extra Cheese </label></p>
  <p><label> <input type=checkbox name="topping" value="onion"> Onion </label></p>
  <p><label> <input type=checkbox name="topping" value="mushroom"> Mushroom </label></p>
 </fieldset>
 <p><label>Preferred delivery time: <input type=time min="11:00" max="21:00" step="900" name="delivery" required></label></p>
 <p><label>Delivery instructions: <textarea name="comments" maxlength=1000></textarea></label></p>
 <p><button>Submit order</button></p>
</form>
4.10.1.7 The difference between the field type, the autofill field name, and the input modality

This section is non-normative.

The type, autocomplete, and inputmode attributes can seem confusingly similar. For instance, in all three cases, the string "email" is a valid value. This section attempts to illustrate the difference between the three attributes and provides advice suggesting how to use them.

The type attribute on input elements decides what kind of control the user agent will use to expose the field. Choosing between different values of this attribute is the same choice as choosing whether to use an input element, a textarea element, a select element, etc.

The autocomplete attribute, in contrast, describes what the value that the user will enter actually represents. Choosing between different values of this attribute is the same choice as choosing what the label for the element will be.

First, consider telephone numbers. If a page is asking for a telephone number from the user, the right form control to use is <input type=tel>. However, which autocomplete value to use depends on which phone number the page is asking for, whether they expect a telephone number in the international format or just the local format, and so forth.

For example, a page that forms part of a checkout process on an e-commerce site for a customer buying a gift to be shipped to a friend might need both the buyer's telephone number (in case of payment issues) and the friend's telephone number (in case of delivery issues). If the site expects international phone numbers (with the country code prefix), this could thus look like this:

<p><label>Your phone number: <input type=tel name=custtel autocomplete="billing tel"></label>
<p><label>Recipient's phone number: <input type=tel name=shiptel autocomplete="shipping tel"></label>
<p>Please enter complete phone numbers including the country code prefix, as in "+1 555 123 4567".

But if the site only supports British customers and recipients, it might instead look like this (notice the use of tel-national rather than tel):

<p><label>Your phone number: <input type=tel name=custtel autocomplete="billing tel-national"></label>
<p><label>Recipient's phone number: <input type=tel name=shiptel autocomplete="shipping tel-national"></label>
<p>Please enter complete UK phone numbers, as in "(01632) 960 123".

Now, consider a person's preferred languages. The right autocomplete value is language. However, there could be a number of different form controls used for the purpose: a text control (<input type=text>), a drop-down list (<select>), radio buttons (<input type=radio>), etc. It only depends on what kind of interface is desired.

Finally, consider names. If a page just wants one name from the user, then the relevant control is <input type=text>. If the page is asking for the user's full name, then the relevant autocomplete value is name.

<p><label>Japanese name: <input name="j" type="text" autocomplete="section-jp name"></label>
<label>Romanized name: <input name="e" type="text" autocomplete="section-en name"></label>

In this example, the "section-*" keywords in the autocomplete attributes' values tell the user agent that the two fields expect different names. Without them, the user agent could automatically fill the second field with the value given in the first field when the user gave a value to the first field.

The "-jp" and "-en" parts of the keywords are opaque to the user agent; the user agent cannot guess, from those, that the two names are expected to be in Japanese and English respectively.

Separate from the choices regarding type and autocomplete, the inputmode attribute decides what kind of input modality (e.g., virtual keyboard) to use, when the control is a text control.

Consider credit card numbers. The appropriate input type is not <input type=number>, as explained below; it is instead <input type=text>. To encourage the user agent to use a numeric input modality anyway (e.g., a virtual keyboard displaying only digits), the page would use

<p><label>Credit card number:
                <input name="cc" type="text" inputmode="numeric" pattern="[0-9]{8,19}" autocomplete="cc-number">
</label></p>
4.10.1.8 日期、时间和数字格式

This section is non-normative.

这个 Pizza 配送的例子中,时间的格式为 "HH:MM": 两位数字的小时(24小时格式),以及两位数字的时间。 (还可以指定秒,虽然这个例子中没有必要)

但是在某些时区里展示给用户的时间是不同的。例如在美国仍然经常使用 12 小时的表加一个 am/pm 指示, 比如 "2pm"。在法国通常使用一个 "h" 字符来分隔小时和分钟,例如 "14h00"。

日期也存在类似的问题,更严重的是日期各部分的顺序也总是不一致的。 — 例如在 Cyprus 2003 年 2 月 1 日会写成 "1/2/03", 同样的日期在日本会写成 "2003年02月01日" — 数字也是一样, 在不同的时区小数点和千分点使用的标点也不一样。

因此把 HTML 和表单提交中的时间、日期和数字的格式(即本规范中定义的格式,以及 ISO 8601 标准建立的对计算机可读的时间和日期格式),和 浏览器显示给用户的或浏览器接受用户输入的时间、日期和数字格式区分开来非常重要。

协议中(即 HTML 标记和表单提交)使用的格式是为了使得计算机可读和一致,且与用户的区域设置无关。 例如日期总是表示为 "YYYY-MM-DD",比如 "2003-02-01"。用户永远不应该看到这个格式。

页面给出的时间、日期或数字的按照协议的格式会在显示给用户之前翻译成用户偏好的显示方式 (基于用户偏好或页面自己所在的区域设置)。类似地,在用户使用他们偏好的格式输入时间、日期或数字时, 用户代理把它放回 DOM 或提交之前,要把它转换回协议格式。

这使得页面脚本和服务器可以使用一致的方式来处理时间、日期和数字,不需要支持几十种不同的格式, 同时仍然能够支持用户的需要。

关于表单控件的本地化请参考 实现纪要

4.10.2 Categories

Mostly for historical reasons, elements in this section fall into several overlapping (but subtly different) categories in addition to the usual ones like flow content, phrasing content, and interactive content.

A number of the elements are form-associated elements, which means they can have a form owner.

The form-associated elements fall into several subcategories:

Listed elements

Denotes elements that are listed in the form.elements and fieldset.elements APIs. These elements also have a form content attribute, and a matching form IDL attribute, that allow authors to specify an explicit form owner.

Submittable elements

Denotes elements that can be used for constructing the entry list when a form element is submitted.

Some submittable elements can be, depending on their attributes, buttons. The prose below defines when an element is a button. Some buttons are specifically submit buttons.

Resettable elements

Denotes elements that can be affected when a form element is reset.

Autocapitalize-inheriting elements

Denotes elements that inherit the autocapitalize attribute from their form owner.

Some elements, not all of them form-associated, are categorized as labelable elements. These are elements that can be associated with a label element.

4.10.3 The form element

Element/form

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLFormElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
Categories:
Flow content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Flow content, but with no form element descendants.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
accept-charset — Character encodings to use for form submission
actionURL to use for form submission
autocomplete — Default setting for autofill feature for controls in the form
enctype — Entry list encoding type to use for form submission
method — Variant to use for form submission
name — Name of form to use in the document.forms API
novalidate — Bypass form control validation for form submission
targetBrowsing context for form submission
rel
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window,
 LegacyOverrideBuiltIns,
 LegacyUnenumerableNamedProperties]
interface HTMLFormElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString acceptCharset;
  [CEReactions] attribute USVString action;
  [CEReactions] attribute DOMString autocomplete;
  [CEReactions] attribute DOMString enctype;
  [CEReactions] attribute DOMString encoding;
  [CEReactions] attribute DOMString method;
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute boolean noValidate;
  [CEReactions] attribute DOMString target;
  [CEReactions] attribute DOMString rel;
  [SameObject, PutForwards=value] readonly attribute DOMTokenList relList;

  [SameObject] readonly attribute HTMLFormControlsCollection elements;
  readonly attribute unsigned long length;
  getter Element (unsigned long index);
  getter (RadioNodeList or Element) (DOMString name);

  undefined submit();
  undefined requestSubmit(optional HTMLElement? submitter = null);
  [CEReactions] undefined reset();
  boolean checkValidity();
  boolean reportValidity();
};

The form element represents a hyperlink that can be manipulated through a collection of form-associated elements, some of which can represent editable values that can be submitted to a server for processing.

The accept-charset attribute gives the character encodings that are to be used for the submission. If specified, the value must be an ASCII case-insensitive match for "UTF-8". [ENCODING]

The name attribute represents the form's name within the forms collection. The value must not be the empty string, and the value must be unique amongst the form elements in the forms collection that it is in, if any.

The autocomplete attribute is an enumerated attribute. The attribute has two states. The on keyword maps to the on state, and the off keyword maps to the off state. The attribute may also be omitted. The missing value default and the invalid value default are the on state. The off state indicates that by default, form controls in the form will have their autofill field name set to "off"; the on state indicates that by default, form controls in the form will have their autofill field name set to "on".

The action, enctype, method, novalidate, and target attributes are attributes for form submission.

The rel attribute on form elements controls what kinds of links the elements create. The attribute's value must be a unordered set of unique space-separated tokens. The allowed keywords and their meanings are defined in an earlier section.

rel's supported tokens are the keywords defined in HTML link types which are allowed on form elements, impact the processing model, and are supported by the user agent. The possible supported tokens are noreferrer, noopener, and opener. rel's supported tokens must only include the tokens from this list that the user agent implements the processing model for.

form . elements

HTMLFormElement/elements

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Returns an HTMLFormControlsCollection of the form controls in the form (excluding image buttons for historical reasons).

form . length

HTMLFormElement/length

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the number of form controls in the form (excluding image buttons for historical reasons).

form[index]

Returns the indexth element in the form (excluding image buttons for historical reasons).

form[name]

Returns the form control (or, if there are several, a RadioNodeList of the form controls) in the form with the given ID or name (excluding image buttons for historical reasons); or, if there are none, returns the img element with the given ID.

Once an element has been referenced using a particular name, that name will continue being available as a way to reference that element in this method, even if the element's actual ID or name changes, for as long as the element remains in the tree.

If there are multiple matching items, then a RadioNodeList object containing all those elements is returned.

form . submit()

HTMLFormElement/submit

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Submits the form, bypassing interactive constraint validation and without firing a submit event.

form . requestSubmit( [ submitter ] )

HTMLFormElement/requestSubmit

Firefox75+SafariNoChrome76+
Opera63+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOSNoChrome Android76+WebView Android76+Samsung Internet12.0+Opera Android54+

Requests to submit the form. Unlike submit(), this method includes interactive constraint validation and firing a submit event, either of which can cancel submission.

The submitter argument can be used to point to a specific submit button, whose formaction, formenctype, formmethod, formnovalidate, and formtarget attributes can impact submission. Additionally, the submitter will be included when constructing the entry list for submission; normally, buttons are excluded.

form . reset()

HTMLFormElement/reset

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Resets the form.

form . checkValidity()

Returns true if the form's controls are all valid; otherwise, returns false.

form . reportValidity()

Returns true if the form's controls are all valid; otherwise, returns false and informs the user.

The autocomplete IDL attribute must reflect the content attribute of the same name, limited to only known values.

HTMLFormElement/name

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The name and rel IDL attributes must reflect the content attribute of the same name.

HTMLFormElement/acceptCharset

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The acceptCharset IDL attribute must reflect the accept-charset content attribute.

The relList IDL attribute must reflect the rel content attribute.


The elements IDL attribute must return an HTMLFormControlsCollection rooted at the form element's root, whose filter matches listed elements whose form owner is the form element, with the exception of input elements whose type attribute is in the Image Button state, which must, for historical reasons, be excluded from this particular collection.

The length IDL attribute must return the number of nodes represented by the elements collection.

The supported property indices at any instant are the indices supported by the object returned by the elements attribute at that instant.

To determine the value of an indexed property for a form element, the user agent must return the value returned by the item method on the elements collection, when invoked with the given index as its argument.


Each form element has a mapping of names to elements called the past names map. It is used to persist names of controls even when they change names.

The supported property names consist of the names obtained from the following algorithm, in the order obtained from this algorithm:

  1. Let sourced names be an initially empty ordered list of tuples consisting of a string, an element, a source, where the source is either id, name, or past, and, if the source is past, an age.

  2. For each listed element candidate whose form owner is the form element, with the exception of any input elements whose type attribute is in the Image Button state:

    1. If candidate has an id attribute, add an entry to sourced names with that id attribute's value as the string, candidate as the element, and id as the source.

    2. If candidate has a name attribute, add an entry to sourced names with that name attribute's value as the string, candidate as the element, and name as the source.

  3. For each img element candidate whose form owner is the form element:

    1. If candidate has an id attribute, add an entry to sourced names with that id attribute's value as the string, candidate as the element, and id as the source.

    2. If candidate has a name attribute, add an entry to sourced names with that name attribute's value as the string, candidate as the element, and name as the source.

  4. For each entry past entry in the past names map add an entry to sourced names with the past entry's name as the string, past entry's element as the element, past as the source, and the length of time past entry has been in the past names map as the age.

  5. Sort sourced names by tree order of the element entry of each tuple, sorting entries with the same element by putting entries whose source is id first, then entries whose source is name, and finally entries whose source is past, and sorting entries with the same element and source by their age, oldest first.

  6. Remove any entries in sourced names that have the empty string as their name.

  7. Remove any entries in sourced names that have the same name as an earlier entry in the map.

  8. Return the list of names from sourced names, maintaining their relative order.

To determine the value of a named property name for a form element, the user agent must run the following steps:

  1. Let candidates be a live RadioNodeList object containing all the listed elements, whose form owner is the form element, that have either an id attribute or a name attribute equal to name, with the exception of input elements whose type attribute is in the Image Button state, in tree order.

  2. If candidates is empty, let candidates be a live RadioNodeList object containing all the img elements, whose form owner is the form element, that have either an id attribute or a name attribute equal to name, in tree order.

  3. If candidates is empty, name is the name of one of the entries in the form element's past names map: return the object associated with name in that map.

  4. If candidates contains more than one node, return candidates.

  5. Otherwise, candidates contains exactly one node. Add a mapping from name to the node in candidates in the form element's past names map, replacing the previous entry with the same name, if any.

  6. Return the node in candidates.

If an element listed in a form element's past names map changes form owner, then its entries must be removed from that map.


The submit() method, when invoked, must submit the form element from the form element itself, with the submitted from submit() method flag set.

The requestSubmit(submitter) method, when invoked, must run the following steps:

  1. If submitter is not null, then:

    1. If submitter is not a submit button, then throw a TypeError.

    2. If submitter's form owner is not this form element, then throw a "NotFoundError" DOMException.

  2. Otherwise, set submitter to this form element.

  3. Submit this form element, from submitter.

The reset() method, when invoked, must run the following steps:

  1. If the form element is marked as locked for reset, then return.

  2. Mark the form element as locked for reset.

  3. Reset the form element.

  4. Unmark the form element as locked for reset.

If the checkValidity() method is invoked, the user agent must statically validate the constraints of the form element, and return true if the constraint validation return a positive result, and false if it returned a negative result.

If the reportValidity() method is invoked, the user agent must interactively validate the constraints of the form element, and return true if the constraint validation return a positive result, and false if it returned a negative result.

This example shows two search forms:

<form action="https://www.google.com/search" method="get">
 <label>Google: <input type="search" name="q"></label> <input type="submit" value="Search...">
</form>
<form action="https://www.bing.com/search" method="get">
 <label>Bing: <input type="search" name="q"></label> <input type="submit" value="Search...">
</form>

4.10.4 The label element

Element/label

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLLabelElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Phrasing content.
Interactive content.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content, but with no descendant labelable elements unless it is the element's labeled control, and no descendant label elements.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
for — Associate the label with form control
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLLabelElement : HTMLElement {
  [HTMLConstructor] constructor();

  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute DOMString htmlFor;
  readonly attribute HTMLElement? control;
};

The label element represents a caption in a user interface. The caption can be associated with a specific form control, known as the label element's labeled control, either using the for attribute, or by putting the form control inside the label element itself.

Except where otherwise specified by the following rules, a label element has no labeled control.

The for attribute may be specified to indicate a form control with which the caption is to be associated. If the attribute is specified, the attribute's value must be the ID of a labelable element in the same tree as the label element. If the attribute is specified and there is an element in the tree whose ID is equal to the value of the for attribute, and the first such element in tree order is a labelable element, then that element is the label element's labeled control.

If the for attribute is not specified, but the label element has a labelable element descendant, then the first such descendant in tree order is the label element's labeled control.

The label element's exact default presentation and behavior, in particular what its activation behavior might be, if anything, should match the platform's label behavior. The activation behavior of a label element for events targeted at interactive content descendants of a label element, and any descendants of those interactive content descendants, must be to do nothing.

Form-associated custom elements are labelable elements, so for user agents where the label element's activation behavior impacts the labeled control, both built-in and custom elements will be impacted.

For example, on platforms where clicking a label activates the form control, clicking the label in the following snippet could trigger the user agent to fire a click event at the input element, as if the element itself had been triggered by the user:

<label><input type=checkbox name=lost> Lost</label>

Similarly, assuming my-checkbox was declared as as a form-associated custom element (like in this example), then the code

<label><my-checkbox name=lost></my-checkbox> Lost</label>

would have the same behavior, firing a click event at the my-checkbox element.

On other platforms, the behavior in both cases might be just to focus the control, or to do nothing.

The following example shows three form controls each with a label, two of which have small text showing the right format for users to use.

<p><label>Full name: <input name=fn> <small>Format: First Last</small></label></p>
<p><label>Age: <input name=age type=number min=0></label></p>
<p><label>Post code: <input name=pc> <small>Format: AB12 3CD</small></label></p>
label . control

HTMLLabelElement/control

Support in all current engines.

Firefox4+Safari5.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android12.1+

Returns the form control that is associated with this element.

label . form

HTMLLabelElement/form

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the form owner of the form control that is associated with this element.

Returns null if there isn't one.

HTMLLabelElement/htmlFor

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The htmlFor IDL attribute must reflect the for content attribute.

The control IDL attribute must return the label element's labeled control, if any, or null if there isn't one.

The form IDL attribute must run the following steps:

  1. If the label element has no labeled control, then return null.

  2. If the label element's labeled control is not a form-associated element, then return null.

  3. Return the label element's labeled control's form owner (which can still be null).

The form IDL attribute on the label element is different from the form IDL attribute on listed form-associated elements, and the label element does not have a form content attribute.


control . labels

HTMLButtonElement/labels

Support in all current engines.

Firefox56+Safari5.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android56+Safari iOS5+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android12.1+

HTMLInputElement/labels

Support in all current engines.

Firefox56+Safari5+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android56+Safari iOS4.2+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android12.1+

HTMLMeterElement/labels

Support in all current engines.

Firefox56+Safari6+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android56+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

HTMLOutputElement/labels

Support in all current engines.

Firefox56+Safari5.1+Chrome9+
Opera12.1+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android56+Safari iOS5+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android12.1+

HTMLProgressElement/labels

Support in all current engines.

Firefox56+Safari6+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android56+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

HTMLSelectElement/labels

Support in all current engines.

Firefox56+Safari5.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android56+Safari iOS5+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android12.1+

HTMLTextAreaElement/labels

Support in all current engines.

Firefox56+Safari5.1+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android56+Safari iOS5+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android12.1+

Returns a NodeList of all the label elements that the form control is associated with.

Labelable elements and all input elements have a live NodeList object associated with them that represents the list of label elements, in tree order, whose labeled control is the element in question. The labels IDL attribute of labelable elements that are not form-associated custom elements, and the labels IDL attribute of input elements, on getting, must return that NodeList object, and that same value must always be returned, unless this element is an input element whose type attribute is in the Hidden state, in which case it must instead return null.

ElementInternals/labels

Firefox98+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOSNoChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

Form-associated custom elements don't have a labels IDL attribute. Instead, their ElementInternals object has a labels IDL attribute. On getting, it must throw a "NotSupportedError" DOMException if the target element is not a form-associated custom element. Otherwise, it must return that NodeList object, and that same value must always be returned.

This (non-conforming) example shows what happens to the NodeList and what labels returns when an input element has its type attribute changed.

<!doctype html>
<p><label><input></label></p>
<script>
 const input = document.querySelector('input');
 const labels = input.labels;
 console.assert(labels.length === 1);

 input.type = 'hidden';
 console.assert(labels.length === 0); // the input is no longer the label's labeled control
 console.assert(input.labels === null);

 input.type = 'checkbox';
 console.assert(labels.length === 1); // the input is once again the label's labeled control
 console.assert(input.labels === labels); // same value as returned originally
</script>

4.10.5 The input element

Element/input

Support in all current engines.

Firefox1+Safari1+ChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOS1+Chrome AndroidYesWebView Android1+Samsung InternetYesOpera AndroidYes

Element/input

HTMLInputElement

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
Categories:
Flow content.
Phrasing content.
If the type attribute is not in the Hidden state: Interactive content.
If the type attribute is not in the Hidden state: Listed, labelable, submittable, resettable, and autocapitalize-inheriting form-associated element.
If the type attribute is in the Hidden state: Listed, submittable, resettable, and autocapitalize-inheriting form-associated element.
If the type attribute is not in the Hidden state: Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Nothing.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
accept — Hint for expected file type in file upload controls
alt — Replacement text for use when images are not available
autocomplete — Hint for form autofill feature
checked — Whether the control is checked
dirname — Name of form control to use for sending the element's directionality in form submission
disabled — Whether the form control is disabled
form — Associates the element with a form element
formactionURL to use for form submission
formenctype — Entry list encoding type to use for form submission
formmethod — Variant to use for form submission
formnovalidate — Bypass form control validation for form submission
formtargetBrowsing context for form submission
height — Vertical dimension
list — List of autocomplete options
max — Maximum value
maxlength — Maximum length of value
min — Minimum value
minlength — Minimum length of value
multiple — Whether to allow multiple values
name — Name of the element to use for form submission and in the form.elements API
pattern — Pattern to be matched by the form control's value
placeholder — User-visible label to be placed within the form control
readonly — Whether to allow the value to be edited by the user
required — Whether the control is required for form submission
size — Size of the control
src — Address of the resource
step — Granularity to be matched by the form control's value
type — Type of form control
value — Value of the form control
width — Horizontal dimension
Also, the title attribute has special semantics on this element: Description of pattern (when used with pattern attribute).
Accessibility considerations:
type attribute in the Hidden state: for authors; for implementers.
type attribute in the Text state: for authors; for implementers.
type attribute in the Search state: for authors; for implementers.
type attribute in the Telephone state: for authors; for implementers.
type attribute in the URL state: for authors; for implementers.
type attribute in the Email state: for authors; for implementers.
type attribute in the Password state: for authors; for implementers.
type attribute in the Date state: for authors; for implementers.
type attribute in the Month state: for authors; for implementers.
type attribute in the Week state: for authors; for implementers.
type attribute in the Time state: for authors; for implementers.
type attribute in the Local Date and Time state: for authors; for implementers.
type attribute in the Number state: for authors; for implementers.
type attribute in the Range state: for authors; for implementers.
type attribute in the Color state: for authors; for implementers.
type attribute in the Checkbox state: for authors; for implementers.
type attribute in the Radio Button state: for authors; for implementers.
type attribute in the File Upload state: for authors; for implementers.
type attribute in the Submit Button state: for authors; for implementers.
type attribute in the Image Button state: for authors; for implementers.
type attribute in the Reset Button state: for authors; for implementers.
type attribute in the Button state: for authors; for implementers.
DOM interface:
[Exposed=Window]
interface HTMLInputElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString accept;
  [CEReactions] attribute DOMString alt;
  [CEReactions] attribute DOMString autocomplete;
  [CEReactions] attribute boolean defaultChecked;
  attribute boolean checked;
  [CEReactions] attribute DOMString dirName;
  [CEReactions] attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  attribute FileList? files;
  [CEReactions] attribute USVString formAction;
  [CEReactions] attribute DOMString formEnctype;
  [CEReactions] attribute DOMString formMethod;
  [CEReactions] attribute boolean formNoValidate;
  [CEReactions] attribute DOMString formTarget;
  [CEReactions] attribute unsigned long height;
  attribute boolean indeterminate;
  readonly attribute HTMLElement? list;
  [CEReactions] attribute DOMString max;
  [CEReactions] attribute long maxLength;
  [CEReactions] attribute DOMString min;
  [CEReactions] attribute long minLength;
  [CEReactions] attribute boolean multiple;
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString pattern;
  [CEReactions] attribute DOMString placeholder;
  [CEReactions] attribute boolean readOnly;
  [CEReactions] attribute boolean required;
  [CEReactions] attribute unsigned long size;
  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString step;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute DOMString defaultValue;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString value;
  attribute object? valueAsDate;
  attribute unrestricted double valueAsNumber;
  [CEReactions] attribute unsigned long width;

  undefined stepUp(optional long n = 1);
  undefined stepDown(optional long n = 1);

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity(DOMString error);

  readonly attribute NodeList? labels;

  undefined select();
  attribute unsigned long? selectionStart;
  attribute unsigned long? selectionEnd;
  attribute DOMString? selectionDirection;
  undefined setRangeText(DOMString replacement);
  undefined setRangeText(DOMString replacement, unsigned long start, unsigned long end, optional SelectionMode selectionMode = "preserve");
  undefined setSelectionRange(unsigned long start, unsigned long end, optional DOMString direction);

  // also has obsolete members
};

The input element represents a typed data field, usually with a form control to allow the user to edit the data.

The type attribute controls the data type (and associated control) of the element. It is an enumerated attribute. The following table lists the keywords and states for the attribute — the keywords in the left column map to the states in the cell in the second column on the same row as the keyword.

Keyword State Data type Control type
hidden Hidden An arbitrary string n/a
text Text Text with no line breaks A text control
search Search Text with no line breaks Search control
tel Telephone Text with no line breaks A text control
url URL An absolute URL A text control
email Email An email address or list of email addresses A text control
password Password Text with no line breaks (sensitive information) A text control that obscures data entry
date Date A date (year, month, day) with no time zone A date control
month Month A date consisting of a year and a month with no time zone A month control
week Week A date consisting of a week-year number and a week number with no time zone A week control
time Time A time (hour, minute, seconds, fractional seconds) with no time zone A time control
datetime-local Local Date and Time A date and time (year, month, day, hour, minute, second, fraction of a second) with no time zone A date and time control
number Number A numerical value A text control or spinner control
range Range A numerical value, with the extra semantic that the exact value is not important A slider control or similar
color Color An sRGB color with 8-bit red, green, and blue components A color picker
checkbox Checkbox A set of zero or more values from a predefined list A checkbox
radio Radio Button An enumerated value A radio button
file File Upload Zero or more files each with a MIME type and optionally a file name A label and a button
submit Submit Button An enumerated value, with the extra semantic that it must be the last value selected and initiates form submission A button
image Image Button A coordinate, relative to a particular image's size, with the extra semantic that it must be the last value selected and initiates form submission Either a clickable image, or a button
reset Reset Button n/a A button
button Button n/a A button

The missing value default and the invalid value default are the Text state.

Which of the accept, alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, and width content attributes, the checked, files, valueAsDate, valueAsNumber, and list IDL attributes, the select() method, the selectionStart, selectionEnd, and selectionDirection, IDL attributes, the setRangeText() and setSelectionRange() methods, the stepUp() and stepDown() methods, and the input and change events apply to an input element depends on the state of its type attribute. The subsections that define each type also clearly define in normative "bookkeeping" sections which of these feature apply, and which do not apply, to each type. The behavior of these features depends on whether they apply or not, as defined in their various sections (q.v. for content attributes, for APIs, for events).

The following table is non-normative and summarizes which of those content attributes, IDL attributes, methods, and events apply to each state:

Hidden Text, Search URL, Telephone Email Password Date, Month, Week, Time Local Date and Time Number Range Color Checkbox, Radio Button File Upload Submit Button Image Button Reset Button, Button
Content attributes
accept · · · · · · · · · · · Yes · · ·
alt · · · · · · · · · · · · · Yes ·
autocomplete Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes · · · · ·
checked · · · · · · · · · · Yes · · · ·
dirname · Yes · · · · · · · · · · · · ·
formaction · · · · · · · · · · · · Yes Yes ·
formenctype · · · · · · · · · · · · Yes Yes ·
formmethod · · · · · · · · · · · · Yes Yes ·
formnovalidate · · · · · · · · · · · · Yes Yes ·
formtarget · · · · · · · · · · · · Yes Yes ·
height · · · · · · · · · · · · · Yes ·
list · Yes Yes Yes · Yes Yes Yes Yes Yes · · · · ·
max · · · · · Yes Yes Yes Yes · · · · · ·
maxlength · Yes Yes Yes Yes · · · · · · · · · ·
min · · · · · Yes Yes Yes Yes · · · · · ·
minlength · Yes Yes Yes Yes · · · · · · · · · ·
multiple · · · Yes · · · · · · · Yes · · ·
pattern · Yes Yes Yes Yes · · · · · · · · · ·
placeholder · Yes Yes Yes Yes · · Yes · · · · · · ·
readonly · Yes Yes Yes Yes Yes Yes Yes · · · · · · ·
required · Yes Yes Yes Yes Yes Yes Yes · · Yes Yes · · ·
size · Yes Yes Yes Yes · · · · · · · · · ·
src · · · · · · · · · · · · · Yes ·
step · · · · · Yes Yes Yes Yes · · · · · ·
width · · · · · · · · · · · · · Yes ·
IDL attributes and methods
checked · · · · · · · · · · Yes · · · ·
files · · · · · · · · · · · Yes · · ·
value default value value value value value value value value value default/on filename default default default
valueAsDate · · · · · Yes · · · · · · · · ·
valueAsNumber · · · · · Yes Yes Yes Yes · · · · · ·
list · Yes Yes Yes · Yes Yes Yes Yes Yes · · · · ·
select() · Yes Yes Yes† Yes Yes† Yes† Yes† · Yes† · Yes† · · ·
selectionStart · Yes Yes · Yes · · · · · · · · · ·
selectionEnd · Yes Yes · Yes · · · · · · · · · ·
selectionDirection · Yes Yes · Yes · · · · · · · · · ·
setRangeText() · Yes Yes · Yes · · · · · · · · · ·
setSelectionRange() · Yes Yes · Yes · · · · · · · · · ·
stepDown() · · · · · Yes Yes Yes Yes · · · · · ·
stepUp() · · · · · Yes Yes Yes Yes · · · · · ·
Events
input event · Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes · · ·
change event · Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes Yes · · ·

† If the control has no selectable text, the select() method results in a no-op, with no "InvalidStateError" DOMException.

Some states of the type attribute define a value sanitization algorithm.

Each input element has a value, which is exposed by the value IDL attribute. Some states define an algorithm to convert a string to a number, an algorithm to convert a number to a string, an algorithm to convert a string to a Date object, and an algorithm to convert a Date object to a string, which are used by max, min, step, valueAsDate, valueAsNumber, and stepUp().

An input element's dirty value flag must be set to true whenever the user interacts with the control in a way that changes the value. (It is also set to true when the value is programmatically changed, as described in the definition of the value IDL attribute.)

The value content attribute gives the default value of the input element. When the value content attribute is added, set, or removed, if the control's dirty value flag is false, the user agent must set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise, and then run the current value sanitization algorithm, if one is defined.

Each input element has a checkedness, which is exposed by the checked IDL attribute.

Each input element has a boolean dirty checkedness flag. When it is true, the element is said to have a dirty checkedness. The dirty checkedness flag must be initially set to false when the element is created, and must be set to true whenever the user interacts with the control in a way that changes the checkedness.

The checked content attribute is a boolean attribute that gives the default checkedness of the input element. When the checked content attribute is added, if the control does not have dirty checkedness, the user agent must set the checkedness of the element to true; when the checked content attribute is removed, if the control does not have dirty checkedness, the user agent must set the checkedness of the element to false.

The reset algorithm for input elements is to set the dirty value flag and dirty checkedness flag back to false, set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise, set the checkedness of the element to true if the element has a checked content attribute and false if it does not, empty the list of selected files, and then invoke the value sanitization algorithm, if the type attribute's current state defines one.

Each input element can be mutable. Except where otherwise specified, an input element is always mutable. Similarly, except where otherwise specified, the user agent should not allow the user to modify the element's value or checkedness.

When an input element is disabled, it is not mutable.

The readonly attribute can also in some cases (e.g. for the Date state, but not the Checkbox state) stop an input element from being mutable.

The cloning steps for input elements must propagate the value, dirty value flag, checkedness, and dirty checkedness flag from the node being cloned to the copy.

The activation behavior for input elements are these steps:

  1. If this element is not mutable and is not in the Checkbox state and is not in the Radio state, then return.

  2. Run this element's input activation behavior, if any, and do nothing otherwise.

The legacy-pre-activation behavior for input elements are these steps:

  1. If this element's type attribute is in the Checkbox state, then set this element's checkedness to its opposite value (i.e. true if it is false, false if it is true) and set this element's indeterminate IDL attribute to false.

  2. If this element's type attribute is in the Radio Button state, then get a reference to the element in this element's radio button group that has its checkedness set to true, if any, and then set this element's checkedness to true.

The legacy-canceled-activation behavior for input elements are these steps:

  1. If the element's type attribute is in the Checkbox state, then set the element's checkedness and the element's indeterminate IDL attribute back to the values they had before the legacy-pre-activation behavior was run.

  2. If this element's type attribute is in the Radio Button state, then if the element to which a reference was obtained in the legacy-pre-activation behavior, if any, is still in what is now this element's radio button group, if it still has one, and if so, setting that element's checkedness to true; or else, if there was no such element, or that element is no longer in this element's radio button group, or if this element no longer has a radio button group, setting this element's checkedness to false.


When an input element is first created, the element's rendering and behavior must be set to the rendering and behavior defined for the type attribute's state, and the value sanitization algorithm, if one is defined for the type attribute's state, must be invoked.

When an input element's type attribute changes state, the user agent must run the following steps:

  1. If the previous state of the element's type attribute put the value IDL attribute in the value mode, and the element's value is not the empty string, and the new state of the element's type attribute puts the value IDL attribute in either the default mode or the default/on mode, then set the element's value content attribute to the element's value.

  2. Otherwise, if the previous state of the element's type attribute put the value IDL attribute in any mode other than the value mode, and the new state of the element's type attribute puts the value IDL attribute in the value mode, then set the value of the element to the value of the value content attribute, if there is one, or the empty string otherwise, and then set the control's dirty value flag to false.

  3. Otherwise, if the previous state of the element's type attribute put the value IDL attribute in any mode other than the filename mode, and the new state of the element's type attribute puts the value IDL attribute in the filename mode, then set the value of the element to the empty string.

  4. Update the element's rendering and behavior to the new state's.

  5. Signal a type change for the element. (The Radio Button state uses this, in particular.)

  6. Invoke the value sanitization algorithm, if one is defined for the type attribute's new state.

  7. Let previouslySelectable be true if setRangeText() previously applied to the element, and false otherwise.

  8. Let nowSelectable be true if setRangeText() now applies to the element, and false otherwise.

  9. If previouslySelectable is false and nowSelectable is true, set the element's text entry cursor position to the beginning of the text control, and set its selection direction to "none".


The name attribute represents the element's name. The dirname attribute controls how the element's directionality is submitted. The disabled attribute is used to make the control non-interactive and to prevent its value from being submitted. The form attribute is used to explicitly associate the input element with its form owner. The autocomplete attribute controls how the user agent provides autofill behavior.

HTMLInputElement#indeterminate

Support in all current engines.

Firefox3.6+Safari3+Chrome1+
Opera≤12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android≤12.1+
caniuse.com table

The indeterminate IDL attribute must initially be set to false. On getting, it must return the last value it was set to. On setting, it must be set to the new value. It has no effect except for changing the appearance of checkbox controls.

HTMLInputElement/multiple

Support in all current engines.

Firefox3.6+Safari4+Chrome2+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The accept, alt, max, min, multiple, pattern, placeholder, required, size, src, and step IDL attributes must reflect the respective content attributes of the same name. The dirName IDL attribute must reflect the dirname content attribute. The readOnly IDL attribute must reflect the readonly content attribute. The defaultChecked IDL attribute must reflect the checked content attribute. The defaultValue IDL attribute must reflect the value content attribute.

The type IDL attribute must reflect the respective content attribute of the same name, limited to only known values. The maxLength IDL attribute must reflect the maxlength content attribute, limited to only non-negative numbers. The minLength IDL attribute must reflect the minlength content attribute, limited to only non-negative numbers.

The IDL attributes width and height must return the rendered width and height of the image, in CSS pixels, if an image is being rendered, and is being rendered to a visual medium; or else the intrinsic width and height of the image, in CSS pixels, if an image is available but not being rendered to a visual medium; or else 0, if no image is available. When the input element's type attribute is not in the Image Button state, then no image is available. [CSS]

On setting, they must act as if they reflected the respective content attributes of the same name.

The willValidate, validity, and validationMessage IDL attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The labels IDL attribute provides a list of the element's labels. The select(), selectionStart, selectionEnd, selectionDirection, setRangeText(), and setSelectionRange() methods and IDL attributes expose the element's text selection. The disabled, form, and name IDL attributes are part of the element's forms API.

4.10.5.1 type 属性的状态
4.10.5.1.1 Hidden state (type=hidden)

Element/input/hidden

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera2+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

When an input element's type attribute is in the Hidden state, the rules in this section apply.

The input element represents a value that is not intended to be examined or manipulated by the user.

Constraint validation: If an input element's type attribute is in the Hidden state, it is barred from constraint validation.

If the name attribute is present and has a value that is an ASCII case-insensitive match for "_charset_", then the element's value attribute must be omitted.

The autocomplete content attribute applies to this element.

The value IDL attribute applies to this element and is in mode default.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

The input and change events do not apply.

4.10.5.1.2 Text (type=text) state and Search state (type=search)

Element/input/search

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Element/input/text

Support in all current engines.

Firefox1+Safari1+Chrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

When an input element's type attribute is in the Text state or the Search state, the rules in this section apply.

The input element represents a one line plain text edit control for the element's value.

The difference between the Text state and the Search state is primarily stylistic: on platforms where search controls are distinguished from regular text controls, the Search state might result in an appearance consistent with the platform's search controls rather than appearing like a regular text control.

If the element is mutable, its value should be editable by the user. User agents must not allow users to insert U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into the element's value.

If the element is mutable, the user agent should allow the user to change the writing direction of the element, setting it either to a left-to-right writing direction or a right-to-left writing direction. If the user does so, the user agent must then run the following steps:

  1. Set the element's dir attribute to "ltr" if the user selected a left-to-right writing direction, and "rtl" if the user selected a right-to-left writing direction.

  2. Queue an element task on the user interaction task source given the element to fire an event named input at the element, with the bubbles and composed attributes initialized to true.

The value attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.

The value sanitization algorithm is as follows: Strip newlines from the value.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, dirname, list, maxlength, minlength, pattern, placeholder, readonly, required, and size content attributes; list, selectionStart, selectionEnd, selectionDirection, and value IDL attributes; select(), setRangeText(), and setSelectionRange() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, formaction, formenctype, formmethod, formnovalidate, formtarget, height, max, min, multiple, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, valueAsDate, and valueAsNumber IDL attributes; stepDown() and stepUp() methods.

4.10.5.1.3 Telephone state (type=tel)

Element/input/tel

Support in all current engines.

FirefoxYesSafari4+Chrome3+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox AndroidYesSafari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

When an input element's type attribute is in the Telephone state, the rules in this section apply.

The input element represents a control for editing a telephone number given in the element's value.

If the element is mutable, its value should be editable by the user. User agents may change the spacing and, with care, the punctuation of values that the user enters. User agents must not allow users to insert U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into the element's value.

The value attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.

The value sanitization algorithm is as follows: Strip newlines from the value.

Unlike the URL and Email types, the Telephone type does not enforce a particular syntax. This is intentional; in practice, telephone number fields tend to be free-form fields, because there are a wide variety of valid phone numbers. Systems that need to enforce a particular format are encouraged to use the pattern attribute or the setCustomValidity() method to hook into the client-side validation mechanism.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, required, and size content attributes; list, selectionStart, selectionEnd, selectionDirection, and value IDL attributes; select(), setRangeText(), and setSelectionRange() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, max, min, multiple, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, valueAsDate, and valueAsNumber IDL attributes; stepDown() and stepUp() methods.

4.10.5.1.4 URL state (type=url)

Element/input/url

Support in all current engines.

FirefoxYesSafariYesChrome1+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

When an input element's type attribute is in the URL state, the rules in this section apply.

The input element represents a control for editing a single absolute URL given in the element's value.

If the element is mutable, the user agent should allow the user to change the URL represented by its value. User agents may allow the user to set the value to a string that is not a valid absolute URL, but may also or instead automatically escape characters entered by the user so that the value is always a valid absolute URL (even if that isn't the actual value seen and edited by the user in the interface). User agents should allow the user to set the value to the empty string. User agents must not allow users to insert U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into the value.

The value attribute, if specified and not empty, must have a value that is a valid URL potentially surrounded by spaces that is also an absolute URL.

The value sanitization algorithm is as follows: Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.

Constraint validation: While the value of the element is neither the empty string nor a valid absolute URL, the element is suffering from a type mismatch.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, maxlength, minlength, pattern, placeholder, readonly, required, and size content attributes; list, selectionStart, selectionEnd, selectionDirection, and value IDL attributes; select(), setRangeText(), and setSelectionRange() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, max, min, multiple, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, valueAsDate, and valueAsNumber IDL attributes; stepDown() and stepUp() methods.

If a document contained the following markup:

<input type="url" name="location" list="urls">
<datalist id="urls">
 <option label="MIME: Format of Internet Message Bodies" value="https://tools.ietf.org/html/rfc2045">
 <option label="HTML" value="https://html.spec.whatwg.org/">
 <option label="DOM" value="https://dom.spec.whatwg.org/">
 <option label="Fullscreen" value="https://fullscreen.spec.whatwg.org/">
 <option label="Media Session" value="https://mediasession.spec.whatwg.org/">
 <option label="The Single UNIX Specification, Version 3" value="http://www.unix.org/version3/">
</datalist>

...and the user had typed "spec.w", and the user agent had also found that the user had visited https://url.spec.whatwg.org/#url-parsing and https://streams.spec.whatwg.org/ in the recent past, then the rendering might look like this:

A text box with an icon on the left followed by the text "spec.w" and a cursor, with a drop down button on the right hand side; with, below, a drop down box containing a list of six URLs on the left, with the first four having grayed out labels on the right; and a scrollbar to the right of the drop down box, indicating further values are available.

The first four URLs in this sample consist of the four URLs in the author-specified list that match the text the user has entered, sorted in some implementation-defined manner (maybe by how frequently the user refers to those URLs). Note how the UA is using the knowledge that the values are URLs to allow the user to omit the scheme part and perform intelligent matching on the domain name.

The last two URLs (and probably many more, given the scrollbar's indications of more values being available) are the matches from the user agent's session history data. This data is not made available to the page DOM. In this particular case, the UA has no titles to provide for those values.

4.10.5.1.5 Email state (type=email)

Element/input/email

Support in all current engines.

FirefoxYesSafariYesChrome5+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS3+Chrome Android?WebView Android?Samsung Internet?Opera AndroidYes

When an input element's type attribute is in the Email state, the rules in this section apply.

How the Email state operates depends on whether the multiple attribute is specified or not.

When the multiple attribute is not specified on the element

The input element represents a control for editing an email address given in the element's value.

If the element is mutable, the user agent should allow the user to change the email address represented by its value. User agents may allow the user to set the value to a string that is not a valid email address. The user agent should act in a manner consistent with expecting the user to provide a single email address. User agents should allow the user to set the value to the empty string. User agents must not allow users to insert U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into the value. User agents may transform the value for display and editing; in particular, user agents should convert punycode in the domain labels of the value to IDN in the display and vice versa.

Constraint validation: While the user interface is representing input that the user agent cannot convert to punycode, the control is suffering from bad input.

The value attribute, if specified and not empty, must have a value that is a single valid email address.

The value sanitization algorithm is as follows: Strip newlines from the value, then strip leading and trailing ASCII whitespace from the value.

Constraint validation: While the value of the element is neither the empty string nor a single valid email address, the element is suffering from a type mismatch.

When the multiple attribute is specified on the element

The input element represents a control for adding, removing, and editing the email addresses given in the element's values.

If the element is mutable, the user agent should allow the user to add, remove, and edit the email addresses represented by its values. User agents may allow the user to set any individual value in the list of values to a string that is not a valid email address, but must not allow users to set any individual value to a string containing U+002C COMMA (,), U+000A LINE FEED (LF), or U+000D CARRIAGE RETURN (CR) characters. User agents should allow the user to remove all the addresses in the element's values. User agents may transform the values for display and editing; in particular, user agents should convert punycode in the domain labels of the value to IDN in the display and vice versa.

Constraint validation: While the user interface describes a situation where an individual value contains a U+002C COMMA (,) or is representing input that the user agent cannot convert to punycode, the control is suffering from bad input.

Whenever the user changes the element's values, the user agent must run the following steps:

  1. Let latest values be a copy of the element's values.

  2. Strip leading and trailing ASCII whitespace from each value in latest values.

  3. Let the element's value be the result of concatenating all the values in latest values, separating each value from the next by a single U+002C COMMA character (,), maintaining the list's order.

The value attribute, if specified, must have a value that is a valid email address list.

The value sanitization algorithm is as follows:

  1. Split on commas the element's value, strip leading and trailing ASCII whitespace from each resulting token, if any, and let the element's values be the (possibly empty) resulting list of (possibly empty) tokens, maintaining the original order.

  2. Let the element's value be the result of concatenating the element's values, separating each value from the next by a single U+002C COMMA character (,), maintaining the list's order.

Constraint validation: While the value of the element is not a valid email address list, the element is suffering from a type mismatch.

When the multiple attribute is set or removed, the user agent must run the value sanitization algorithm.

A valid email address is a string that matches the email production of the following ABNF, the character set for which is Unicode. This ABNF implements the extensions described in RFC 1123. [ABNF] [RFC5322] [RFC1034] [RFC1123]

email         = 1*( atext / "." ) "@" label *( "." label )
label         = let-dig [ [ ldh-str ] let-dig ]  ; limited to a length of 63 characters by RFC 1034 section 3.5
atext         = < as defined in RFC 5322 section 3.2.3 >
let-dig       = < as defined in RFC 1034 section 3.5 >
ldh-str       = < as defined in RFC 1034 section 3.5 >

This requirement is a willful violation of RFC 5322, which defines a syntax for email addresses that is simultaneously too strict (before the "@" character), too vague (after the "@" character), and too lax (allowing comments, whitespace characters, and quoted strings in manners unfamiliar to most users) to be of practical use here.

The following JavaScript- and Perl-compatible regular expression is an implementation of the above definition.

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

A valid email address list is a set of comma-separated tokens, where each token is itself a valid email address. To obtain the list of tokens from a valid email address list, an implementation must split the string on commas.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, maxlength, minlength, multiple, pattern, placeholder, readonly, required, and size content attributes; list and value IDL attributes; select() method.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, max, min, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; setRangeText(), setSelectionRange(), stepDown() and stepUp() methods.

4.10.5.1.6 Password state (type=password)

Element/input/password

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera2+Edge79+
Edge (Legacy)12+Internet Explorer2+
Firefox Android4+Safari iOSYesChrome AndroidYesWebView Android?Samsung InternetYesOpera AndroidYes

When an input element's type attribute is in the Password state, the rules in this section apply.

The input element represents a one line plain text edit control for the element's value. The user agent should obscure the value so that people other than the user cannot see it.

If the element is mutable, its value should be editable by the user. User agents must not allow users to insert U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters into the value.

The value attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.

The value sanitization algorithm is as follows: Strip newlines from the value.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, maxlength, minlength, pattern, placeholder, readonly, required, and size content attributes; selectionStart, selectionEnd, selectionDirection, and value IDL attributes; select(), setRangeText(), and setSelectionRange() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, min, multiple, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, list, valueAsDate, and valueAsNumber IDL attributes; stepDown() and stepUp() methods.

4.10.5.1.7 Date state (type=date)

Element/input/date

Support in all current engines.

Firefox57+Safari14.1+Chrome20+
Opera11+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android57+Safari iOS5+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android11+

When an input element's type attribute is in the Date state, the rules in this section apply.

The input element represents a control for setting the element's value to a string representing a specific date.

If the element is mutable, the user agent should allow the user to change the date represented by its value, as obtained by parsing a date from it. User agents must not allow the user to set the value to a non-empty string that is not a valid date string. If the user agent provides a user interface for selecting a date, then the value must be set to a valid date string representing the user's selection. User agents should allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid date string, the control is suffering from bad input.

See the introduction section for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.

The value attribute, if specified and not empty, must have a value that is a valid date string.

The value sanitization algorithm is as follows: If the value of the element is not a valid date string, then set it to the empty string instead.

The min attribute, if specified, must have a value that is a valid date string. The max attribute, if specified, must have a value that is a valid date string.

The step attribute is expressed in days. The step scale factor is 86,400,000 (which converts the days to milliseconds, as used in the other algorithms). The default step is 1 day.

When the element is suffering from a step mismatch, the user agent may round the element's value to the nearest date for which the element would not suffer from a step mismatch.

The algorithm to convert a string to a number, given a string input, is as follows: If parsing a date from input results in an error, then return an error; otherwise, return the number of milliseconds elapsed from midnight UTC on the morning of 1970-01-01 (the time represented by the value "1970-01-01T00:00:00.0Z") to midnight UTC on the morning of the parsed date, ignoring leap seconds.

The algorithm to convert a number to a string, given a number input, is as follows: Return a valid date string that represents the date that, in UTC, is current input milliseconds after midnight UTC on the morning of 1970-01-01 (the time represented by the value "1970-01-01T00:00:00.0Z").

The algorithm to convert a string to a Date object, given a string input, is as follows: If parsing a date from input results in an error, then return an error; otherwise, return a new Date object representing midnight UTC on the morning of the parsed date.

The algorithm to convert a Date object to a string, given a Date object input, is as follows: Return a valid date string that represents the date current at the time represented by input in the UTC time zone.

The Date state (and other date- and time-related states described in subsequent sections) is not intended for the entry of values for which a precise date and time relative to the contemporary calendar cannot be established. For example, it would be inappropriate for the entry of times like "one millisecond after the big bang", "the early part of the Jurassic period", or "a winter around 250 BCE".

For the input of dates before the introduction of the Gregorian calendar, authors are encouraged to not use the Date state (and the other date- and time-related states described in subsequent sections), as user agents are not required to support converting dates and times from earlier periods to the Gregorian calendar, and asking users to do so manually puts an undue burden on users. (This is complicated by the manner in which the Gregorian calendar was phased in, which occurred at different times in different countries, ranging from partway through the 16th century all the way to early in the 20th.) Instead, authors are encouraged to provide fine-grained input controls using the select element and input elements with the Number state.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, readonly, required, and step content attributes; list, value, valueAsDate, and valueAsNumber IDL attributes; select(), stepDown(), and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, selectionStart, selectionEnd, and selectionDirection IDL attributes; setRangeText(), and setSelectionRange() methods.

4.10.5.1.8 Month state (type=month)

Element/input/month

Support in all current engines.

FirefoxNoSafariNoChrome20+
Opera11+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android18+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

When an input element's type attribute is in the Month state, the rules in this section apply.

The input element represents a control for setting the element's value to a string representing a specific month.

If the element is mutable, the user agent should allow the user to change the month represented by its value, as obtained by parsing a month from it. User agents must not allow the user to set the value to a non-empty string that is not a valid month string. If the user agent provides a user interface for selecting a month, then the value must be set to a valid month string representing the user's selection. User agents should allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid month string, the control is suffering from bad input.

See the introduction section for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.

The value attribute, if specified and not empty, must have a value that is a valid month string.

The value sanitization algorithm is as follows: If the value of the element is not a valid month string, then set it to the empty string instead.

The min attribute, if specified, must have a value that is a valid month string. The max attribute, if specified, must have a value that is a valid month string.

The step attribute is expressed in months. The step scale factor is 1 (there is no conversion needed as the algorithms use months). The default step is 1 month.

When the element is suffering from a step mismatch, the user agent may round the element's value to the nearest month for which the element would not suffer from a step mismatch.

The algorithm to convert a string to a number, given a string input, is as follows: If parsing a month from input results in an error, then return an error; otherwise, return the number of months between January 1970 and the parsed month.

The algorithm to convert a number to a string, given a number input, is as follows: Return a valid month string that represents the month that has input months between it and January 1970.

The algorithm to convert a string to a Date object, given a string input, is as follows: If parsing a month from input results in an error, then return an error; otherwise, return a new Date object representing midnight UTC on the morning of the first day of the parsed month.

The algorithm to convert a Date object to a string, given a Date object input, is as follows: Return a valid month string that represents the month current at the time represented by input in the UTC time zone.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, readonly, required, and step content attributes; list, value, valueAsDate, and valueAsNumber IDL attributes; select(), stepDown(), and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, and selectionDirection IDL attributes; setRangeText(), and setSelectionRange() methods.

4.10.5.1.9 Week state (type=week)

Element/input/week

FirefoxNoSafariNoChrome20+
Opera11+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android18+Safari iOSNoChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

When an input element's type attribute is in the Week state, the rules in this section apply.

The input element represents a control for setting the element's value to a string representing a specific week.

If the element is mutable, the user agent should allow the user to change the week represented by its value, as obtained by parsing a week from it. User agents must not allow the user to set the value to a non-empty string that is not a valid week string. If the user agent provides a user interface for selecting a week, then the value must be set to a valid week string representing the user's selection. User agents should allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid week string, the control is suffering from bad input.

See the introduction section for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.

The value attribute, if specified and not empty, must have a value that is a valid week string.

The value sanitization algorithm is as follows: If the value of the element is not a valid week string, then set it to the empty string instead.

The min attribute, if specified, must have a value that is a valid week string. The max attribute, if specified, must have a value that is a valid week string.

The step attribute is expressed in weeks. The step scale factor is 604,800,000 (which converts the weeks to milliseconds, as used in the other algorithms). The default step is 1 week. The default step base is −259,200,000 (the start of week 1970-W01).

When the element is suffering from a step mismatch, the user agent may round the element's value to the nearest week for which the element would not suffer from a step mismatch.

The algorithm to convert a string to a number, given a string input, is as follows: If parsing a week string from input results in an error, then return an error; otherwise, return the number of milliseconds elapsed from midnight UTC on the morning of 1970-01-01 (the time represented by the value "1970-01-01T00:00:00.0Z") to midnight UTC on the morning of the Monday of the parsed week, ignoring leap seconds.

The algorithm to convert a number to a string, given a number input, is as follows: Return a valid week string that represents the week that, in UTC, is current input milliseconds after midnight UTC on the morning of 1970-01-01 (the time represented by the value "1970-01-01T00:00:00.0Z").

The algorithm to convert a string to a Date object, given a string input, is as follows: If parsing a week from input results in an error, then return an error; otherwise, return a new Date object representing midnight UTC on the morning of the Monday of the parsed week.

The algorithm to convert a Date object to a string, given a Date object input, is as follows: Return a valid week string that represents the week current at the time represented by input in the UTC time zone.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, readonly, required, and step content attributes; list, value, valueAsDate, and valueAsNumber IDL attributes; select(), stepDown(), and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, and selectionDirection IDL attributes; setRangeText(), and setSelectionRange() methods.

4.10.5.1.10 Time state (type=time)

Element/input/time

Support in all current engines.

Firefox57+Safari14.1+Chrome20+
Opera10+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android57+Safari iOSYesChrome Android25+WebView AndroidYesSamsung Internet1.5+Opera AndroidYes

When an input element's type attribute is in the Time state, the rules in this section apply.

The input element represents a control for setting the element's value to a string representing a specific time.

If the element is mutable, the user agent should allow the user to change the time represented by its value, as obtained by parsing a time from it. User agents must not allow the user to set the value to a non-empty string that is not a valid time string. If the user agent provides a user interface for selecting a time, then the value must be set to a valid time string representing the user's selection. User agents should allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid time string, the control is suffering from bad input.

See the introduction section for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.

The value attribute, if specified and not empty, must have a value that is a valid time string.

The value sanitization algorithm is as follows: If the value of the element is not a valid time string, then set it to the empty string instead.

The form control has a periodic domain.

The min attribute, if specified, must have a value that is a valid time string. The max attribute, if specified, must have a value that is a valid time string.

The step attribute is expressed in seconds. The step scale factor is 1000 (which converts the seconds to milliseconds, as used in the other algorithms). The default step is 60 seconds.

When the element is suffering from a step mismatch, the user agent may round the element's value to the nearest time for which the element would not suffer from a step mismatch.

The algorithm to convert a string to a number, given a string input, is as follows: If parsing a time from input results in an error, then return an error; otherwise, return the number of milliseconds elapsed from midnight to the parsed time on a day with no time changes.

The algorithm to convert a number to a string, given a number input, is as follows: Return a valid time string that represents the time that is input milliseconds after midnight on a day with no time changes.

The algorithm to convert a string to a Date object, given a string input, is as follows: If parsing a time from input results in an error, then return an error; otherwise, return a new Date object representing the parsed time in UTC on 1970-01-01.

The algorithm to convert a Date object to a string, given a Date object input, is as follows: Return a valid time string that represents the UTC time component that is represented by input.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, readonly, required, and step content attributes; list, value, valueAsDate, and valueAsNumber IDL attributes; select(), stepDown(), and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, and selectionDirection IDL attributes; setRangeText(), and setSelectionRange() methods.

4.10.5.1.11 Local Date and Time state (type=datetime-local)

Element/input/datetime-local

Support in all current engines.

Firefox93+Safari14.1+Chrome20+
Opera11+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android11+

When an input element's type attribute is in the Local Date and Time state, the rules in this section apply.

The input element represents a control for setting the element's value to a string representing a local date and time, with no time-zone offset information.

If the element is mutable, the user agent should allow the user to change the date and time represented by its value, as obtained by parsing a date and time from it. User agents must not allow the user to set the value to a non-empty string that is not a valid normalized local date and time string. If the user agent provides a user interface for selecting a local date and time, then the value must be set to a valid normalized local date and time string representing the user's selection. User agents should allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid normalized local date and time string, the control is suffering from bad input.

See the introduction section for a discussion of the difference between the input format and submission format for date, time, and number form controls, and the implementation notes regarding localization of form controls.

The value attribute, if specified and not empty, must have a value that is a valid local date and time string.

The value sanitization algorithm is as follows: If the value of the element is a valid local date and time string, then set it to a valid normalized local date and time string representing the same date and time; otherwise, set it to the empty string instead.

The min attribute, if specified, must have a value that is a valid local date and time string. The max attribute, if specified, must have a value that is a valid local date and time string.

The step attribute is expressed in seconds. The step scale factor is 1000 (which converts the seconds to milliseconds, as used in the other algorithms). The default step is 60 seconds.

When the element is suffering from a step mismatch, the user agent may round the element's value to the nearest local date and time for which the element would not suffer from a step mismatch.

The algorithm to convert a string to a number, given a string input, is as follows: If parsing a date and time from input results in an error, then return an error; otherwise, return the number of milliseconds elapsed from midnight on the morning of 1970-01-01 (the time represented by the value "1970-01-01T00:00:00.0") to the parsed local date and time, ignoring leap seconds.

The algorithm to convert a number to a string, given a number input, is as follows: Return a valid normalized local date and time string that represents the date and time that is input milliseconds after midnight on the morning of 1970-01-01 (the time represented by the value "1970-01-01T00:00:00.0").

See the note on historical dates in the Date state section.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, readonly, required, and step content attributes; list, value, and valueAsNumber IDL attributes; select(), stepDown(), and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, selectionDirection, and valueAsDate IDL attributes; setRangeText(), and setSelectionRange() methods.

The following example shows part of a flight booking application. The application uses an input element with its type attribute set to datetime-local, and it then interprets the given date and time in the time zone of the selected airport.

<fieldset>
 <legend>Destination</legend>
 <p><label>Airport: <input type=text name=to list=airports></label></p>
 <p><label>Departure time: <input type=datetime-local name=totime step=3600></label></p>
</fieldset>
<datalist id=airports>
 <option value=ATL label="Atlanta">
 <option value=MEM label="Memphis">
 <option value=LHR label="London Heathrow">
 <option value=LAX label="Los Angeles">
 <option value=FRA label="Frankfurt">
</datalist>
4.10.5.1.12 Number state (type=number)

Element/input/number

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet Explorer10+
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

When an input element's type attribute is in the Number state, the rules in this section apply.

The input element represents a control for setting the element's value to a string representing a number.

If the element is mutable, the user agent should allow the user to change the number represented by its value, as obtained from applying the rules for parsing floating-point number values to it. User agents must not allow the user to set the value to a non-empty string that is not a valid floating-point number. If the user agent provides a user interface for selecting a number, then the value must be set to the best representation of the number representing the user's selection as a floating-point number. User agents should allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid floating-point number, the control is suffering from bad input.

This specification does not define what user interface user agents are to use; user agent vendors are encouraged to consider what would best serve their users' needs. For example, a user agent in Persian or Arabic markets might support Persian and Arabic numeric input (converting it to the format required for submission as described above). Similarly, a user agent designed for Romans might display the value in Roman numerals rather than in decimal; or (more realistically) a user agent designed for the French market might display the value with apostrophes between thousands and commas before the decimals, and allow the user to enter a value in that manner, internally converting it to the submission format described above.

The value attribute, if specified and not empty, must have a value that is a valid floating-point number.

The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the empty string instead.

The min attribute, if specified, must have a value that is a valid floating-point number. The max attribute, if specified, must have a value that is a valid floating-point number.

The step scale factor is 1. The default step is 1 (allowing only integers to be selected by the user, unless the step base has a non-integer value).

When the element is suffering from a step mismatch, the user agent may round the element's value to the nearest number for which the element would not suffer from a step mismatch. If there are two such numbers, user agents are encouraged to pick the one nearest positive infinity.

The algorithm to convert a string to a number, given a string input, is as follows: If applying the rules for parsing floating-point number values to input results in an error, then return an error; otherwise, return the resulting number.

The algorithm to convert a number to a string, given a number input, is as follows: Return a valid floating-point number that represents input.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, placeholder, readonly, required, and step content attributes; list, value, and valueAsNumber IDL attributes; select(), stepDown(), and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, selectionDirection, and valueAsDate IDL attributes; setRangeText(), and setSelectionRange() methods.

Here is an example of using a numeric input control:

<label>How much do you want to charge? $<input type=number min=0 step=0.01 name=price></label>

As described above, a user agent might support numeric input in the user's local format, converting it to the format required for submission as described above. This might include handling grouping separators (as in "872,000,000,000") and various decimal separators (such as "3,99" vs "3.99") or using local digits (such as those in Arabic, Devanagari, Persian, and Thai).

The type=number state is not appropriate for input that happens to only consist of numbers but isn't strictly speaking a number. For example, it would be inappropriate for credit card numbers or US postal codes. A simple way of determining whether to use type=number is to consider whether it would make sense for the input control to have a spinbox interface (e.g. with "up" and "down" arrows). Getting a credit card number wrong by 1 in the last digit isn't a minor mistake, it's as wrong as getting every digit incorrect. So it would not make sense for the user to select a credit card number using "up" and "down" buttons. When a spinbox interface is not appropriate, type=text is probably the right choice (possibly with an inputmode or pattern attribute).

4.10.5.1.13 Range state (type=range)

Element/input/range

Support in all current engines.

Firefox23+Safari3.1+Chrome4+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android52+Safari iOS5+Chrome Android57+WebView Android4.4+Samsung Internet7.0+Opera AndroidYes

When an input element's type attribute is in the Range state, the rules in this section apply.

The input element represents a control for setting the element's value to a string representing a number, but with the caveat that the exact value is not important, letting UAs provide a simpler interface than they do for the Number state.

If the element is mutable, the user agent should allow the user to change the number represented by its value, as obtained from applying the rules for parsing floating-point number values to it. User agents must not allow the user to set the value to a string that is not a valid floating-point number. If the user agent provides a user interface for selecting a number, then the value must be set to a best representation of the number representing the user's selection as a floating-point number. User agents must not allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid floating-point number, the control is suffering from bad input.

The value attribute, if specified, must have a value that is a valid floating-point number.

The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the best representation, as a floating-point number, of the default value.

The default value is the minimum plus half the difference between the minimum and the maximum, unless the maximum is less than the minimum, in which case the default value is the minimum.

When the element is suffering from an underflow, the user agent must set the element's value to the best representation, as a floating-point number, of the minimum.

When the element is suffering from an overflow, if the maximum is not less than the minimum, the user agent must set the element's value to a valid floating-point number that represents the maximum.

When the element is suffering from a step mismatch, the user agent must round the element's value to the nearest number for which the element would not suffer from a step mismatch, and which is greater than or equal to the minimum, and, if the maximum is not less than the minimum, which is less than or equal to the maximum, if there is a number that matches these constraints. If two numbers match these constraints, then user agents must use the one nearest to positive infinity.

For example, the markup <input type="range" min=0 max=100 step=20 value=50> results in a range control whose initial value is 60.

Here is an example of a range control using an autocomplete list with the list attribute. This could be useful if there are values along the full range of the control that are especially important, such as preconfigured light levels or typical speed limits in a range control used as a speed control. The following markup fragment:

<input type="range" min="-100" max="100" value="0" step="10" name="power" list="powers">
<datalist id="powers">
<option value="0">
<option value="-30">
<option value="30">
 <option value="++50">
</datalist>

...with the following style sheet applied:

input { height: 75px; width: 49px; background: #D5CCBB; color: black; }

...might render as:

A vertical slider control whose primary color is black and whose background color is beige, with the slider having five tick marks, one long one at each extremity, and three short ones clustered around the midpoint.

Note how the UA determined the orientation of the control from the ratio of the style-sheet-specified height and width properties. The colors were similarly derived from the style sheet. The tick marks, however, were derived from the markup. In particular, the step attribute has not affected the placement of tick marks, the UA deciding to only use the author-specified completion values and then adding longer tick marks at the extremes.

Note also how the invalid value ++50 was completely ignored.

For another example, consider the following markup fragment:

<input name=x type=range min=100 max=700 step=9.09090909 value=509.090909>

A user agent could display in a variety of ways, for instance:

As a dial.

Or, alternatively, for instance:

As a long horizontal slider with tick marks.

The user agent could pick which one to display based on the dimensions given in the style sheet. This would allow it to maintain the same resolution for the tick marks, despite the differences in width.

Finally, here is an example of a range control with two labeled values:

<input type="range" name="a" list="a-values">
<datalist id="a-values">
<option value="10" label="Low">
<option value="90" label="High">
</datalist>

With styles that make the control draw vertically, it might look as follows:

A vertical slider control with two tick marks, one near the top labeled 'High', and one near the bottom labeled 'Low'.

In this state, the range and step constraints are enforced even during user input, and there is no way to set the value to the empty string.

The min attribute, if specified, must have a value that is a valid floating-point number. The default minimum is 0. The max attribute, if specified, must have a value that is a valid floating-point number. The default maximum is 100.

The step scale factor is 1. The default step is 1 (allowing only integers, unless the min attribute has a non-integer value).

The algorithm to convert a string to a number, given a string input, is as follows: If applying the rules for parsing floating-point number values to input results in an error, then return an error; otherwise, return the resulting number.

The algorithm to convert a number to a string, given a number input, is as follows: Return the best representation, as a floating-point number, of input.

The following common input element content attributes, IDL attributes, and methods apply to the element: autocomplete, list, max, min, and step content attributes; list, value, and valueAsNumber IDL attributes; stepDown() and stepUp() methods.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, maxlength, minlength, multiple, pattern, placeholder, readonly, required, size, src, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, selectionDirection, and valueAsDate IDL attributes; select(), setRangeText(), and setSelectionRange() methods.

4.10.5.1.14 Color state (type=color)

Element/input/color

Support in all current engines.

Firefox29+Safari12.1+Chrome20+
Opera12+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android27+Safari iOS12.2+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12+

When an input element's type attribute is in the Color state, the rules in this section apply.

The input element represents a color well control, for setting the element's value to a string representing a simple color.

In this state, there is always a color picked, and there is no way to set the value to the empty string.

If the element is mutable, the user agent should allow the user to change the color represented by its value, as obtained from applying the rules for parsing simple color values to it. User agents must not allow the user to set the value to a string that is not a valid lowercase simple color. If the user agent provides a user interface for selecting a color, then the value must be set to the result of using the rules for serializing simple color values to the user's selection. User agents must not allow the user to set the value to the empty string.

Constraint validation: While the user interface describes input that the user agent cannot convert to a valid lowercase simple color, the control is suffering from bad input.

The value attribute, if specified and not empty, must have a value that is a valid simple color.

The value sanitization algorithm is as follows: If the value of the element is a valid simple color, then set it to the value of the element converted to ASCII lowercase; otherwise, set it to the string "#000000".

The following common input element content attributes and IDL attributes apply to the element: autocomplete and list content attributes; list and value IDL attributes; select() method.

The value IDL attribute is in mode value.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, selectionStart, selectionEnd, selectionDirection, valueAsDate and, valueAsNumber IDL attributes; setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

4.10.5.1.15 Checkbox state (type=checkbox)

Element/input/checkbox

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

When an input element's type attribute is in the Checkbox state, the rules in this section apply.

The input element represents a two-state control that represents the element's checkedness state. If the element's checkedness state is true, the control represents a positive selection, and if it is false, a negative selection. If the element's indeterminate IDL attribute is set to true, then the control's selection should be obscured as if the control was in a third, indeterminate, state.

The control is never a true tri-state control, even if the element's indeterminate IDL attribute is set to true. The indeterminate IDL attribute only gives the appearance of a third state.

The input activation behavior is to run the following steps:

  1. If the element is not connected, then return.

  2. Fire an event named input at the element with the bubbles and composed attributes initialized to true.

  3. Fire an event named change at the element with the bubbles attribute initialized to true.

Constraint validation: If the element is required and its checkedness is false, then the element is suffering from being missing.

input . indeterminate [ = value ]

When set, overrides the rendering of checkbox controls so that the current value is not visible.

The following common input element content attributes and IDL attributes apply to the element: checked, and required content attributes; checked and value IDL attributes.

The value IDL attribute is in mode default/on.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, autocomplete, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

4.10.5.1.16 Radio Button state (type=radio)

Element/input/radio

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

When an input element's type attribute is in the Radio Button state, the rules in this section apply.

The input element represents a control that, when used in conjunction with other input elements, forms a radio button group in which only one control can have its checkedness state set to true. If the element's checkedness state is true, the control represents the selected control in the group, and if it is false, it indicates a control in the group that is not selected.

The radio button group that contains an input element a also contains all the other input elements b that fulfill all of the following conditions:

A tree must not contain an input element whose radio button group contains only that element.

When any of the following phenomena occur, if the element's checkedness state is true after the occurrence, the checkedness state of all the other elements in the same radio button group must be set to false:

The input activation behavior is to run the following steps:

  1. If the element is not connected, then return.

  2. Fire an event named input at the element with the bubbles and composed attributes initialized to true.

  3. Fire an event named change at the element with the bubbles attribute initialized to true.

Constraint validation: If an element in the radio button group is required, and all of the input elements in the radio button group have a checkedness that is false, then the element is suffering from being missing.

The following example, for some reason, has specified that puppers are both required and disabled:

<form>
 <p><label><input type="radio" name="dog-type" value="pupper" required disabled> Pupper</label>
 <p><label><input type="radio" name="dog-type" value="doggo"> Doggo</label>
 <p><button>Make your choice</button>
</form>

If the user tries to submit this form without first selecting "Doggo", then both input elements will be suffering from being missing, since an element in the radio button group is required (viz. the first element), and both of the elements in the radio button group have a false checkedness.

On the other hand, if the user selects "Doggo" and then submits the form, then neither input element will be suffering from being missing, since while one of them is required, not all of them have a false checkedness.

If none of the radio buttons in a radio button group are checked, then they will all be initially unchecked in the interface, until such time as one of them is checked (either by the user or by script).

The following common input element content attributes and IDL attributes apply to the element: checked and required content attributes; checked and value IDL attributes.

The value IDL attribute is in mode default/on.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: accept, alt, autocomplete, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

4.10.5.1.17 File Upload state (type=file)

Element/input/file

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera11+Edge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android11+

When an input element's type attribute is in the File Upload state, the rules in this section apply.

The input element represents a list of selected files, each file consisting of a file name, a file type, and a file body (the contents of the file).

File names must not contain path components, even in the case that a user has selected an entire directory hierarchy or multiple files with the same name from different directories. Path components, for the purposes of the File Upload state, are those parts of file names that are separated by U+005C REVERSE SOLIDUS character (\) characters.

Unless the multiple attribute is set, there must be no more than one file in the list of selected files.

The element's input activation behavior is to run the following steps:

  1. If the algorithm is invoked when the element's Window object does not have transient activation, then return without doing anything else.

  2. Run these steps in parallel:

    1. Optionally, wait until any prior execution of this algorithm has terminated.

    2. Display a prompt to the user requesting that the user specify some files. If the multiple attribute is not set, there must be no more than one file selected; otherwise, any number may be selected. Files can be from the filesystem or created on the fly, e.g., a picture taken from a camera connected to the user's device.

    3. Wait for the user to have made their selection.

    4. Update the file selection for the input element.

If the element is mutable, the user agent should allow the user to change the files on the list in other ways also, e.g., adding or removing files by drag-and-drop. When the user does so, the user agent must update the file selection for the element.

If the element is not mutable, the user agent must not allow the user to change the element's selection.

To update the file selection for an element element:

  1. Queue an element task on the user interaction task source given element and the following steps:

    1. Update element's selected files so that it represents the user's selection.

    2. Fire an event named input at the input element, with the bubbles and composed attributes initialized to true.

    3. Fire an event named change at the input element, with the bubbles attribute initialized to true.

Constraint validation: If the element is required and the list of selected files is empty, then the element is suffering from being missing.


Element/input#attr-accept

Support in all current engines.

Firefox37+Safari11.1+Chrome26+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android37+Safari iOS11.3+Chrome Android26+WebView Android4.4+Samsung Internet1.5+Opera Android15+

The accept attribute may be specified to provide user agents with a hint of what file types will be accepted.

If specified, the attribute must consist of a set of comma-separated tokens, each of which must be an ASCII case-insensitive match for one of the following:

The string "audio/*"
Indicates that sound files are accepted.
The string "video/*"
Indicates that video files are accepted.
The string "image/*"
Indicates that image files are accepted.
A valid MIME type string with no parameters
Indicates that files of the specified type are accepted.
A string whose first character is a U+002E FULL STOP character (.)
Indicates that files with the specified file extension are accepted.

The tokens must not be ASCII case-insensitive matches for any of the other tokens (i.e. duplicates are not allowed). To obtain the list of tokens from the attribute, the user agent must split the attribute value on commas.

User agents may use the value of this attribute to display a more appropriate user interface than a generic file picker. For instance, given the value image/*, a user agent could offer the user the option of using a local camera or selecting a photograph from their photo collection; given the value audio/*, a user agent could offer the user the option of recording a clip using a headset microphone.

User agents should prevent the user from selecting files that are not accepted by one (or more) of these tokens.

Authors are encouraged to specify both any MIME types and any corresponding extensions when looking for data in a specific format.

For example, consider an application that converts Microsoft Word documents to Open Document Format files. Since Microsoft Word documents are described with a wide variety of MIME types and extensions, the site can list several, as follows:

<input type="file" accept=".doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">

On platforms that only use file extensions to describe file types, the extensions listed here can be used to filter the allowed documents, while the MIME types can be used with the system's type registration table (mapping MIME types to extensions used by the system), if any, to determine any other extensions to allow. Similarly, on a system that does not have file names or extensions but labels documents with MIME types internally, the MIME types can be used to pick the allowed files, while the extensions can be used if the system has an extension registration table that maps known extensions to MIME types used by the system.

Extensions tend to be ambiguous (e.g. there are an untold number of formats that use the ".dat" extension, and users can typically quite easily rename their files to have a ".doc" extension even if they are not Microsoft Word documents), and MIME types tend to be unreliable (e.g. many formats have no formally registered types, and many formats are in practice labeled using a number of different MIME types). Authors are reminded that, as usual, data received from a client should be treated with caution, as it may not be in an expected format even if the user is not hostile and the user agent fully obeyed the accept attribute's requirements.

Element/input/file

For historical reasons, the value IDL attribute prefixes the file name with the string "C:\fakepath\". Some legacy user agents actually included the full path (which was a security vulnerability). As a result of this, obtaining the file name from the value IDL attribute in a backwards-compatible way is non-trivial. The following function extracts the file name in a suitably compatible manner:

function extractFilename(path) {
  if (path.substr(0, 12) == "C:\\fakepath\\")
    return path.substr(12); // modern browser
  var x;
  x = path.lastIndexOf('/');
  if (x >= 0) // Unix-based path
    return path.substr(x+1);
  x = path.lastIndexOf('\\');
  if (x >= 0) // Windows-based path
    return path.substr(x+1);
  return path; // just the file name
}

This can be used as follows:

<p><input type=file name=image onchange="updateFilename(this.value)"></p>
<p>The name of the file you picked is: <span id="filename">(none)</span></p>
<script>
 function updateFilename(path) {
   var name = extractFilename(path);
   document.getElementById('filename').textContent = name;
 }
</script>

The following common input element content attributes and IDL attributes apply to the element: accept, multiple, and required content attributes; files and value IDL attributes; select() method.

The value IDL attribute is in mode filename.

The input and change events apply.

The following content attributes must not be specified and do not apply to the element: alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, pattern, placeholder, readonly, size, src, step, and width.

The element's value attribute must be omitted.

The following IDL attributes and methods do not apply to the element: checked, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

4.10.5.1.18 Submit Button state (type=submit)

Element/input/submit

Support in all current engines.

Firefox1+Safari1+Chrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

When an input element's type attribute is in the Submit Button state, the rules in this section apply.

(This is a tracking vector.) The input element represents a button that, when activated, submits the form. If the element has a value attribute, the button's label must be the value of that attribute; otherwise, it must be an implementation-defined string that means "Submit" or some such. The element is a button, specifically a submit button.

Since the default label is implementation-defined, and the width of the button typically depends on the button's label, the button's width can leak a few bits of fingerprintable information. These bits are likely to be strongly correlated to the identity of the user agent and the user's locale.

The element's input activation behavior is as follows: if the element has a form owner, and the element's node document is fully active, submit the form owner from the input element; otherwise, do nothing.

The formaction, formenctype, formmethod, formnovalidate, and formtarget attributes are attributes for form submission.

The formnovalidate attribute can be used to make submit buttons that do not trigger the constraint validation.

The following common input element content attributes and IDL attributes apply to the element: formaction, formenctype, formmethod, formnovalidate, and formtarget content attributes; value IDL attribute.

The value IDL attribute is in mode default.

The following content attributes must not be specified and do not apply to the element: accept, alt, autocomplete, checked, dirname, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

The input and change events do not apply.

4.10.5.1.19 Image Button state (type=image)

Element/input/image

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome Android?WebView AndroidYesSamsung Internet?Opera AndroidYes

When an input element's type attribute is in the Image Button state, the rules in this section apply.

The input element represents either an image from which a user can select a coordinate and submit the form, or alternatively a button from which the user can submit the form. The element is a button, specifically a submit button.

The coordinate is sent to the server during form submission by sending two entries for the element, derived from the name of the control but with ".x" and ".y" appended to the name with the x and y components of the coordinate respectively.


The image is given by the src attribute. The src attribute must be present, and must contain a valid non-empty URL potentially surrounded by spaces referencing a non-interactive, optionally animated, image resource that is neither paged nor scripted.

When any of the these events occur

then unless the user agent cannot support images, or its support for images has been disabled, or the user agent only fetches images on demand, or the src attribute's value is the empty string, the user agent must parse the value of the src attribute value, relative to the element's node document, and if that is successful, then:

  1. Let request be a new request whose url is the resulting URL record, client is the element's node document's relevant settings object, destination is "image", credentials mode is "include", and whose use-URL-credentials flag is set.

  2. Fetch request.

Fetching the image must delay the load event of the element's node document until the task that is queued by the networking task source once the resource has been fetched (defined below) has been run.

If the image was successfully obtained, with no network errors, and the image's type is a supported image type, and the image is a valid image of that type, then the image is said to be available. If this is true before the image is completely downloaded, each task that is queued by the networking task source while the image is being fetched must update the presentation of the image appropriately.

The user agent should apply the image sniffing rules to determine the type of the image, with the image's associated Content-Type headers giving the official type. If these rules are not applied, then the type of the image must be the type given by the image's associated Content-Type headers.

User agents must not support non-image resources with the input element. User agents must not run executable code embedded in the image resource. User agents must only display the first page of a multipage resource. User agents must not allow the resource to act in an interactive fashion, but should honor any animation in the resource.

The task that is queued by the networking task source once the resource has been fetched, must, if the download was successful and the image is available, queue an element task on the user interaction task source given the input element to fire an event named load at the input element; and otherwise, if the fetching process fails without a response from the remote server, or completes but the image is not a valid or supported image, queue an element task on the user interaction task source given the input element to fire an event named error on the input element.


The alt attribute provides the textual label for the button for users and user agents who cannot use the image. The alt attribute must be present, and must contain a non-empty string giving the label that would be appropriate for an equivalent button if the image was unavailable.

The input element supports dimension attributes.


If the src attribute is set, and the image is available and the user agent is configured to display that image, then: The element represents a control for selecting a coordinate from the image specified by the src attribute; if the element is mutable, the user agent should allow the user to select this coordinate, and the element's input activation behavior is as follows: if the element has a form owner, and the element's node document is fully active, take the user's selected coordinate, and submit the input element's form owner from the input element. If the user activates the control without explicitly selecting a coordinate, then the coordinate (0,0) must be assumed.

Otherwise, the element represents a submit button whose label is given by the value of the alt attribute; the element's input activation behavior is as follows: if the element has a form owner, and the element's node document is fully active, set the selected coordinate to (0,0), and submit the input element's form owner from the input element.

In either case, if the element has no form owner or the element's node document is not fully active, then its input activation behavior must be to do nothing..

The selected coordinate must consist of an x-component and a y-component. The coordinates represent the position relative to the edge of the image, with the coordinate space having the positive x direction to the right, and the positive y direction downwards.

The x-component must be a valid integer representing a number x in the range −(borderleft+paddingleft) ≤ xwidth+borderright+paddingright, where width is the rendered width of the image, borderleft is the width of the border on the left of the image, paddingleft is the width of the padding on the left of the image, borderright is the width of the border on the right of the image, and paddingright is the width of the padding on the right of the image, with all dimensions given in CSS pixels.

The y-component must be a valid integer representing a number y in the range −(bordertop+paddingtop) ≤ yheight+borderbottom+paddingbottom, where height is the rendered height of the image, bordertop is the width of the border above the image, paddingtop is the width of the padding above the image, borderbottom is the width of the border below the image, and paddingbottom is the width of the padding below the image, with all dimensions given in CSS pixels.

Where a border or padding is missing, its width is zero CSS pixels.


The formaction, formenctype, formmethod, formnovalidate, and formtarget attributes are attributes for form submission.

image . width [ = value ]
image . height [ = value ]

These attributes return the actual rendered dimensions of the image, or zero if the dimensions are not known.

They can be set, to change the corresponding content attributes.

The following common input element content attributes and IDL attributes apply to the element: alt, formaction, formenctype, formmethod, formnovalidate, formtarget, height, src, and width content attributes; value IDL attribute.

The value IDL attribute is in mode default.

The following content attributes must not be specified and do not apply to the element: accept, autocomplete, checked, dirname, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, and step.

The element's value attribute must be omitted.

The following IDL attributes and methods do not apply to the element: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

The input and change events do not apply.

Many aspects of this state's behavior are similar to the behavior of the img element. Readers are encouraged to read that section, where many of the same requirements are described in more detail.

Take the following form:

<form action="process.cgi">
 <input type=image src=map.png name=where alt="Show location list">
</form>

If the user clicked on the image at coordinate (127,40) then the URL used to submit the form would be "process.cgi?where.x=127&where.y=40".

(In this example, it's assumed that for users who don't see the map, and who instead just see a button labeled "Show location list", clicking the button will cause the server to show a list of locations to pick from instead of the map.)

4.10.5.1.20 Reset Button state (type=reset)

Element/input/reset

Support in all current engines.

Firefox1+Safari1+Chrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

When an input element's type attribute is in the Reset Button state, the rules in this section apply.

(This is a tracking vector.) The input element represents a button that, when activated, resets the form. If the element has a value attribute, the button's label must be the value of that attribute; otherwise, it must be an implementation-defined string that means "Reset" or some such. The element is a button.

Since the default label is implementation-defined, and the width of the button typically depends on the button's label, the button's width can leak a few bits of fingerprintable information. These bits are likely to be strongly correlated to the identity of the user agent and the user's locale.

The element's input activation behavior, if the element has a form owner and the element's node document is fully active, is to reset the form owner; otherwise, it is to do nothing.

Constraint validation: The element is barred from constraint validation.

The value IDL attribute applies to this element and is in mode default.

The following content attributes must not be specified and do not apply to the element: accept, alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

The input and change events do not apply.

4.10.5.1.21 Button state (type=button)

Element/input/button

Support in all current engines.

Firefox1+Safari1+Chrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome Android18+WebView AndroidYesSamsung Internet1.0+Opera AndroidYes

When an input element's type attribute is in the Button state, the rules in this section apply.

The input element represents a button with no default behavior. A label for the button must be provided in the value attribute, though it may be the empty string. If the element has a value attribute, the button's label must be the value of that attribute; otherwise, it must be the empty string. The element is a button.

The element has no input activation behavior.

Constraint validation: The element is barred from constraint validation.

The value IDL attribute applies to this element and is in mode default.

The following content attributes must not be specified and do not apply to the element: accept, alt, autocomplete, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, list, max, maxlength, min, minlength, multiple, pattern, placeholder, readonly, required, size, src, step, and width.

The following IDL attributes and methods do not apply to the element: checked, files, list, selectionStart, selectionEnd, selectionDirection, valueAsDate, and valueAsNumber IDL attributes; select(), setRangeText(), setSelectionRange(), stepDown(), and stepUp() methods.

The input and change events do not apply.

4.10.5.2 关于表单控件的本地化的实现笔记

This section is non-normative.

日期、时间和数字控件展示给用户的格式与提交表单使用的格式相独立。

鼓励浏览器根据 input 元素的 language 或用户偏好中的语言环境暗示的惯例 来展示日期、时间和数字的 UI。使用页面的语言环境可以确保页面提供的数据一致。

例如,如果一个美式英语区域的页面说 Cirque De Soleil 节目将会在 02/03 播出,但浏览器设置了英式英语区域, 在购票日期选择中会把日期显示为 03/02,这会让用户很困惑。 使用页面的区域设置至少可以确保日期在所有地方都以同一种格式显示。 (当然用户仍然可能迟到一个月,但对于这样的文化差异只能做到这个地步了...)

4.10.5.3 通用 input 元素属性

这些属性只 适用于 input 元素的 type 属性所处的状态定义了这个属性 适用 的情况。 当一个属性 不适用于 input 元素时, 用户代理必须 忽略 这个属性,忽略下面的要求和定义。

4.10.5.3.1 The maxlength and minlength attributes

Element/input#attr-maxlength

Support in all current engines.

Firefox4+Safari5.1+Chrome4+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android5+Safari iOS9+Chrome Android18+WebView Android4.4+Samsung Internet1.5+Opera Android15+
caniuse.com table

The maxlength attribute, when it applies, is a form control maxlength attribute.

Element/input#attr-minlength

Support in all current engines.

Firefox51+Safari10.1+Chrome40+
Opera27+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android51+Safari iOS10.3+Chrome Android40+WebView Android40+Samsung Internet4.0+Opera Android27+
caniuse.com table

The minlength attribute, when it applies, is a form control minlength attribute.

If the input element has a maximum allowed value length, then the length of the value of the element's value attribute must be equal to or less than the element's maximum allowed value length.

The following extract shows how a messaging client's text entry could be arbitrarily restricted to a fixed number of characters, thus forcing any conversation through this medium to be terse and discouraging intelligent discourse.

<label>What are you doing? <input name=status maxlength=140></label>

Here, a password is given a minimum length:

<p><label>Username: <input name=u required></label>
<p><label>Password: <input name=p required minlength=12></label>
4.10.5.3.2 size 属性

size 属性给出了 在用户编辑元素的 的时候,用户代理允许用户看到的字符数目。

指定 size 属性时,值必须是一个大于零的 合法的非负整数

如果指定了这个属性,就必须使用 解析非负整数的规则 解析它的值, 如果结果是一个大于零的数字,用户代理应该确保至少那么多字符可见。

size IDL 属性 仅限于大于零的非负整数, 默认值为 20。

4.10.5.3.3 readonly 属性

Attributes/readonly

Support in all current engines.

Firefox1+Safari≤4+Chrome1+
Opera≤12.1+Edge79+
Edge (Legacy)12+Internet Explorer≤6+
Firefox Android4+Safari iOS≤3+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android≤12.1+

readonly 属性是一个 布尔属性 用来控制用户是否可以编辑这个表单控件。 指定后这个元素就不 可变 了。

约束验证:如果在 input 元素上指定了 readonly 属性,这个元素就 禁止约束验证

disabledreadonly 之间的区别是 read-only 控件仍然运作, 但 disabled 控件通常不具有控件的功能。这在本规范的其他地方会对 disabled 的概念的形式化要求进行详细介绍。 (例如元素的 激活行为,是否是一个 可聚焦区域,或何时 构造项目列表)。 禁用控件的任何其他与用户交互相关的行为都不在本规范中定义,比如文本是否可以选择和拷贝。

只有文本控件可以做成只读,因为其他控件(比如复选框和按钮)的只读和禁用没什么区别, 所以 readonly 属性 不适用

在下面的例子中,已经存在的产品标识不可修改,但仍然可以显示为表单的一部分, 只是为了与显示新产品(它的标识还未填写)的行保持一致。

<form action="products.cgi" method="post" enctype="multipart/form-data">
 <table>
  <tr> <th> Product ID <th> Product name <th> Price <th> Action
  <tr>
   <td> <input readonly="readonly" name="1.pid" value="H412">
   <td> <input required="required" name="1.pname" value="Floor lamp Ulke">
   <td> $<input required="required" type="number" min="0" step="0.01" name="1.pprice" value="49.99">
   <td> <button formnovalidate="formnovalidate" name="action" value="delete:1">Delete</button>
  <tr>
   <td> <input readonly="readonly" name="2.pid" value="FG28">
   <td> <input required="required" name="2.pname" value="Table lamp Ulke">
   <td> $<input required="required" type="number" min="0" step="0.01" name="2.pprice" value="24.99">
   <td> <button formnovalidate="formnovalidate" name="action" value="delete:2">Delete</button>
  <tr>
   <td> <input required="required" name="3.pid" value="" pattern="[A-Z0-9]+">
   <td> <input required="required" name="3.pname" value="">
   <td> $<input required="required" type="number" min="0" step="0.01" name="3.pprice" value="">
   <td> <button formnovalidate="formnovalidate" name="action" value="delete:3">Delete</button>
 </table>
 <p> <button formnovalidate="formnovalidate" name="action" value="add">Add</button> </p>
 <p> <button name="action" value="update">Save</button> </p>
</form>
4.10.5.3.4 required 属性

required 属性是一个 布尔属性。当指定时这个元素就是 必要的

约束验证:如果这个元素是 必要的, 且它的 value IDL 属性 适用 且处于 value 模式,而且该元素是 可变的,而且该元素的 value 为空字符串,那么这个元素就 处于缺失错误状态

下面的表单有两个必要字段,一个是邮件地址另一个是密码。 第三个字段只在用户输入与密码字段同样的密码时才有效。

<h1>Create new account</h1>
<form action="/newaccount" method=post
      oninput="up2.setCustomValidity(up2.value != up.value ? 'Passwords do not match.' : '')">
 <p>
  <label for="username">E-mail address:</label>
  <input id="username" type=email required name=un>
 <p>
  <label for="password1">Password:</label>
  <input id="password1" type=password required name=up>
 <p>
  <label for="password2">Confirm password:</label>
  <input id="password2" type=password name=up2>
 <p>
  <input type=submit value="Create account">
</form>

对于单选按钮,如果 分组 中任意一个单选按钮被选中, required 属性就会被满足。 因此在下面的例子中,可以选中任意一个单选按钮,而不仅仅是标记为必选的那个:

<fieldset>
 <legend>Did the movie pass the Bechdel test?</legend>
 <p><label><input type="radio" name="bechdel" value="no-characters"> No, there are not even two female characters in the movie. </label>
 <p><label><input type="radio" name="bechdel" value="no-names"> No, the female characters never talk to each other. </label>
 <p><label><input type="radio" name="bechdel" value="no-topic"> No, when female characters talk to each other it's always about a male character. </label>
 <p><label><input type="radio" name="bechdel" value="yes" required> Yes. </label>
 <p><label><input type="radio" name="bechdel" value="unknown"> I don't know. </label>
</fieldset>

为避免困惑 关于是否 单选按钮分组 是否是必选的, 鼓励作者在组中的所有单选按钮上都指定属性,其实通常也鼓励作者避免这种没有初始选中的单选按钮分组, 因为用户无法返回到这个状态,因此也通常被认为是糟糕的用户界面。

4.10.5.3.5 multiple 属性

Element/input#attr-multiple

Support in all current engines.

Firefox3.6+Safari4+Chrome2+
Opera≤12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android≤37+Samsung Internet1.0+Opera Android≤12.1+

multiple 属性是一个 布尔属性,表示是否允许用户指定多个值。

下面的片段展示了 e-mail 客户端的 "To" 字符串如何接受多个 e-mail 地址。

<label>To: <input type=email multiple name=to></label>

如果用户的联系人数据库中有这样两个朋友:"Spider-Man" (地址为"spider@parker.example.net")和 "Scarlet Witch"(地址为"scarlet@avengers.example.net"), 在用户输入了 "s" 后,用户代理可能会给用户建议这些 e-mail 地址。

这个页面可能会链接到用户的联系人数据库:

<label>To: <input type=email multiple name=to list=contacts></label>
...
<datalist id="contacts">
 <option value="hedral@damowmow.com">
 <option value="pillar@example.com">
 <option value="astrophy@cute.example">
 <option value="astronomy@science.example.org">
</datalist>

假设用户在文本控件中输入了 "bob@example.net",然后开始键入第二个 e-mail 地址,开头是 "s"。用户代理可能会显示前面提到的两个朋友, 以及 datalist 元素给出的 "astrophy" 和 "astronomy" 两个值。

下面的片段展示了 e-mail 客户端的 "Attachments" 字段是如何接受多个文件上传的。

<label>Attachments: <input type=file multiple name=att></label>
4.10.5.3.6 pattern 属性

pattern 属性指定了 该控件的 的正则表达式, 或者当设置了 multiple 属性并且输入控件 适用这个属性 时, 就要检查这个控件的值

如果指定了这个属性,它的值必须匹配 JavaScript Pattern 生成式。

如果 input 元素设置了 pattern 属性,且这个属性的值可以作为 JavaScript 正则表达式(只带 "u" 标志)成功地编译, 那么结果正则表达式就是这个元素的 编译后的模式正则表达式。 如果这个元素没有这种属性,或者其属性值不能成功编译,那么这个元素就没有 编译后的模式正则表达式[JAVASCRIPT]

如果值不能成功编译,鼓励用户代理把这个日志打到开发控制台来帮助调试。

约束验证:如果这个元素的 不是空字符串,或者元素没有指定 multiple 属性, 或者它 不适用input 元素的 type 属性的当前状态,且这个元素有 编译后的模式正则表达式 但这个正则不匹配元素的 ,那么就说这个元素 处于模式不匹配错误状态

约束验证:如果这个元素的 value 不是空字符串, 且这个元素指定了 multiple 属性, 且 适用于 input 元素, 且该元素有一个 编译后的模式正则表达式, 但这个正则不匹配元素的每一个值 values, 那么这个元素 处于模式不匹配错误状态

编译后的模式正则表达式 与字符串进行匹配时,必须把它的开始位置对准字符串的开始位置,它的结尾对准字符串的结尾位置。

这意味着用于这个属性的正则表达式语言与用于 JavaScript 的一样,除了 pattern 属性匹配的是整个值,而不是一个子集 (有些像是在前面添加一个 ^(?:,在后面加一个 )$

当一个 input 元素设置有 pattern 属性时, 作者应该引入一个 title 属性来描述这个模式。 如果有的话,当用户代理提示用户模式不匹配的时候,或者其他任何适当的时候,都可以使用这个属性的内容。 比如显示为一个 tooltip,或者在控件 获得焦点 时由辅助技术读出来。

例如下面的片段:

<label> Part number:
 <input pattern="[0-9][A-Z]{3}" name="part"
        title="A part number is a digit followed by three uppercase letters."/>
</label>

...could cause the UA to display an alert such as:

A part number is a digit followed by three uppercase letters.
You cannot submit this form when the field is incorrect.

当一个控件有 pattern 属性时,如果用了 title 属性,它就必须描述这个模式。 也可以包含额外的信息,只要是帮助用户填写这个控件的。否则辅助技术将受到影响。

假如 title 属性包含控件标题, 辅助技术可能会说 你输入的文字不匹配要求的模式:生日,这根本没用。

UA 仍然可以在没错误的情况下显示 title (例如作为悬停在空间上时的 tooltip),这样作者应该注意不要把 title 的文字写得像是已经发生了错误一样。

4.10.5.3.7 minmax 属性

有些表单控件可以有显式的约束来限制用户提供的值的范围。 通常,这样的范围将是线性的并且是连续的。 表单控件可能 有周期性的范围 但最宽可能的范围是有限的, 作者可以显式地设置一个横跨边界的范围。

具体而言,最广泛的 type=time 控件最宽的范围是午夜到午夜(24小时), 作者可以设置连续线性的范围(比如9pm到11pm),也可以设置跨过午夜的不连续的范围(比如 11pm 到 1am)。

minmax 属性表示这个元素允许的值的范围。

它们的语法由定义 type 属性当前状态的章节定义。

如果这个元素有 min 属性,而且对 min 属性执行 字符串转换为数字算法 的结果是一个数字,那么这个数字就是该元素的 最小值; 否则,如果 type 属性的当前状态定义了 默认最小值,那么这就是 最小值;否则,这个元素就没有 最小值

min 属性还定义了 step base

如果这个元素有 max 属性,而且对 max 属性执行 字符串转换为数字算法 的结果是一个数字,那么这个数字就是该元素的 最大值; 否则,如果 type 属性的当前状态定义了 默认最大值,那么这就是 最大值;否则,这个元素就没有 最大值

如果这个元素没有 周期性的范围max 属性的值(最大值)不得小于 min 属性的值(最小值)。

如果没有 周期性的范围 的元素的 最大值 小于它的 最小值,只要这个元素有 , 那么它或者 处于下溢出错误状态, 或者 处于上溢出错误状态

如果元素 有周期性的范围 且它的 最大值 小于 最小值, 那么它就 有反转的范围

如果一个元素定义了 最小值最大值, 那么它就 有范围限制

约束验证:当元素有 最小值 而且没有 反转范围,而且对元素的 value 给出的字符串执行 字符串转换为数字算法 得到的结果是一个数字, 而且得到的这个数字小于 最小值,这个元素就 处于下溢出错误状态

约束验证:当元素有 最大值 而且没有 反转范围,而且对元素的 value 给出的字符串执行 字符串转换为数字算法 得到的结果是一个数字, 而且得到的这个数字大于 最大值,这个元素就 处于上溢出错误状态

约束验证:当元素 有反转范围 时, 如果在该元素的 value 给出的字符串上执行 字符串转换为数字算法 得到的结果是一个数字, 而且这个数字大于 最大值 小于 最小值,该元素就同时 处于下溢出状态上溢出状态

下面的日期控件限制输入在 1980 年之前:

<input name=bday type=date max="1979-12-31">

下面的数字控件限制输入为大于 0 的整数:

<input name=quantity required="" type="number" min="1" value="1">

下面的时间控件限制输入为 9pm 到 6am 之间的分钟,默认为午夜:

<input name="sleepStart" type=time min="21:00" max="06:00" step="60" value="00:00">
4.10.5.3.8 The step attribute

The step attribute indicates the granularity that is expected (and required) of the value or values, by limiting the allowed values. The section that defines the type attribute's current state also defines the default step, the step scale factor, and in some cases the default step base, which are used in processing the attribute as described below.

The step attribute, if specified, must either have a value that is a valid floating-point number that parses to a number that is greater than zero, or must have a value that is an ASCII case-insensitive match for the string "any".

The attribute provides the allowed value step for the element, as follows:

  1. If the attribute does not apply, then there is no allowed value step.

  2. Otherwise, if the attribute is absent, then the allowed value step is the default step multiplied by the step scale factor.

  3. Otherwise, if the attribute's value is an ASCII case-insensitive match for the string "any", then there is no allowed value step.

  4. Otherwise, if the rules for parsing floating-point number values, when they are applied to the attribute's value, return an error, zero, or a number less than zero, then the allowed value step is the default step multiplied by the step scale factor.

  5. Otherwise, the allowed value step is the number returned by the rules for parsing floating-point number values when they are applied to the attribute's value, multiplied by the step scale factor.

The step base is the value returned by the following algorithm:

  1. If the element has a min content attribute, and the result of applying the algorithm to convert a string to a number to the value of the min content attribute is not an error, then return that result.

  2. If the element has a value content attribute, and the result of applying the algorithm to convert a string to a number to the value of the value content attribute is not an error, then return that result.

  3. If a default step base is defined for this element given its type attribute's state, then return it.

  4. Return zero.

Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to the string given by the element's value is a number, and that number subtracted from the step base is not an integral multiple of the allowed value step, the element is suffering from a step mismatch.

The following range control only accepts values in the range 0..1, and allows 256 steps in that range:

<input name=opacity type=range min=0 max=1 step=0.00392156863>

The following control allows any time in the day to be selected, with any accuracy (e.g. thousandth-of-a-second accuracy or more):

<input name=favtime type=time step=any>

Normally, time controls are limited to an accuracy of one minute.

4.10.5.3.9 list 属性

list 属性用于识别 给用户列出了建议的预定义选项的元素。

如果指定了这个属性,它的值必须是同一个 中的 datalist 元素的 ID

建议来源元素 是在 中的 按照 树序 的第一个 ID 属性等于 list 属性值的 datalist 元素。 如果没有 list 属性,或者没有这个 ID 的元素,或者第一个有这个 ID 的元素不是 datalist 元素,那就没有 建议来源元素

如果有一个 建议来源元素,那么当用户代理 允许用户编辑这个 input 元素的 时, 用户代理应该把 建议来源元素 表示的建议以与控件类型相适应的方式提供给用户。 如果合适的话,用户代理应该使用建议的 labelvalue 来给用户标识建议。

如果建议很多,鼓励用户代理过滤 建议来源元素 表示的建议, (比如基于用户目前的输入)只显示最相关的那些。没有定义精确的阈值,但 4-7 个值是比较合理的。 如果是基于用户输入进行过滤,用户代理应该对建议的 labelvalue 进行子字符串匹配。

这个文本字段允许你选择一个JavaScript 函数类型。

<input type="text" list="function-types">
<datalist id="function-types">
  <option value="function">function</option>
  <option value="async function">async function</option>
  <option value="function*">generator function</option>
  <option value="=>">arrow function</option>
  <option value="async =>">async arrow function</option>
  <option value="async function*">async generator function</option>
</datalist>

对遵守以上建议的用户代理,labelvalue 可能会显示为:

A text box with a drop down button on the right hand side; with, below, a drop down box containing a list of the six values the left and the six labels on the right.

然后键入 "arrow" 或 "=>" 将会把列表过滤为 "arrow function" 和 "async arrow function"。 键入 "generator" 或 "*" 将会把列表过滤为 "generator function" 和 "async generator function"。

与往常一样,用户代理可以自己决定什么样的用户界面适合特定的要求和特定的用户场景。 但这在历史上是实现方,Web 开发者,用户都容易混淆的地方, 所以我们给出了一些 "应该" 遵守的建议。

如何处理用户选择建议项取决于这个控件元素只接受单个值还是接受多个值:

如果这个元素没有设置 multiple 属性 或者如果 multiple 属性 不适用

当用户选择一项建议时,input 元素的 必须被设置为选中建议的 ,就像用户自己写了那个值一样。

如果这个元素的 type 属性处于 Email 状态且该元素设置了 multiple 属性

当用户选择一项建议时,用户代理必须添加一个新项目到 input 元素的 中, 其值为选中建议项的 , 或者把 input 元素的 中的既有项改为选中的建议项的 给出的值。 就像是用户自己添加了一项那个值,或者把既有项编辑成那个值。 应用上述哪个行为取决于用户代理定义的用户界面。


如果 list 属性 不适用,就不存在 建议来源元素

这个 URL 字段提供了一些建议。

<label>Homepage: <input name=hp type=url list=hpurls></label>
<datalist id=hpurls>
 <option value="https://www.google.com/" label="Google">
 <option value="https://www.reddit.com/" label="Reddit">
</datalist>

用户历史中的其他 URL 也可能显示;这取决于用户代理。

这个例子演示了如何使用自动完成列表功能设计一个表单,同时仍然能在旧用户代理上做有用的降级。

如果自动完成列表仅仅是一种帮助,而且对内容不重要。那么直接使用 datalist 元素和子 option 元素就足够了。 为了阻止在旧用户代理上渲染这些值,需要把它们放到 value 属性中,而不是内联。

<p>
 <label>
  Enter a breed:
  <input type="text" name="breed" list="breeds">
  <datalist id="breeds">
   <option value="Abyssinian">
   <option value="Alpaca">
   <!-- ... -->
  </datalist>
 </label>
</p>

但如果需要在旧 UA 显示这些值,fallback 内容可以放在 datalist 元素中,像这样:

<p>
 <label>
  Enter a breed:
  <input type="text" name="breed" list="breeds">
 </label>
 <datalist id="breeds">
  <label>
   or select one from the list:
   <select name="breed">
    <option value=""> (none selected)
    <option>Abyssinian
    <option>Alpaca
    <!-- ... -->
   </select>
  </label>
 </datalist>
</p>

fallback 内容只会在不支持 datalist 的 UA 显示。 但这些 option 会被所有 UA 检测到,即使它们不是 datalist 元素的子节点。

注意如果在 datalist 中用到的 option 元素处于 selected 状态, 它会在旧 UA 上默认选中(因为它会影响 select), 但它在支持 datalist 的 UA 上对 input 元素将不会有任何影响。

4.10.5.3.10 The placeholder attribute

Element/input#attr-placeholder

Support in all current engines.

Firefox4+Safari4+Chrome3+
Opera≤12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android≤37+Samsung Internet1.0+Opera Android≤12.1+

The placeholder attribute represents a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. A hint could be a sample value or a brief description of the expected format. The attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.

The placeholder attribute should not be used as an alternative to a label. For a longer hint or other advisory text, the title attribute is more appropriate.

These mechanisms are very similar but subtly different: the hint given by the control's label is shown at all times; the short hint given in the placeholder attribute is shown before the user enters a value; and the hint in the title attribute is shown when the user requests further help.

User agents should present this hint to the user, after having stripped newlines from it, when the element's value is the empty string, especially if the control is not focused.

If a user agent normally doesn't show this hint to the user when the control is focused, then the user agent should nonetheless show the hint for the control if it was focused as a result of the autofocus attribute, since in that case the user will not have had an opportunity to examine the control before focusing it.

Here is an example of a mail configuration user interface that uses the placeholder attribute:

<fieldset>
 <legend>Mail Account</legend>
 <p><label>Name: <input type="text" name="fullname" placeholder="John Ratzenberger"></label></p>
 <p><label>Address: <input type="email" name="address" placeholder="john@example.net"></label></p>
 <p><label>Password: <input type="password" name="password"></label></p>
 <p><label>Description: <input type="text" name="desc" placeholder="My Email Account"></label></p>
</fieldset>

In situations where the control's content has one directionality but the placeholder needs to have a different directionality, Unicode's bidirectional-algorithm formatting characters can be used in the attribute value:

<input name=t1 type=tel placeholder="&#x202B;رقم الهاتف 1&#x202E;">
<input name=t2 type=tel placeholder="&#x202B;رقم الهاتف 2&#x202E;">

For slightly more clarity, here's the same example using numeric character references instead of inline Arabic:

<input name=t1 type=tel placeholder="&#x202B;&#1585;&#1602;&#1605; &#1575;&#1604;&#1607;&#1575;&#1578;&#1601; 1&#x202E;">
<input name=t2 type=tel placeholder="&#x202B;&#1585;&#1602;&#1605; &#1575;&#1604;&#1607;&#1575;&#1578;&#1601; 2&#x202E;">
4.10.5.4 Common input element APIs
input . value [ = value ]

Returns the current value of the form control.

Can be set, to change the value.

Throws an "InvalidStateError" DOMException if it is set to any value other than the empty string when the control is a file upload control.

input . checked [ = value ]

Returns the current checkedness of the form control.

Can be set, to change the checkedness.

input . files [ = files ]

FileList

Support in all current engines.

Firefox3+Safari4+Chrome1+
Opera11.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11.1+

Returns a FileList object listing the selected files of the form control.

Returns null if the control isn't a file control.

Can be set to a FileList object to change the selected files of the form control. For instance, as the result of a drag-and-drop operation.

input . valueAsDate [ = value ]

Returns a Date object representing the form control's value, if applicable; otherwise, returns null.

Can be set, to change the value.

Throws an "InvalidStateError" DOMException if the control isn't date- or time-based.

input . valueAsNumber [ = value ]

Returns a number representing the form control's value, if applicable; otherwise, returns NaN.

Can be set, to change the value. Setting this to NaN will set the underlying value to the empty string.

Throws an "InvalidStateError" DOMException if the control is neither date- or time-based nor numeric.

input . stepUp( [ n ] )

HTMLInputElement/stepUp

Firefox🔰 16+Safari5+Chrome5+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android🔰 16+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
input . stepDown( [ n ] )

HTMLInputElement/stepDown

Firefox🔰 16+Safari5+Chrome5+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android🔰 16+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Changes the form control's value by the value given in the step attribute, multiplied by n. The default value for n is 1.

Throws "InvalidStateError" DOMException if the control is neither date- or time-based nor numeric, or if the step attribute's value is "any".

input . list

Returns the datalist element indicated by the list attribute.

The value IDL attribute allows scripts to manipulate the value of an input element. The attribute is in one of the following modes, which define its behavior:

value

On getting, return the current value of the element.

On setting:

  1. Let oldValue be the element's value.

  2. Set the element's value to the new value.

  3. Set the element's dirty value flag to true.

  4. Invoke the value sanitization algorithm, if the element's type attribute's current state defines one.

  5. If the element's value (after applying the value sanitization algorithm) is different from oldValue, and the element has a text entry cursor position, move the text entry cursor position to the end of the text control, unselecting any selected text and resetting the selection direction to "none".

default

On getting, if the element has a value content attribute, return that attribute's value; otherwise, return the empty string.

On setting, set the value of the element's value content attribute to the new value.

default/on

On getting, if the element has a value content attribute, return that attribute's value; otherwise, return the string "on".

On setting, set the value of the element's value content attribute to the new value.

filename

On getting, return the string "C:\fakepath\" followed by the name of the first file in the list of selected files, if any, or the empty string if the list is empty.

On setting, if the new value is the empty string, empty the list of selected files; otherwise, throw an "InvalidStateError" DOMException.

This "fakepath" requirement is a sad accident of history. See the example in the File Upload state section for more information.

Since path components are not permitted in file names in the list of selected files, the "\fakepath\" cannot be mistaken for a path component.


The checked IDL attribute allows scripts to manipulate the checkedness of an input element. On getting, it must return the current checkedness of the element; and on setting, it must set the element's checkedness to the new value and set the element's dirty checkedness flag to true.


The files IDL attribute allows scripts to access the element's selected files.

On getting, if the IDL attribute applies, it must return a FileList object that represents the current selected files. The same object must be returned until the list of selected files changes. If the IDL attribute does not apply, then it must instead return null. [FILEAPI]

On setting, it must run these steps:

  1. If the IDL attribute does not apply or the given value is null, then return.

  2. Replace the element's selected files with the given value.


The valueAsDate IDL attribute represents the value of the element, interpreted as a date.

On getting, if the valueAsDate attribute does not apply, as defined for the input element's type attribute's current state, then return null. Otherwise, run the algorithm to convert a string to a Date object defined for that state to the element's value; if the algorithm returned a Date object, then return it, otherwise, return null.

On setting, if the valueAsDate attribute does not apply, as defined for the input element's type attribute's current state, then throw an "InvalidStateError" DOMException; otherwise, if the new value is not null and not a Date object throw a TypeError exception; otherwise if the new value is null or a Date object representing the NaN time value, then set the value of the element to the empty string; otherwise, run the algorithm to convert a Date object to a string, as defined for that state, on the new value, and set the value of the element to the resulting string.


The valueAsNumber IDL attribute represents the value of the element, interpreted as a number.

On getting, if the valueAsNumber attribute does not apply, as defined for the input element's type attribute's current state, then return a Not-a-Number (NaN) value. Otherwise, run the algorithm to convert a string to a number defined for that state to the element's value; if the algorithm returned a number, then return it, otherwise, return a Not-a-Number (NaN) value.

On setting, if the new value is infinite, then throw a TypeError exception. Otherwise, if the valueAsNumber attribute does not apply, as defined for the input element's type attribute's current state, then throw an "InvalidStateError" DOMException. Otherwise, if the new value is a Not-a-Number (NaN) value, then set the value of the element to the empty string. Otherwise, run the algorithm to convert a number to a string, as defined for that state, on the new value, and set the value of the element to the resulting string.


The stepDown(n) and stepUp(n) methods, when invoked, must run the following algorithm:

  1. If the stepDown() and stepUp() methods do not apply, as defined for the input element's type attribute's current state, then throw an "InvalidStateError" DOMException.

  2. If the element has no allowed value step, then throw an "InvalidStateError" DOMException.

  3. If the element has a minimum and a maximum and the minimum is greater than the maximum, then return.

  4. If the element has a minimum and a maximum and there is no value greater than or equal to the element's minimum and less than or equal to the element's maximum that, when subtracted from the step base, is an integral multiple of the allowed value step, then return.

  5. If applying the algorithm to convert a string to a number to the string given by the element's value does not result in an error, then let value be the result of that algorithm. Otherwise, let value be zero.

  6. Let valueBeforeStepping be value.

  7. If value subtracted from the step base is not an integral multiple of the allowed value step, then set value to the nearest value that, when subtracted from the step base, is an integral multiple of the allowed value step, and that is less than value if the method invoked was the stepDown() method, and more than value otherwise.

    Otherwise (value subtracted from the step base is an integral multiple of the allowed value step):

    1. Let n be the argument.

    2. Let delta be the allowed value step multiplied by n.

    3. If the method invoked was the stepDown() method, negate delta.

    4. Let value be the result of adding delta to value.

  8. If the element has a minimum, and value is less than that minimum, then set value to the smallest value that, when subtracted from the step base, is an integral multiple of the allowed value step, and that is more than or equal to minimum.

  9. If the element has a maximum, and value is greater than that maximum, then set value to the largest value that, when subtracted from the step base, is an integral multiple of the allowed value step, and that is less than or equal to maximum.

  10. If either the method invoked was the stepDown() method and value is greater than valueBeforeStepping, or the method invoked was the stepUp() method and value is less than valueBeforeStepping, then return.

    This ensures that invoking the stepUp() method on the input element in the following example does not change the value of that element:

    <input type=number value=1 max=0>
  11. Let value as string be the result of running the algorithm to convert a number to a string, as defined for the input element's type attribute's current state, on value.

  12. Set the value of the element to value as string.


The list IDL attribute must return the current suggestions source element, if any, or null otherwise.

4.10.5.5 通用事件行为

inputchange 事件 适用 时 (也就是除 按钮type 属性处于 Hidden 状态的控件之外的 input 控件), 这些事件的触发表示用户已经在与控件进行交互。 只要用户修改了控件的数据就会触发 input 事件 当编辑的值提交时,如果这个值对该控件有效或者该控件 失去了焦点 就会触发 change 事件。 所有情况下 input 事件都会在对应的 change 事件(如果有)前到达。

input 元素定义有 输入激活行为, 在上一章定义 type 属性的状态时,给出了 分发这些事件的规则(如果 适用 的话), (这适用于 type 属性处于 Checkbox 状态, Radio Button 状态,或者 File Upload 状态的所有 input 控件。)

对没有定义 输入激活行为input 元素, 如果这些事件 适用, 而且涉及交互式操作和显式的提交动作的用户交互,那么当用户改变元素的 时,用户代理必须 入队一个任务 来在 input 元素上 触发一个 名为 input 的事件,其 bubbles 属性初始化为 true,只要用户提交了改动,用户代理就必须 入队一个任务 来在 input 元素上 触发一个 名为 change 的事件,其 bubbles 属性初始化为 true。

一个涉及交互操作和提交动作的用户界面的例子是, 使用指点设备操作一个有滑块的 Range 控件。 当用户拖动控件的滑块时,只要位置发生改变就会触发 input 事件, 而 change 事件只会在用户放开滑块时触发, 这时指定的值才会提交。

对于没有定义 输入激活行为input 元素,如果这些事件 适用, 而且用户界面涉及一个显式的提交动作但没有间接的交互,那么只要用户给该元素的 value 提交了改动,用户代理就必须 入队一个任务 来首先在 input 元素上 触发一个 名为 input 的事件,其 bubbles 属性初始为 true,然后在 input 元素上 触发一个 名为 change 的事件,其 bubbles 属性初始为 true。

一个涉及提交动作的用户界面的例子是 Color 控件, 它只有一个打开色盘的按钮:如果 value 只会在对话框关闭时发生改变, 那么这就是显式的提交动作。另一方面,如果是交互式地操作控件来改变颜色,那就可能没有提交动作了。

另一个有提交动作的用户界面例子是允许用户文本输入和从下拉日历中选择的 Date 控件: 文本输入可能没有一个显式的提交步骤,但从下拉日历中选择并关闭下拉菜单就是一个提交动作。

对于没有定义 输入激活行为input 元素,如果这些事件 适用, 只要用户在没有显式的提交动作的情况下改变了元素的 , 用户代理就必须 入队一个任务 来在 input 元素上 触发一个 名为 input 的事件, 其 bubbles 属性初始为 true。 在控件 失去焦点 时,将会触发对应的 change 事件(如果有)。

用户改变元素的 的例子包括, 用户在文本控件总输入,粘贴新的值到控件中,或者在那个控件中撤销编辑。 有些用户交互不会改变值,例如在空的文本控件中按下删除键, 或粘贴替换的文本恰好和控件中的文本相同。

对于有滑块的 Range 控件, 如果用户已经 获得焦点 并正在用键盘与之交互, 这将是另一个不经过提交步骤改变元素 的例子。

在只触发一个 input 事件的 任务 中,用户代理可以在用户交互后等待适当的时间, 再 入队 任务; 例如,用户代理可以等待用户 100ms 不敲键,这样就能只在用户输入间歇时触发,而不是每次敲键都触发。

如果用户代理要为用户改变 input 元素的 (比如作为表单预填充特性的一部分), 用户代理必须 入队一个任务 来首先适当地更新 ,然后在这个 input 元素上 触发一个 名为 input 的事件, 其 bubbles 属性初始化为 true,然后在 input 元素上 触发一个 名为 change 的事件, 其 bubbles 属性初始化为 true。

这些事件不会因为脚本改变表单控件的值而触发。 (这是为了让用户操作下更新表单控件的值更容易,这样就不需要过滤掉脚本自行改的情况以避免死循环。)

这些 任务任务源用户交互任务源

4.10.6 The button element

Element/button

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLButtonElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Phrasing content.
Interactive content.
Listed, labelable, submittable, and autocapitalize-inheriting form-associated element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content, but there must be no interactive content descendant and no descendant with the tabindex attribute specified.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
disabled — Whether the form control is disabled
form — Associates the element with a form element
formactionURL to use for form submission
formenctype — Entry list encoding type to use for form submission
formmethod — Variant to use for form submission
formnovalidate — Bypass form control validation for form submission
formtargetBrowsing context for form submission
name — Name of the element to use for form submission and in the form.elements API
type — Type of button
value — Value to be used for form submission
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLButtonElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute USVString formAction;
  [CEReactions] attribute DOMString formEnctype;
  [CEReactions] attribute DOMString formMethod;
  [CEReactions] attribute boolean formNoValidate;
  [CEReactions] attribute DOMString formTarget;
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute DOMString value;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity(DOMString error);

  readonly attribute NodeList labels;
};

The button element represents a button labeled by its contents.

The element is a button.

The type attribute controls the behavior of the button when it is activated. It is an enumerated attribute. The following table lists the keywords and states for the attribute — the keywords in the left column map to the states in the cell in the second column on the same row as the keyword.

Keyword State Brief description
submit Submit Button Submits the form.
reset Reset Button Resets the form.
button Button Does nothing.

The missing value default and invalid value default are the Submit Button state.

If the type attribute is in the Submit Button state, the element is specifically a submit button.

Constraint validation: If the type attribute is in the Reset Button state or the Button state, the element is barred from constraint validation.

A button element's activation behavior is to run the steps defined in the following list for the current state of this element's type attribute, if this element is not disabled, and do nothing otherwise:

Submit Button

If the element has a form owner and the element's node document is fully active, the element must submit the form owner from the button element.

Reset Button

If the element has a form owner and the element's node document is fully active, the element must reset the form owner.

Button

Do nothing.

The form attribute is used to explicitly associate the button element with its form owner. The name attribute represents the element's name. The disabled attribute is used to make the control non-interactive and to prevent its value from being submitted. The formaction, formenctype, formmethod, formnovalidate, and formtarget attributes are attributes for form submission.

The formnovalidate attribute can be used to make submit buttons that do not trigger the constraint validation.

The formaction, formenctype, formmethod, formnovalidate, and formtarget must not be specified if the element's type attribute is not in the Submit Button state.

The value attribute gives the element's value for the purposes of form submission. The element's value is the value of the element's value attribute, if there is one, or the empty string otherwise.

A button (and its value) is only included in the form submission if the button itself was used to initiate the form submission.


The value IDL attribute must reflect the content attribute of the same name.

The type IDL attribute must reflect the content attribute of the same name, limited to only known values.

The willValidate, validity, and validationMessage IDL attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The labels IDL attribute provides a list of the element's labels. The disabled, form, and name IDL attributes are part of the element's forms API.

The following button is labeled "Show hint" and pops up a dialog box when activated:

<button type=button
        onclick="alert('This 15-20 minute piece was composed by George Gershwin.')">
 Show hint
</button>

4.10.7 The select element

Element/select

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLSelectElement

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera2+Edge79+
Edge (Legacy)12+Internet Explorer1+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
Categories:
Flow content.
Phrasing content.
Interactive content.
Listed, labelable, submittable, resettable, and autocapitalize-inheriting form-associated element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Zero or more option, optgroup, and script-supporting elements.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
autocomplete — Hint for form autofill feature
disabled — Whether the form control is disabled
form — Associates the element with a form element
multiple — Whether to allow multiple values
name — Name of the element to use for form submission and in the form.elements API
required — Whether the control is required for form submission
size — Size of the control
Accessibility considerations:
If the element has a multiple attribute or a size attribute with a value > 1: for authors; for implementers.
Otherwise: for authors; for implementers.
DOM interface:
[Exposed=Window]
interface HTMLSelectElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString autocomplete;
  [CEReactions] attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute boolean multiple;
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute boolean required;
  [CEReactions] attribute unsigned long size;

  readonly attribute DOMString type;

  [SameObject] readonly attribute HTMLOptionsCollection options;
  [CEReactions] attribute unsigned long length;
  getter Element? item(unsigned long index);
  HTMLOptionElement? namedItem(DOMString name);
  [CEReactions] undefined add((HTMLOptionElement or HTMLOptGroupElement) element, optional (HTMLElement or long)? before = null);
  [CEReactions] undefined remove(); // ChildNode overload
  [CEReactions] undefined remove(long index);
  [CEReactions] setter undefined (unsigned long index, HTMLOptionElement? option);

  [SameObject] readonly attribute HTMLCollection selectedOptions;
  attribute long selectedIndex;
  attribute DOMString value;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity(DOMString error);

  readonly attribute NodeList labels;
};

The select element represents a control for selecting amongst a set of options.

The multiple attribute is a boolean attribute. If the attribute is present, then the select element represents a control for selecting zero or more options from the list of options. If the attribute is absent, then the select element represents a control for selecting a single option from the list of options.

The size attribute gives the number of options to show to the user. The size attribute, if specified, must have a value that is a valid non-negative integer greater than zero.

The display size of a select element is the result of applying the rules for parsing non-negative integers to the value of element's size attribute, if it has one and parsing it is successful. If applying those rules to the attribute's value is not successful, or if the size attribute is absent, then the element's display size is 4 if the element's multiple content attribute is present, and 1 otherwise.

The list of options for a select element consists of all the option element children of the select element, and all the option element children of all the optgroup element children of the select element, in tree order.

The required attribute is a boolean attribute. When specified, the user will be required to select a value before submitting the form.

If a select element has a required attribute specified, does not have a multiple attribute specified, and has a display size of 1; and if the value of the first option element in the select element's list of options (if any) is the empty string, and that option element's parent node is the select element (and not an optgroup element), then that option is the select element's placeholder label option.

If a select element has a required attribute specified, does not have a multiple attribute specified, and has a display size of 1, then the select element must have a placeholder label option.

In practice, the requirement stated in the paragraph above can only apply when a select element does not have a size attribute with a value greater than 1.

Constraint validation: If the element has its required attribute specified, and either none of the option elements in the select element's list of options have their selectedness set to true, or the only option element in the select element's list of options with its selectedness set to true is the placeholder label option, then the element is suffering from being missing.

If the multiple attribute is absent, and the element is not disabled, then the user agent should allow the user to pick an option element in its list of options that is itself not disabled. Upon this option element being picked (either through a click, or through unfocusing the element after changing its value, or through a menu command, or through any other mechanism), and before the relevant user interaction event is queued (e.g. before the click event), the user agent must set the selectedness of the picked option element to true, set its dirtiness to true, and then send select update notifications.

If the multiple attribute is absent, whenever an option element in the select element's list of options has its selectedness set to true, and whenever an option element with its selectedness set to true is added to the select element's list of options, the user agent must set the selectedness of all the other option elements in its list of options to false.

If the multiple attribute is absent and the element's display size is greater than 1, then the user agent should also allow the user to request that the option whose selectedness is true, if any, be unselected. Upon this request being conveyed to the user agent, and before the relevant user interaction event is queued (e.g. before the click event), the user agent must set the selectedness of that option element to false, set its dirtiness to true, and then send select update notifications.

If nodes are inserted or nodes are removed causing the list of options to gain or lose one or more option elements, or if an option element in the list of options asks for a reset, then, if the select element's multiple attribute is absent, the user agent must run the first applicable set of steps from the following list:

If the select element's display size is 1, and no option elements in the select element's list of options have their selectedness set to true

Set the selectedness of the first option element in the list of options in tree order that is not disabled, if any, to true.

If two or more option elements in the select element's list of options have their selectedness set to true

Set the selectedness of all but the last option element with its selectedness set to true in the list of options in tree order to false.

If the multiple attribute is present, and the element is not disabled, then the user agent should allow the user to toggle the selectedness of the option elements in its list of options that are themselves not disabled. Upon such an element being toggled (either through a click, or through a menu command, or any other mechanism), and before the relevant user interaction event is queued (e.g. before a related click event), the selectedness of the option element must be changed (from true to false or false to true), the dirtiness of the element must be set to true, and the user agent must send select update notifications.

When the user agent is to send select update notifications, queue an element task on the user interaction task source given the select element to run these steps:

  1. Fire an event named input at the select element, with the bubbles and composed attributes initialized to true.

  2. Fire an event named change at the select element, with the bubbles attribute initialized to true.

The reset algorithm for select elements is to go through all the option elements in the element's list of options, set their selectedness to true if the option element has a selected attribute, and false otherwise, set their dirtiness to false, and then have the option elements ask for a reset.

The form attribute is used to explicitly associate the select element with its form owner. The name attribute represents the element's name. The disabled attribute is used to make the control non-interactive and to prevent its value from being submitted. The autocomplete attribute controls how the user agent provides autofill behavior.

A select element that is not disabled is mutable.

select . type

HTMLSelectElement/type

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera2+Edge79+
Edge (Legacy)12+Internet Explorer1+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Returns "select-multiple" if the element has a multiple attribute, and "select-one" otherwise.

select . options

HTMLSelectElement/options

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns an HTMLOptionsCollection of the list of options.

select . length [ = value ]

Returns the number of elements in the list of options.

When set to a smaller number, truncates the number of option elements in the select.

When set to a greater number, adds new blank option elements to the select.

element = select . item(index)

HTMLSelectElement/item

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
select[index]

Returns the item with index index from the list of options. The items are sorted in tree order.

element = select . namedItem(name)

HTMLSelectElement/namedItem

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the first item with ID or name name from the list of options.

Returns null if no element with that ID could be found.

select . add(element [, before ] )

HTMLSelectElement/add

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Inserts element before the node given by before.

The before argument can be a number, in which case element is inserted before the item with that number, or an element from the list of options, in which case element is inserted before that element.

If before is omitted, null, or a number out of range, then element will be added at the end of the list.

This method will throw a "HierarchyRequestError" DOMException if element is an ancestor of the element into which it is to be inserted.

select . selectedOptions

HTMLSelectElement/selectedOptions

Support in all current engines.

Firefox26+Safari6+Chrome19+
Opera9+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android26+Safari iOS6+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android10.1+

Returns an HTMLCollection of the list of options that are selected.

select . selectedIndex [ = value ]

HTMLSelectElement/selectedIndex

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the index of the first selected item, if any, or −1 if there is no selected item.

Can be set, to change the selection.

select . value [ = value ]

Returns the value of the first selected item, if any, or the empty string if there is no selected item.

Can be set, to change the selection.

The type IDL attribute, on getting, must return the string "select-one" if the multiple attribute is absent, and the string "select-multiple" if the multiple attribute is present.

The options IDL attribute must return an HTMLOptionsCollection rooted at the select node, whose filter matches the elements in the list of options.

The options collection is also mirrored on the HTMLSelectElement object. The supported property indices at any instant are the indices supported by the object returned by the options attribute at that instant.

The length IDL attribute must return the number of nodes represented by the options collection. On setting, it must act like the attribute of the same name on the options collection.

The item(index) method must return the value returned by the method of the same name on the options collection, when invoked with the same argument.

The namedItem(name) method must return the value returned by the method of the same name on the options collection, when invoked with the same argument.

When the user agent is to set the value of a new indexed property or set the value of an existing indexed property for a select element, it must instead run the corresponding algorithm on the select element's options collection.

Similarly, the add() method must act like its namesake method on that same options collection.

HTMLSelectElement/remove

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The remove() method must act like its namesake method on that same options collection when it has arguments, and like its namesake method on the ChildNode interface implemented by the HTMLSelectElement ancestor interface Element when it has no arguments.

The selectedOptions IDL attribute must return an HTMLCollection rooted at the select node, whose filter matches the elements in the list of options that have their selectedness set to true.

The selectedIndex IDL attribute, on getting, must return the index of the first option element in the list of options in tree order that has its selectedness set to true, if any. If there isn't one, then it must return −1.

On setting, the selectedIndex attribute must set the selectedness of all the option elements in the list of options to false, and then the option element in the list of options whose index is the given new value, if any, must have its selectedness set to true and its dirtiness set to true.

This can result in no element having a selectedness set to true even in the case of the select element having no multiple attribute and a display size of 1.

The value IDL attribute, on getting, must return the value of the first option element in the list of options in tree order that has its selectedness set to true, if any. If there isn't one, then it must return the empty string.

On setting, the value attribute must set the selectedness of all the option elements in the list of options to false, and then the first option element in the list of options, in tree order, whose value is equal to the given new value, if any, must have its selectedness set to true and its dirtiness set to true.

This can result in no element having a selectedness set to true even in the case of the select element having no multiple attribute and a display size of 1.

The multiple, required, and size IDL attributes must reflect the respective content attributes of the same name. The size IDL attribute has a default value of zero.

For historical reasons, the default value of the size IDL attribute does not return the actual size used, which, in the absence of the size content attribute, is either 1 or 4 depending on the presence of the multiple attribute.

The willValidate, validity, and validationMessage IDL attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The labels IDL attribute provides a list of the element's labels. The disabled, form, and name IDL attributes are part of the element's forms API.

The following example shows how a select element can be used to offer the user with a set of options from which the user can select a single option. The default option is preselected.

<p>
 <label for="unittype">Select unit type:</label>
 <select id="unittype" name="unittype">
  <option value="1"> Miner </option>
  <option value="2"> Puffer </option>
  <option value="3" selected> Snipey </option>
  <option value="4"> Max </option>
  <option value="5"> Firebot </option>
 </select>
</p>

When there is no default option, a placeholder can be used instead:

<select name="unittype" required>
 <option value=""> Select unit type </option>
 <option value="1"> Miner </option>
 <option value="2"> Puffer </option>
 <option value="3"> Snipey </option>
 <option value="4"> Max </option>
 <option value="5"> Firebot </option>
</select>

Here, the user is offered a set of options from which they can select any number. By default, all five options are selected.

<p>
 <label for="allowedunits">Select unit types to enable on this map:</label>
 <select id="allowedunits" name="allowedunits" multiple>
  <option value="1" selected> Miner </option>
  <option value="2" selected> Puffer </option>
  <option value="3" selected> Snipey </option>
  <option value="4" selected> Max </option>
  <option value="5" selected> Firebot </option>
 </select>
</p>

Sometimes, a user has to select one or more items. This example shows such an interface.

<label>
 Select the songs from that you would like on your Act II Mix Tape:
 <select multiple required name="act2">
  <option value="s1">It Sucks to Be Me (Reprise)
  <option value="s2">There is Life Outside Your Apartment
  <option value="s3">The More You Ruv Someone
  <option value="s4">Schadenfreude
  <option value="s5">I Wish I Could Go Back to College
  <option value="s6">The Money Song
  <option value="s7">School for Monsters
  <option value="s8">The Money Song (Reprise)
  <option value="s9">There's a Fine, Fine Line (Reprise)
  <option value="s10">What Do You Do With a B.A. in English? (Reprise)
  <option value="s11">For Now
 </select>
</label>

4.10.8 The datalist element

Element/datalist

Support in all current engines.

Firefox4+Safari12.1+Chrome20+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android🔰 79+Safari iOS12.2+Chrome Android33+WebView Android4.4.3+Samsung Internet2.0+Opera Android20+

HTMLDataListElement

Support in all current engines.

Firefox4+Safari12.1+Chrome20+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS12.2+Chrome Android25+WebView Android4.4.3+Samsung Internet1.5+Opera Android12.1+
Categories:
Flow content.
Phrasing content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Either: phrasing content.
Or: Zero or more option and script-supporting elements.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLDataListElement : HTMLElement {
  [HTMLConstructor] constructor();

  [SameObject] readonly attribute HTMLCollection options;
};

The datalist element represents a set of option elements that represent predefined options for other controls. In the rendering, the datalist element represents nothing and it, along with its children, should be hidden.

The datalist element can be used in two ways. In the simplest case, the datalist element has just option element children.

<label>
 Animal:
 <input name=animal list=animals>
 <datalist id=animals>
  <option value="Cat">
  <option value="Dog">
 </datalist>
</label>

In the more elaborate case, the datalist element can be given contents that are to be displayed for down-level clients that don't support datalist. In this case, the option elements are provided inside a select element inside the datalist element.

<label>
 Animal:
 <input name=animal list=animals>
</label>
<datalist id=animals>
 <label>
  or select from the list:
  <select name=animal>
   <option value="">
   <option>Cat
   <option>Dog
  </select>
 </label>
</datalist>

The datalist element is hooked up to an input element using the list attribute on the input element.

Each option element that is a descendant of the datalist element, that is not disabled, and whose value is a string that isn't the empty string, represents a suggestion. Each suggestion has a value and a label.

datalist . options

Returns an HTMLCollection of the option elements of the datalist element.

The options IDL attribute must return an HTMLCollection rooted at the datalist node, whose filter matches option elements.

Constraint validation: If an element has a datalist element ancestor, it is barred from constraint validation.

4.10.9 The optgroup element

Element/optgroup

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLOptGroupElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
None.
Contexts in which this element can be used:
As a child of a select element.
Content model:
Zero or more option and script-supporting elements.
text/html 中的标签省略
An optgroup element's end tag can be omitted if the optgroup element is immediately followed by another optgroup element, or if there is no more content in the parent element.
Content attributes:
Global attributes
disabled — Whether the form control is disabled
label — User-visible label
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLOptGroupElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean disabled;
  [CEReactions] attribute DOMString label;
};

The optgroup element represents a group of option elements with a common label.

The element's group of option elements consists of the option elements that are children of the optgroup element.

When showing option elements in select elements, user agents should show the option elements of such groups as being related to each other and separate from other option elements.

The disabled attribute is a boolean attribute and can be used to disable a group of option elements together.

The label attribute must be specified. Its value gives the name of the group, for the purposes of the user interface. User agents should use this attribute's value when labeling the group of option elements in a select element.

The disabled and label attributes must reflect the respective content attributes of the same name.

There is no way to select an optgroup element. Only option elements can be selected. An optgroup element merely provides a label for a group of option elements.

The following snippet shows how a set of lessons from three courses could be offered in a select drop-down widget:

<form action="courseselector.dll" method="get">
 <p>Which course would you like to watch today?
 <p><label>Course:
  <select name="c">
   <optgroup label="8.01 Physics I: Classical Mechanics">
    <option value="8.01.1">Lecture 01: Powers of Ten
    <option value="8.01.2">Lecture 02: 1D Kinematics
    <option value="8.01.3">Lecture 03: Vectors
   <optgroup label="8.02 Electricity and Magnestism">
    <option value="8.02.1">Lecture 01: What holds our world together?
    <option value="8.02.2">Lecture 02: Electric Field
    <option value="8.02.3">Lecture 03: Electric Flux
   <optgroup label="8.03 Physics III: Vibrations and Waves">
    <option value="8.03.1">Lecture 01: Periodic Phenomenon
    <option value="8.03.2">Lecture 02: Beats
    <option value="8.03.3">Lecture 03: Forced Oscillations with Damping
  </select>
 </label>
 <p><input type=submit value="▶ Play">
</form>

4.10.10 The option element

Element/option

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLOptionElement

Support in all current engines.

Firefox1+Safari1.2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
None.
Contexts in which this element can be used:
As a child of a select element.
As a child of a datalist element.
As a child of an optgroup element.
Content model:
If the element has a label attribute and a value attribute: Nothing.
If the element has a label attribute but no value attribute: Text.
If the element has no label attribute and is not a child of a datalist element: Text that is not inter-element whitespace.
If the element has no label attribute and is a child of a datalist element: Text.
text/html 中的标签省略
An option element's end tag can be omitted if the option element is immediately followed by another option element, or if it is immediately followed by an optgroup element, or if there is no more content in the parent element.
Content attributes:
Global attributes
disabled — Whether the form control is disabled
label — User-visible label
selected — Whether the option is selected by default
value — Value to be used for form submission
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window,
 LegacyFactoryFunction=Option(optional DOMString text = "", optional DOMString value, optional boolean defaultSelected = false, optional boolean selected = false)]
interface HTMLOptionElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute DOMString label;
  [CEReactions] attribute boolean defaultSelected;
  attribute boolean selected;
  [CEReactions] attribute DOMString value;

  [CEReactions] attribute DOMString text;
  readonly attribute long index;
};

The option element represents an option in a select element or as part of a list of suggestions in a datalist element.

In certain circumstances described in the definition of the select element, an option element can be a select element's placeholder label option. A placeholder label option does not represent an actual option, but instead represents a label for the select control.

The disabled attribute is a boolean attribute. An option element is disabled if its disabled attribute is present or if it is a child of an optgroup element whose disabled attribute is present.

An option element that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.

The label attribute provides a label for element. The label of an option element is the value of the label content attribute, if there is one and its value is not the empty string, or, otherwise, the value of the element's text IDL attribute.

The label content attribute, if specified, must not be empty.

The value attribute provides a value for element. The value of an option element is the value of the value content attribute, if there is one, or, if there is not, the value of the element's text IDL attribute.

The selected attribute is a boolean attribute. It represents the default selectedness of the element.

The dirtiness of an option element is a boolean state, initially false. It controls whether adding or removing the selected content attribute has any effect.

The selectedness of an option element is a boolean state, initially false. Except where otherwise specified, when the element is created, its selectedness must be set to true if the element has a selected attribute. Whenever an option element's selected attribute is added, if its dirtiness is false, its selectedness must be set to true. Whenever an option element's selected attribute is removed, if its dirtiness is false, its selectedness must be set to false.

The Option() constructor, when called with three or fewer arguments, overrides the initial state of the selectedness state to always be false even if the third argument is true (implying that a selected attribute is to be set). The fourth argument can be used to explicitly set the initial selectedness state when using the constructor.

A select element whose multiple attribute is not specified must not have more than one descendant option element with its selected attribute set.

An option element's index is the number of option elements that are in the same list of options but that come before it in tree order. If the option element is not in a list of options, then the option element's index is zero.

option . selected

Returns true if the element is selected, and false otherwise.

Can be set, to override the current state of the element.

option . index

Returns the index of the element in its select element's options list.

option . form

Returns the element's form element, if any, or null otherwise.

option . text

Same as textContent, except that spaces are collapsed and script elements are skipped.

option = new Option( [ text [, value [, defaultSelected [, selected ] ] ] ] )

HTMLOptionElement/Option

Support in all current engines.

Firefox1+Safari1.2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns a new option element.

The text argument sets the contents of the element.

The value argument sets the value attribute.

The defaultSelected argument sets the selected attribute.

The selected argument sets whether or not the element is selected. If it is omitted, even if the defaultSelected argument is true, the element is not selected.

The disabled IDL attribute must reflect the content attribute of the same name. The defaultSelected IDL attribute must reflect the selected content attribute.

The label IDL attribute, on getting, if there is a label content attribute, must return that attribute's value; otherwise, it must return the element's label. On setting, the element's label content attribute must be set to the new value.

The value IDL attribute, on getting, must return the element's value. On setting, the element's value content attribute must be set to the new value.

The selected IDL attribute, on getting, must return true if the element's selectedness is true, and false otherwise. On setting, it must set the element's selectedness to the new value, set its dirtiness to true, and then cause the element to ask for a reset.

The index IDL attribute must return the element's index.

The text IDL attribute, on getting, must return the result of stripping and collapsing ASCII whitespace from the concatenation of data of all the Text node descendants of the option element, in tree order, excluding any that are descendants of descendants of the option element that are themselves script or SVG script elements.

The text attribute's setter must string replace all with the given value within this element.

The form IDL attribute's behavior depends on whether the option element is in a select element or not. If the option has a select element as its parent, or has an optgroup element as its parent and that optgroup element has a select element as its parent, then the form IDL attribute must return the same value as the form IDL attribute on that select element. Otherwise, it must return null.

A legacy factory function is provided for creating HTMLOptionElement objects (in addition to the factory methods from DOM such as createElement()): Option(text, value, defaultSelected, selected). When invoked, the legacy factory function must perform the following steps:

  1. Let document be the current global object's associated Document.

  2. Let option be the result of creating an element given document, option, and the HTML namespace.

  3. If text is not the empty string, then append to option a new Text node whose data is text.

  4. If value is given, then set an attribute value for option using "value" and value.

  5. If defaultSelected is true, then set an attribute value for option using "selected" and the empty string.

  6. If selected is true, then set option's selectedness to true; otherwise set its selectedness to false (even if defaultSelected is true).

  7. Return option.

4.10.11 The textarea element

Element/textarea

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLTextAreaElement

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
Categories:
Flow content.
Phrasing content.
Interactive content.
Listed, labelable, submittable, resettable, and autocapitalize-inheriting form-associated element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Text.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
autocomplete — Hint for form autofill feature
cols — Maximum number of characters per line
dirname — Name of form control to use for sending the element's directionality in form submission
disabled — Whether the form control is disabled
form — Associates the element with a form element
maxlength — Maximum length of value
minlength — Minimum length of value
name — Name of the element to use for form submission and in the form.elements API
placeholder — User-visible label to be placed within the form control
readonly — Whether to allow the value to be edited by the user
required — Whether the control is required for form submission
rows — Number of lines to show
wrap — How the value of the form control is to be wrapped for form submission
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLTextAreaElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString autocomplete;
  [CEReactions] attribute unsigned long cols;
  [CEReactions] attribute DOMString dirName;
  [CEReactions] attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute long maxLength;
  [CEReactions] attribute long minLength;
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString placeholder;
  [CEReactions] attribute boolean readOnly;
  [CEReactions] attribute boolean required;
  [CEReactions] attribute unsigned long rows;
  [CEReactions] attribute DOMString wrap;

  readonly attribute DOMString type;
  [CEReactions] attribute DOMString defaultValue;
  attribute [LegacyNullToEmptyString] DOMString value;
  readonly attribute unsigned long textLength;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity(DOMString error);

  readonly attribute NodeList labels;

  undefined select();
  attribute unsigned long selectionStart;
  attribute unsigned long selectionEnd;
  attribute DOMString selectionDirection;
  undefined setRangeText(DOMString replacement);
  undefined setRangeText(DOMString replacement, unsigned long start, unsigned long end, optional SelectionMode selectionMode = "preserve");
  undefined setSelectionRange(unsigned long start, unsigned long end, optional DOMString direction);
};

The textarea element represents a multiline plain text edit control for the element's raw value. The contents of the control represent the control's default value.

The raw value of a textarea control must be initially the empty string.

This element has rendering requirements involving the bidirectional algorithm.

The readonly attribute is a boolean attribute used to control whether the text can be edited by the user or not.

In this example, a text control is marked read-only because it represents a read-only file:

Filename: <code>/etc/bash.bashrc</code>
<textarea name="buffer" readonly>
# System-wide .bashrc file for interactive bash(1) shells.

# To enable the settings / commands in this file for login shells as well,
# this file has to be sourced in /etc/profile.

# If not running interactively, don't do anything
[ -z "$PS1" ] &amp;&amp; return

...</textarea>

Constraint validation: If the readonly attribute is specified on a textarea element, the element is barred from constraint validation.

A textarea element is mutable if it is neither disabled nor has a readonly attribute specified.

When a textarea is mutable, its raw value should be editable by the user: the user agent should allow the user to edit, insert, and remove text, and to insert and remove line breaks in the form of U+000A LINE FEED (LF) characters. Any time the user causes the element's raw value to change, the user agent must queue an element task on the user interaction task source given the textarea element to fire an event named input at the textarea element, with the bubbles and composed attributes initialized to true. User agents may wait for a suitable break in the user's interaction before queuing the task; for example, a user agent could wait for the user to have not hit a key for 100ms, so as to only fire the event when the user pauses, instead of continuously for each keystroke.

A textarea element's dirty value flag must be set to true whenever the user interacts with the control in a way that changes the raw value.

The cloning steps for textarea elements must propagate the raw value and dirty value flag from the node being cloned to the copy.

The children changed steps for textarea elements must, if the element's dirty value flag is false, set the element's raw value to its child text content.

The reset algorithm for textarea elements is to set the dirty value flag back to false, and set the raw value of element to its child text content.

When a textarea element is popped off the stack of open elements of an HTML parser or XML parser, then the user agent must invoke the element's reset algorithm.

If the element is mutable, the user agent should allow the user to change the writing direction of the element, setting it either to a left-to-right writing direction or a right-to-left writing direction. If the user does so, the user agent must then run the following steps:

  1. Set the element's dir attribute to "ltr" if the user selected a left-to-right writing direction, and "rtl" if the user selected a right-to-left writing direction.

  2. Queue an element task on the user interaction task source given the textarea element to fire an event named input at the textarea element, with the bubbles and composed attributes initialized to true.

The cols attribute specifies the expected maximum number of characters per line. If the cols attribute is specified, its value must be a valid non-negative integer greater than zero. If applying the rules for parsing non-negative integers to the attribute's value results in a number greater than zero, then the element's character width is that value; otherwise, it is 20.

The user agent may use the textarea element's character width as a hint to the user as to how many characters the server prefers per line (e.g. for visual user agents by making the width of the control be that many characters). In visual renderings, the user agent should wrap the user's input in the rendering so that each line is no wider than this number of characters.

The rows attribute specifies the number of lines to show. If the rows attribute is specified, its value must be a valid non-negative integer greater than zero. If applying the rules for parsing non-negative integers to the attribute's value results in a number greater than zero, then the element's character height is that value; otherwise, it is 2.

Visual user agents should set the height of the control to the number of lines given by character height.

The wrap attribute is an enumerated attribute with two keywords and states: the soft keyword which maps to the Soft state, and the hard keyword which maps to the Hard state. The missing value default and invalid value default are the Soft state.

The Soft state indicates that the text in the textarea is not to be wrapped when it is submitted (though it can still be wrapped in the rendering).

The Hard state indicates that the text in the textarea is to have newlines added by the user agent so that the text is wrapped when it is submitted.

If the element's wrap attribute is in the Hard state, the cols attribute must be specified.

For historical reasons, the element's value is normalized in three different ways for three different purposes. The raw value is the value as it was originally set. It is not normalized. The API value is the value used in the value IDL attribute, textLength IDL attribute, and by the maxlength and minlength content attributes. It is normalized so that line breaks use U+000A LINE FEED (LF) characters. Finally, there is the value, as used in form submission and other processing models in this specification. It is normalized so that line breaks use U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pairs, and in addition, if necessary given the element's wrap attribute, additional line breaks are inserted to wrap the text at the given width.

The algorithm for obtaining the element's API value is to return the element's raw value, with newlines normalized.

The element's value is defined to be the element's raw value with the textarea wrapping transformation applied. The textarea wrapping transformation is the following algorithm, as applied to a string:

  1. Replace every occurrence of a U+000D CARRIAGE RETURN (CR) character not followed by a U+000A LINE FEED (LF) character, and every occurrence of a U+000A LINE FEED (LF) character not preceded by a U+000D CARRIAGE RETURN (CR) character, by a two-character string consisting of a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair.

  2. If the element's wrap attribute is in the Hard state, insert U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pairs into the string using an implementation-defined algorithm so that each line has no more than character width characters. For the purposes of this requirement, lines are delimited by the start of the string, the end of the string, and U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pairs.

The maxlength attribute is a form control maxlength attribute.

If the textarea element has a maximum allowed value length, then the element's children must be such that the length of the value of the element's descendant text content with newlines normalized is equal to or less than the element's maximum allowed value length.

The minlength attribute is a form control minlength attribute.

The required attribute is a boolean attribute. When specified, the user will be required to enter a value before submitting the form.

Constraint validation: If the element has its required attribute specified, and the element is mutable, and the element's value is the empty string, then the element is suffering from being missing.

The placeholder attribute represents a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. A hint could be a sample value or a brief description of the expected format.

The placeholder attribute should not be used as an alternative to a label. For a longer hint or other advisory text, the title attribute is more appropriate.

These mechanisms are very similar but subtly different: the hint given by the control's label is shown at all times; the short hint given in the placeholder attribute is shown before the user enters a value; and the hint in the title attribute is shown when the user requests further help.

User agents should present this hint to the user when the element's value is the empty string and the control is not focused (e.g. by displaying it inside a blank unfocused control). All U+000D CARRIAGE RETURN U+000A LINE FEED character pairs (CRLF) in the hint, as well as all other U+000D CARRIAGE RETURN (CR) and U+000A LINE FEED (LF) characters in the hint, must be treated as line breaks when rendering the hint.

If a user agent normally doesn't show this hint to the user when the control is focused, then the user agent should nonetheless show the hint for the control if it was focused as a result of the autofocus attribute, since in that case the user will not have had an opportunity to examine the control before focusing it.

The name attribute represents the element's name. The dirname attribute controls how the element's directionality is submitted. The disabled attribute is used to make the control non-interactive and to prevent its value from being submitted. The form attribute is used to explicitly associate the textarea element with its form owner. The autocomplete attribute controls how the user agent provides autofill behavior.

textarea . type

Returns the string "textarea".

textarea . value

Returns the current value of the element.

Can be set, to change the value.

The cols, placeholder, required, rows, and wrap IDL attributes must reflect the respective content attributes of the same name. The cols and rows attributes are limited to only non-negative numbers greater than zero with fallback. The cols IDL attribute's default value is 20. The rows IDL attribute's default value is 2. The dirName IDL attribute must reflect the dirname content attribute. The maxLength IDL attribute must reflect the maxlength content attribute, limited to only non-negative numbers. The minLength IDL attribute must reflect the minlength content attribute, limited to only non-negative numbers. The readOnly IDL attribute must reflect the readonly content attribute.

The type IDL attribute must return the value "textarea".

The defaultValue attribute's getter must return the element's child text content.

The defaultValue attribute's setter must string replace all with the given value within this element.

The value IDL attribute must, on getting, return the element's API value. On setting, it must perform the following steps:

  1. Let oldAPIValue be this element's API value.

  2. Set this element's raw value to the new value.

  3. Set this element's dirty value flag to true.

  4. If the new API value is different from oldAPIValue, then move the text entry cursor position to the end of the text control, unselecting any selected text and resetting the selection direction to "none".

The textLength IDL attribute must return the length of the element's API value.

The willValidate, validity, and validationMessage IDL attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The labels IDL attribute provides a list of the element's labels. The select(), selectionStart, selectionEnd, selectionDirection, setRangeText(), and setSelectionRange() methods and IDL attributes expose the element's text selection. The disabled, form, and name IDL attributes are part of the element's forms API.

Here is an example of a textarea being used for unrestricted free-form text input in a form:

<p>If you have any comments, please let us know: <textarea cols=80 name=comments></textarea></p>

To specify a maximum length for the comments, one can use the maxlength attribute:

<p>If you have any short comments, please let us know: <textarea cols=80 name=comments maxlength=200></textarea></p>

To give a default value, text can be included inside the element:

<p>If you have any comments, please let us know: <textarea cols=80 name=comments>You rock!</textarea></p>

You can also give a minimum length. Here, a letter needs to be filled out by the user; a template (which is shorter than the minimum length) is provided, but is insufficient to submit the form:

<textarea required minlength="500">Dear Madam Speaker,

Regarding your letter dated ...

...

Yours Sincerely,

...</textarea>

A placeholder can be given as well, to suggest the basic form to the user, without providing an explicit template:

<textarea placeholder="Dear Francine,

They closed the parks this week, so we won't be able to
meet your there. Should we just have dinner?

Love,
Daddy"></textarea>

To have the browser submit the directionality of the element along with the value, the dirname attribute can be specified:

<p>If you have any comments, please let us know (you may use either English or Hebrew for your comments):
<textarea cols=80 name=comments dirname=comments.dir></textarea></p>

4.10.12 The output element

Element/output

Support in all current engines.

Firefox4+Safari7+Chrome10+
Opera11+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android?

HTMLOutputElement

Support in all current engines.

Firefox4+Safari5.1+Chrome9+
Opera12.1+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Phrasing content.
Listed, labelable, resettable, and autocapitalize-inheriting form-associated element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
for — Specifies controls from which the output was calculated
form — Associates the element with a form element
name — Name of the element to use in the form.elements API.
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLOutputElement : HTMLElement {
  [HTMLConstructor] constructor();

  [SameObject, PutForwards=value] readonly attribute DOMTokenList htmlFor;
  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute DOMString name;

  readonly attribute DOMString type;
  [CEReactions] attribute DOMString defaultValue;
  [CEReactions] attribute DOMString value;

  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity(DOMString error);

  readonly attribute NodeList labels;
};

The output element represents the result of a calculation performed by the application, or the result of a user action.

This element can be contrasted with the samp element, which is the appropriate element for quoting the output of other programs run previously.

The for content attribute allows an explicit relationship to be made between the result of a calculation and the elements that represent the values that went into the calculation or that otherwise influenced the calculation. The for attribute, if specified, must contain a string consisting of an unordered set of unique space-separated tokens, none of which are identical to another token and each of which must have the value of an ID of an element in the same tree.

The form attribute is used to explicitly associate the output element with its form owner. The name attribute represents the element's name. The output element is associated with a form so that it can be easily referenced from the event handlers of form controls; the element's value itself is not submitted when the form is submitted.

The element has a default value override (null or a string). Initially it must be null.

The element's default value is determined by the following steps:

  1. If this element's default value override is non-null, then return it.

  2. Return this element's descendant text content.

The reset algorithm for output elements is to run these steps:

  1. String replace all with this element's default value within this element.

  2. Set this element's default value override to null.

output . value [ = value ]

Returns the element's current value.

Can be set, to change the value.

output . defaultValue [ = value ]

Returns the element's current default value.

Can be set, to change the default value.

output . type

Returns the string "output".

The value attribute's getter must return this element's descendant text content.

The value attribute's setter must run these steps:

  1. Set this element's default value override to its default value.

  2. String replace all with the given value within this element.

The defaultValue attribute's getter must return the result of running this element's default value.

The defaultValue attribute's setter must run these steps:

  1. If this element's default value override is null, then string replace all with the given value within this element and return.

  2. Set this element's default value override to the given value.

The type attribute's getter must return "output".

The htmlFor IDL attribute must reflect the for content attribute.

The willValidate, validity, and validationMessage IDL attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The labels IDL attribute provides a list of the element's labels. The form and name IDL attributes are part of the element's forms API.

A simple calculator could use output for its display of calculated results:

<form onsubmit="return false" oninput="o.value = a.valueAsNumber + b.valueAsNumber">
 <input id=a type=number step=any> +
 <input id=b type=number step=any> =
 <output id=o for="a b"></output>
</form>

In this example, an output element is used to report the results of a calculation performed by a remote server, as they come in:

<output id="result"></output>
<script>
 var primeSource = new WebSocket('ws://primes.example.net/');
 primeSource.onmessage = function (event) {
   document.getElementById('result').value = event.data;
 }
</script>

4.10.13 The progress element

Element/progress

Support in all current engines.

Firefox6+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android6+Safari iOS7+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android11+

HTMLProgressElement

Support in all current engines.

Firefox6+Safari6+Chrome6+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android6+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Phrasing content.
Labelable element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content, but there must be no progress element descendants.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
value — Current value of the element
max — Upper bound of range
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLProgressElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute double value;
  [CEReactions] attribute double max;
  readonly attribute double position;
  readonly attribute NodeList labels;
};

The progress element represents the completion progress of a task. The progress is either indeterminate, indicating that progress is being made but that it is not clear how much more work remains to be done before the task is complete (e.g. because the task is waiting for a remote host to respond), or the progress is a number in the range zero to a maximum, giving the fraction of work that has so far been completed.

There are two attributes that determine the current task completion represented by the element. The value attribute specifies how much of the task has been completed, and the max attribute specifies how much work the task requires in total. The units are arbitrary and not specified.

To make a determinate progress bar, add a value attribute with the current progress (either a number from 0.0 to 1.0, or, if the max attribute is specified, a number from 0 to the value of the max attribute). To make an indeterminate progress bar, remove the value attribute.

Authors are encouraged to also include the current value and the maximum value inline as text inside the element, so that the progress is made available to users of legacy user agents.

Here is a snippet of a web application that shows the progress of some automated task:

<section>
 <h2>Task Progress</h2>
 <p>Progress: <progress id="p" max=100><span>0</span>%</progress></p>
 <script>
  var progressBar = document.getElementById('p');
  function updateProgress(newValue) {
    progressBar.value = newValue;
    progressBar.getElementsByTagName('span')[0].textContent = newValue;
  }
 </script>
</section>

(The updateProgress() method in this example would be called by some other code on the page to update the actual progress bar as the task progressed.)

The value and max attributes, when present, must have values that are valid floating-point numbers. The value attribute, if present, must have a value equal to or greater than zero, and less than or equal to the value of the max attribute, if present, or 1.0, otherwise. The max attribute, if present, must have a value greater than zero.

The progress element is the wrong element to use for something that is just a gauge, as opposed to task progress. For instance, indicating disk space usage using progress would be inappropriate. Instead, the meter element is available for such use cases.

User agent requirements: If the value attribute is omitted, then the progress bar is an indeterminate progress bar. Otherwise, it is a determinate progress bar.

If the progress bar is a determinate progress bar and the element has a max attribute, the user agent must parse the max attribute's value according to the rules for parsing floating-point number values. If this does not result in an error, and if the parsed value is greater than zero, then the maximum value of the progress bar is that value. Otherwise, if the element has no max attribute, or if it has one but parsing it resulted in an error, or if the parsed value was less than or equal to zero, then the maximum value of the progress bar is 1.0.

If the progress bar is a determinate progress bar, user agents must parse the value attribute's value according to the rules for parsing floating-point number values. If this does not result in an error and the parsed value is greater than zero, then the value of the progress bar is that parsed value. Otherwise, if parsing the value attribute's value resulted in an error or a number less than or equal to zero, then the value of the progress bar is zero.

If the progress bar is a determinate progress bar, then the current value is the maximum value, if value is greater than the maximum value, and value otherwise.

UA requirements for showing the progress bar: When representing a progress element to the user, the UA should indicate whether it is a determinate or indeterminate progress bar, and in the former case, should indicate the relative position of the current value relative to the maximum value.

progress . position

For a determinate progress bar (one with known current and maximum values), returns the result of dividing the current value by the maximum value.

For an indeterminate progress bar, returns −1.

If the progress bar is an indeterminate progress bar, then the position IDL attribute must return −1. Otherwise, it must return the result of dividing the current value by the maximum value.

If the progress bar is an indeterminate progress bar, then the value IDL attribute, on getting, must return 0. Otherwise, it must return the current value. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the value content attribute must be set to that string.

Setting the value IDL attribute to itself when the corresponding content attribute is absent would change the progress bar from an indeterminate progress bar to a determinate progress bar with no progress.

The max IDL attribute must reflect the content attribute of the same name, limited to numbers greater than zero. The default value for max is 1.0.

The labels IDL attribute provides a list of the element's labels.

4.10.14 The meter element

Element/meter

Support in all current engines.

Firefox16+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android16+Safari iOS10.3+Chrome Android18+WebView AndroidNoSamsung Internet1.0+Opera Android11+

HTMLMeterElement

Support in all current engines.

Firefox16+Safari6+Chrome6+
Opera11+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android16+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
Categories:
Flow content.
Phrasing content.
Labelable element.
Palpable content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Phrasing content, but there must be no meter element descendants.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
value — Current value of the element
min — Lower bound of range
max — Upper bound of range
low — High limit of low range
high — Low limit of high range
optimum — Optimum value in gauge
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLMeterElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute double value;
  [CEReactions] attribute double min;
  [CEReactions] attribute double max;
  [CEReactions] attribute double low;
  [CEReactions] attribute double high;
  [CEReactions] attribute double optimum;
  readonly attribute NodeList labels;
};

The meter element represents a scalar measurement within a known range, or a fractional value; for example disk usage, the relevance of a query result, or the fraction of a voting population to have selected a particular candidate.

This is also known as a gauge.

The meter element should not be used to indicate progress (as in a progress bar). For that role, HTML provides a separate progress element.

The meter element also does not represent a scalar value of arbitrary range — for example, it would be wrong to use this to report a weight, or height, unless there is a known maximum value.

There are six attributes that determine the semantics of the gauge represented by the element.

The min attribute specifies the lower bound of the range, and the max attribute specifies the upper bound. The value attribute specifies the value to have the gauge indicate as the "measured" value.

The other three attributes can be used to segment the gauge's range into "low", "medium", and "high" parts, and to indicate which part of the gauge is the "optimum" part. The low attribute specifies the range that is considered to be the "low" part, and the high attribute specifies the range that is considered to be the "high" part. The optimum attribute gives the position that is "optimum"; if that is higher than the "high" value then this indicates that the higher the value, the better; if it's lower than the "low" mark then it indicates that lower values are better, and naturally if it is in between then it indicates that neither high nor low values are good.

Authoring requirements: The value attribute must be specified. The value, min, low, high, max, and optimum attributes, when present, must have values that are valid floating-point numbers.

In addition, the attributes' values are further constrained:

Let value be the value attribute's number.

If the min attribute is specified, then let minimum be that attribute's value; otherwise, let it be zero.

If the max attribute is specified, then let maximum be that attribute's value; otherwise, let it be 1.0.

The following inequalities must hold, as applicable:

If no minimum or maximum is specified, then the range is assumed to be 0..1, and the value thus has to be within that range.

Authors are encouraged to include a textual representation of the gauge's state in the element's contents, for users of user agents that do not support the meter element.

When used with microdata, the meter element's value attribute provides the element's machine-readable value.

The following examples show three gauges that would all be three-quarters full:

Storage space usage: <meter value=6 max=8>6 blocks used (out of 8 total)</meter>
Voter turnout: <meter value=0.75><img alt="75%" src="graph75.png"></meter>
Tickets sold: <meter min="0" max="100" value="75"></meter>

The following example is incorrect use of the element, because it doesn't give a range (and since the default maximum is 1, both of the gauges would end up looking maxed out):

<p>The grapefruit pie had a radius of <meter value=12>12cm</meter>
and a height of <meter value=2>2cm</meter>.</p> <!-- BAD! -->

Instead, one would either not include the meter element, or use the meter element with a defined range to give the dimensions in context compared to other pies:

<p>The grapefruit pie had a radius of 12cm and a height of
2cm.</p>
<dl>
 <dt>Radius: <dd> <meter min=0 max=20 value=12>12cm</meter>
 <dt>Height: <dd> <meter min=0 max=10 value=2>2cm</meter>
</dl>

There is no explicit way to specify units in the meter element, but the units may be specified in the title attribute in free-form text.

The example above could be extended to mention the units:

<dl>
 <dt>Radius: <dd> <meter min=0 max=20 value=12 title="centimeters">12cm</meter>
 <dt>Height: <dd> <meter min=0 max=10 value=2 title="centimeters">2cm</meter>
</dl>

User agent requirements: User agents must parse the min, max, value, low, high, and optimum attributes using the rules for parsing floating-point number values.

User agents must then use all these numbers to obtain values for six points on the gauge, as follows. (The order in which these are evaluated is important, as some of the values refer to earlier ones.)

The minimum value

If the min attribute is specified and a value could be parsed out of it, then the minimum value is that value. Otherwise, the minimum value is zero.

The maximum value

If the max attribute is specified and a value could be parsed out of it, then the candidate maximum value is that value. Otherwise, the candidate maximum value is 1.0.

If the candidate maximum value is greater than or equal to the minimum value, then the maximum value is the candidate maximum value. Otherwise, the maximum value is the same as the minimum value.

The actual value

If the value attribute is specified and a value could be parsed out of it, then that value is the candidate actual value. Otherwise, the candidate actual value is zero.

If the candidate actual value is less than the minimum value, then the actual value is the minimum value.

Otherwise, if the candidate actual value is greater than the maximum value, then the actual value is the maximum value.

Otherwise, the actual value is the candidate actual value.

The low boundary

If the low attribute is specified and a value could be parsed out of it, then the candidate low boundary is that value. Otherwise, the candidate low boundary is the same as the minimum value.

If the candidate low boundary is less than the minimum value, then the low boundary is the minimum value.

Otherwise, if the candidate low boundary is greater than the maximum value, then the low boundary is the maximum value.

Otherwise, the low boundary is the candidate low boundary.

The high boundary

If the high attribute is specified and a value could be parsed out of it, then the candidate high boundary is that value. Otherwise, the candidate high boundary is the same as the maximum value.

If the candidate high boundary is less than the low boundary, then the high boundary is the low boundary.

Otherwise, if the candidate high boundary is greater than the maximum value, then the high boundary is the maximum value.

Otherwise, the high boundary is the candidate high boundary.

The optimum point

If the optimum attribute is specified and a value could be parsed out of it, then the candidate optimum point is that value. Otherwise, the candidate optimum point is the midpoint between the minimum value and the maximum value.

If the candidate optimum point is less than the minimum value, then the optimum point is the minimum value.

Otherwise, if the candidate optimum point is greater than the maximum value, then the optimum point is the maximum value.

Otherwise, the optimum point is the candidate optimum point.

All of which will result in the following inequalities all being true:

UA requirements for regions of the gauge: If the optimum point is equal to the low boundary or the high boundary, or anywhere in between them, then the region between the low and high boundaries of the gauge must be treated as the optimum region, and the low and high parts, if any, must be treated as suboptimal. Otherwise, if the optimum point is less than the low boundary, then the region between the minimum value and the low boundary must be treated as the optimum region, the region from the low boundary up to the high boundary must be treated as a suboptimal region, and the remaining region must be treated as an even less good region. Finally, if the optimum point is higher than the high boundary, then the situation is reversed; the region between the high boundary and the maximum value must be treated as the optimum region, the region from the high boundary down to the low boundary must be treated as a suboptimal region, and the remaining region must be treated as an even less good region.

UA requirements for showing the gauge: When representing a meter element to the user, the UA should indicate the relative position of the actual value to the minimum and maximum values, and the relationship between the actual value and the three regions of the gauge.

The following markup:

<h3>Suggested groups</h3>
<menu>
 <li><a href="?cmd=hsg" onclick="hideSuggestedGroups()">Hide suggested groups</a></li>
</menu>
<ul>
 <li>
  <p><a href="/group/comp.infosystems.www.authoring.stylesheets/view">comp.infosystems.www.authoring.stylesheets</a> -
     <a href="/group/comp.infosystems.www.authoring.stylesheets/subscribe">join</a></p>
  <p>Group description: <strong>Layout/presentation on the WWW.</strong></p>
  <p><meter value="0.5">Moderate activity,</meter> Usenet, 618 subscribers</p>
 </li>
 <li>
  <p><a href="/group/netscape.public.mozilla.xpinstall/view">netscape.public.mozilla.xpinstall</a> -
     <a href="/group/netscape.public.mozilla.xpinstall/subscribe">join</a></p>
  <p>Group description: <strong>Mozilla XPInstall discussion.</strong></p>
  <p><meter value="0.25">Low activity,</meter> Usenet, 22 subscribers</p>
 </li>
 <li>
  <p><a href="/group/mozilla.dev.general/view">mozilla.dev.general</a> -
     <a href="/group/mozilla.dev.general/subscribe">join</a></p>
  <p><meter value="0.25">Low activity,</meter> Usenet, 66 subscribers</p>
 </li>
</ul>

Might be rendered as follows:

With the <meter> elements rendered as inline green bars of varying lengths.

User agents may combine the value of the title attribute and the other attributes to provide context-sensitive help or inline text detailing the actual values.

For example, the following snippet:

<meter min=0 max=60 value=23.2 title=seconds></meter>

...might cause the user agent to display a gauge with a tooltip saying "Value: 23.2 out of 60." on one line and "seconds" on a second line.

The value IDL attribute, on getting, must return the actual value. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the value content attribute must be set to that string.

The min IDL attribute, on getting, must return the minimum value. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the min content attribute must be set to that string.

The max IDL attribute, on getting, must return the maximum value. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the max content attribute must be set to that string.

The low IDL attribute, on getting, must return the low boundary. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the low content attribute must be set to that string.

The high IDL attribute, on getting, must return the high boundary. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the high content attribute must be set to that string.

The optimum IDL attribute, on getting, must return the optimum value. On setting, the given value must be converted to the best representation of the number as a floating-point number and then the optimum content attribute must be set to that string.

The labels IDL attribute provides a list of the element's labels.

The following example shows how a gauge could fall back to localized or pretty-printed text.

<p>Disk usage: <meter min=0 value=170261928 max=233257824>170 261 928 bytes used
out of 233 257 824 bytes available</meter></p>

4.10.15 The fieldset element

Element/fieldset

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLFieldSetElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Flow content.
Sectioning root.
Listed and autocapitalize-inheriting form-associated element.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Optionally a legend element, followed by flow content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
disabled — Whether the descendant form controls, except any inside legend, are disabled
form — Associates the element with a form element
name — Name of the element to use in the form.elements API.
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLFieldSetElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean disabled;
  readonly attribute HTMLFormElement? form;
  [CEReactions] attribute DOMString name;

  readonly attribute DOMString type;

  [SameObject] readonly attribute HTMLCollection elements;

  readonly attribute boolean willValidate;
  [SameObject] readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();
  undefined setCustomValidity(DOMString error);
};

The fieldset element represents a set of form controls (or other content) grouped together, optionally with a caption. The caption is given by the first legend element that is a child of the fieldset element, if any. The remainder of the descendants form the group.

Element/fieldset#attr-disabled

Support in all current engines.

FirefoxYesSafari6+ChromeYes
Opera12+EdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOS6+Chrome AndroidYesWebView Android4.4+Samsung InternetYesOpera Android?

The disabled attribute, when specified, causes all the form control descendants of the fieldset element, excluding those that are descendants of the fieldset element's first legend element child, if any, to be disabled.

A fieldset element is a disabled fieldset if it matches any of the following conditions:

The form attribute is used to explicitly associate the fieldset element with its form owner. The name attribute represents the element's name.

fieldset . type

Returns the string "fieldset".

fieldset . elements

Returns an HTMLCollection of the form controls in the element.

The disabled IDL attribute must reflect the content attribute of the same name.

The type IDL attribute must return the string "fieldset".

The elements IDL attribute must return an HTMLCollection rooted at the fieldset element, whose filter matches listed elements.

The willValidate, validity, and validationMessage attributes, and the checkValidity(), reportValidity(), and setCustomValidity() methods, are part of the constraint validation API. The form and name IDL attributes are part of the element's forms API.

This example shows a fieldset element being used to group a set of related controls:

<fieldset>
 <legend>Display</legend>
 <p><label><input type=radio name=c value=0 checked> Black on White</label>
 <p><label><input type=radio name=c value=1> White on Black</label>
 <p><label><input type=checkbox name=g> Use grayscale</label>
 <p><label>Enhance contrast <input type=range name=e list=contrast min=0 max=100 value=0 step=1></label>
 <datalist id=contrast>
  <option label=Normal value=0>
  <option label=Maximum value=100>
 </datalist>
</fieldset>

The following snippet shows a fieldset with a checkbox in the legend that controls whether or not the fieldset is enabled. The contents of the fieldset consist of two required text controls and an optional year/month control.

<fieldset name="clubfields" disabled>
 <legend> <label>
  <input type=checkbox name=club onchange="form.clubfields.disabled = !checked">
  Use Club Card
 </label> </legend>
 <p><label>Name on card: <input name=clubname required></label></p>
 <p><label>Card number: <input name=clubnum required pattern="[-0-9]+"></label></p>
 <p><label>Expiry date: <input name=clubexp type=month></label></p>
</fieldset>

You can also nest fieldset elements. Here is an example expanding on the previous one that does so:

<fieldset name="clubfields" disabled>
 <legend> <label>
  <input type=checkbox name=club onchange="form.clubfields.disabled = !checked">
  Use Club Card
 </label> </legend>
 <p><label>Name on card: <input name=clubname required></label></p>
 <fieldset name="numfields">
  <legend> <label>
   <input type=radio checked name=clubtype onchange="form.numfields.disabled = !checked">
   My card has numbers on it
  </label> </legend>
  <p><label>Card number: <input name=clubnum required pattern="[-0-9]+"></label></p>
 </fieldset>
 <fieldset name="letfields" disabled>
  <legend> <label>
   <input type=radio name=clubtype onchange="form.letfields.disabled = !checked">
   My card has letters on it
  </label> </legend>
  <p><label>Card code: <input name=clublet required pattern="[A-Za-z]+"></label></p>
 </fieldset>
</fieldset>

In this example, if the outer "Use Club Card" checkbox is not checked, everything inside the outer fieldset, including the two radio buttons in the legends of the two nested fieldsets, will be disabled. However, if the checkbox is checked, then the radio buttons will both be enabled and will let you select which of the two inner fieldsets is to be enabled.

This example shows a grouping of controls where the legend element both labels the grouping, and the nested heading element surfaces the grouping in the document outline:

<fieldset>
 <legend> <h2>
  How can we best reach you?
 </h2> </legend>
 <p> <label>
 <input type=radio checked name=contact_pref>
  Phone
 </label> </p>
 <p> <label>
  <input type=radio name=contact_pref>
  Text
 </label> </p>
 <p> <label>
  <input type=radio name=contact_pref>
  Email
 </label> </p>
</fieldset>

4.10.16 The legend element

Element/legend

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLLegendElement

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
None.
Contexts in which this element can be used:
As the first child of a fieldset element.
Content model:
Phrasing content, optionally intermixed with heading content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLLegendElement : HTMLElement {
  [HTMLConstructor] constructor();

  readonly attribute HTMLFormElement? form;

  // also has obsolete members
};

The legend element represents a caption for the rest of the contents of the legend element's parent fieldset element, if any.

legend . form

Returns the element's form element, if any, or null otherwise.

The form IDL attribute's behavior depends on whether the legend element is in a fieldset element or not. If the legend has a fieldset element as its parent, then the form IDL attribute must return the same value as the form IDL attribute on that fieldset element. Otherwise, it must return null.

4.10.17 Form control infrastructure

4.10.17.1 A form control's value

Most form controls have a value and a checkedness. (The latter is only used by input elements.) These are used to describe how the user interacts with the control.

A control's value is its internal state. As such, it might not match the user's current input.

For instance, if a user enters the word "three" into a numeric field that expects digits, the user's input would be the string "three" but the control's value would remain unchanged. Or, if a user enters the email address "  awesome@example.com" (with leading whitespace) into an email field, the user's input would be the string "  awesome@example.com" but the browser's UI for email fields might translate that into a value of "awesome@example.com" (without the leading whitespace).

input and textarea elements have a dirty value flag. This is used to track the interaction between the value and default value. If it is false, value mirrors the default value. If it is true, the default value is ignored.

To define the behavior of constraint validation in the face of the input element's multiple attribute, input elements can also have separately defined values.

To define the behavior of the maxlength and minlength attributes, as well as other APIs specific to the textarea element, all form control with a value also have an algorithm for obtaining an API value. By default this algorithm is to simply return the control's value.

The select element does not have a value; the selectedness of its option elements is what is used instead.

4.10.17.2 可变性

表单控件可以指定为 可变的

这决定了(本规范中有些定义和要求依赖于元素是否被指定为可变的) 用户是否可以修改表单控件的 选中状态,或控件是否可以自动填充。

4.10.17.3 Association of controls and forms

A form-associated element can have a relationship with a form element, which is called the element's form owner. If a form-associated element is not associated with a form element, its form owner is said to be null.

A form-associated element has an associated parser inserted flag.

Attributes#attr-form

Support in all current engines.

Firefox1+Safari≤4+Chrome1+
Opera≤12.1+Edge79+
Edge (Legacy)12+Internet Explorer≤6+
Firefox Android4+Safari iOS≤3+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android≤12.1+

A form-associated element is, by default, associated with its nearest ancestor form element (as described below), but, if it is listed, may have a form attribute specified to override this.

This feature allows authors to work around the lack of support for nested form elements.

If a listed form-associated element has a form attribute specified, then that attribute's value must be the ID of a form element in the element's tree.

The rules in this section are complicated by the fact that although conforming documents or trees will never contain nested form elements, it is quite possible (e.g., using a script that performs DOM manipulation) to generate trees that have such nested elements. They are also complicated by rules in the HTML parser that, for historical reasons, can result in a form-associated element being associated with a form element that is not its ancestor.

When a form-associated element is created, its form owner must be initialized to null (no owner).

When a form-associated element is to be associated with a form, its form owner must be set to that form.

When a form-associated element or one of its ancestors is inserted, then:

  1. If the form-associated element's parser inserted flag is set, then return.

  2. Reset the form owner of the form-associated element.

When a form-associated element or one of its ancestors is removed, then:

  1. If the form-associated element has a form owner and the form-associated element and its form owner are no longer in the same tree, then reset the form owner of the form-associated element.

When a listed form-associated element's form attribute is set, changed, or removed, then the user agent must reset the form owner of that element.

When a listed form-associated element has a form attribute and the ID of any of the elements in the tree changes, then the user agent must reset the form owner of that form-associated element.

When a listed form-associated element has a form attribute and an element with an ID is inserted into or removed from the Document, then the user agent must reset the form owner of that form-associated element.

When the user agent is to reset the form owner of a form-associated element element, it must run the following steps:

  1. Unset element's parser inserted flag.

  2. If all of the following conditions are true

    then do nothing, and return.

  3. Set element's form owner to null.

  4. If element is listed, has a form content attribute, and is connected, then:

    1. If the first element in element's tree, in tree order, to have an ID that is identical to element's form content attribute's value, is a form element, then associate the element with that form element.

  5. Otherwise, if element has an ancestor form element, then associate element with the nearest such ancestor form element.

In the following non-conforming snippet:

...
 <form id="a">
  <div id="b"></div>
 </form>
 <script>
  document.getElementById('b').innerHTML =
     '<table><tr><td></form><form id="c"><input id="d"></table>' +
     '<input id="e">';
 </script>
...

The form owner of "d" would be the inner nested form "c", while the form owner of "e" would be the outer form "a".

This happens as follows: First, the "e" node gets associated with "c" in the HTML parser. Then, the innerHTML algorithm moves the nodes from the temporary document to the "b" element. At this point, the nodes see their ancestor chain change, and thus all the "magic" associations done by the parser are reset to normal ancestor associations.

This example is a non-conforming document, though, as it is a violation of the content models to nest form elements, and there is a parse error for the </form> tag.

element . form

HTMLObjectElement/form

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLSelectElement/form

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the element's form owner.

Returns null if there isn't one.

Listed form-associated elements except for form-associated custom elements have a form IDL attribute, which, on getting, must return the element's form owner, or null if there isn't one.

ElementInternals/form

Firefox98+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOSNoChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

Form-associated custom elements don't have form IDL attribute. Instead, their ElementInternals object has a form IDL attribute. On getting, it must throw a "NotSupportedError" DOMException if the target element is not a form-associated custom element. Otherwise, it must return the element's form owner, or null if there isn't one.

4.10.18 表单控件通用的属性

4.10.18.1 Naming form controls: the name attribute

The name content attribute gives the name of the form control, as used in form submission and in the form element's elements object. If the attribute is specified, its value must not be the empty string or isindex.

A number of user agents historically implemented special support for first-in-form text controls with the name isindex, and this specification previously defined related user agent requirements for it. However, some user agents subsequently dropped that special support, and the related requirements were removed from this specification. So, to avoid problematic reinterpretations in legacy user agents, the name isindex is no longer allowed.

Other than isindex, any non-empty value for name is allowed. An ASCII case-insensitive match for the name _charset_ is special: if used as the name of a Hidden control with no value attribute, then during submission the value attribute is automatically given a value consisting of the submission character encoding.

The name IDL attribute must reflect the name content attribute.

DOM clobbering is a common cause of security issues. Avoid using the names of built-in form properties with the name content attribute.

In this example, the input element overrides the built-in method property:

let form = document.createElement("form");
let input = document.createElement("input");
form.appendChild(input);

form.method;           // => "get"
input.name = "method"; // DOM clobbering occurs here
form.method === input; // => true

Since the input name takes precedence over built-in form properties, the JavaScript reference form.method will point to the input element named "method" instead of the built-in method property.

4.10.18.2 提交元素 element directionality: the dirname attribute

表单控件元素上的 dirname 属性 会让元素提交 文字方向, 并且给出 表单提交 时包含这个值的字段名。 如果指定了这个属性,它的值不得为空字符串。

在这个例子中,表单包含了一个文本控件和一个提交按钮:

<form action="addcomment.cgi" method=post>
 <p><label>Comment: <input type=text name="comment" dirname="comment.dir" required></label></p>
 <p><button name="mode" type=submit value="add">Post Comment</button></p>
</form>

当用户提交表单时,用户代理包含了 3 个字段,一个叫 "comment", 一个叫 "comment.dir", 一个叫 "mode";所以如果用户键入 "Hello",提交的消息体可能像这样:

comment=Hello&comment.dir=ltr&mode=add

如果用户手动切换到右到左书写方向,然后输入 "مرحبا",提交的消息体可能像这样:

comment=%D9%85%D8%B1%D8%AD%D8%A8%D8%A7&comment.dir=rtl&mode=add
4.10.18.3 Limiting user input length: the maxlength attribute

A form control maxlength attribute, controlled by the dirty value flag, declares a limit on the number of characters a user can input. The "number of characters" is measured using length and, in the case of textarea elements, with all newlines normalized to a single character (as opposed to CRLF pairs).

If an element has its form control maxlength attribute specified, the attribute's value must be a valid non-negative integer. If the attribute is specified and applying the rules for parsing non-negative integers to its value results in a number, then that number is the element's maximum allowed value length. If the attribute is omitted or parsing its value results in an error, then there is no maximum allowed value length.

Constraint validation: If an element has a maximum allowed value length, its dirty value flag is true, its value was last changed by a user edit (as opposed to a change made by a script), and the length of the element's API value is greater than the element's maximum allowed value length, then the element is suffering from being too long.

User agents may prevent the user from causing the element's API value to be set to a value whose length is greater than the element's maximum allowed value length.

In the case of textarea elements, the API value and value differ. In particular, newline normalization is applied before the maximum allowed value length is checked (whereas the textarea wrapping transformation is not applied).

4.10.18.4 Setting minimum input length requirements: the minlength attribute

A form control minlength attribute, controlled by the dirty value flag, declares a lower bound on the number of characters a user can input. The "number of characters" is measured using length and, in the case of textarea elements, with all newlines normalized to a single character (as opposed to CRLF pairs).

The minlength attribute does not imply the required attribute. If the form control has no required attribute, then the value can still be omitted; the minlength attribute only kicks in once the user has entered a value at all. If the empty string is not allowed, then the required attribute also needs to be set.

If an element has its form control minlength attribute specified, the attribute's value must be a valid non-negative integer. If the attribute is specified and applying the rules for parsing non-negative integers to its value results in a number, then that number is the element's minimum allowed value length. If the attribute is omitted or parsing its value results in an error, then there is no minimum allowed value length.

If an element has both a maximum allowed value length and a minimum allowed value length, the minimum allowed value length must be smaller than or equal to the maximum allowed value length.

Constraint validation: If an element has a minimum allowed value length, its dirty value flag is true, its value was last changed by a user edit (as opposed to a change made by a script), its value is not the empty string, and the length of the element's API value is less than the element's minimum allowed value length, then the element is suffering from being too short.

In this example, there are four text controls. The first is required, and has to be at least 5 characters long. The other three are optional, but if the user fills one in, the user has to enter at least 10 characters.

<form action="/events/menu.cgi" method="post">
 <p><label>Name of Event: <input required minlength=5 maxlength=50 name=event></label></p>
 <p><label>Describe what you would like for breakfast, if anything:
    <textarea name="breakfast" minlength="10"></textarea></label></p>
 <p><label>Describe what you would like for lunch, if anything:
    <textarea name="lunch" minlength="10"></textarea></label></p>
 <p><label>Describe what you would like for dinner, if anything:
    <textarea name="dinner" minlength="10"></textarea></label></p>
 <p><input type=submit value="Submit Request"></p>
</form>
4.10.18.5 Enabling and disabling form controls: the disabled attribute

The disabled content attribute is a boolean attribute.

The disabled attribute for option elements and the disabled attribute for optgroup elements are defined separately.

A form control is disabled if any of the following conditions are met:

  1. The element is a button, input, select, textarea, or form-associated custom element, and the disabled attribute is specified on this element (regardless of its value).
  2. The element is a descendant of a fieldset element whose disabled attribute is specified, and is not a descendant of that fieldset element's first legend element child, if any.

A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.

Constraint validation: If an element is disabled, it is barred from constraint validation.

HTMLButtonElement/disabled

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLSelectElement/disabled

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

The disabled IDL attribute must reflect the disabled content attribute.

4.10.18.6 Form submission attributes

Element/form#Attributes_for_form_submission

Support in all current engines.

Firefox4+Safari10.1+Chrome10+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS10.3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+

Attributes for form submission can be specified both on form elements and on submit buttons (elements that represent buttons that submit forms, e.g. an input element whose type attribute is in the Submit Button state).

The attributes for form submission that may be specified on form elements are action, enctype, method, novalidate, and target.

The corresponding attributes for form submission that may be specified on submit buttons are formaction, formenctype, formmethod, formnovalidate, and formtarget. When omitted, they default to the values given on the corresponding attributes on the form element.


The action and formaction content attributes, if specified, must have a value that is a valid non-empty URL potentially surrounded by spaces.

The action of an element is the value of the element's formaction attribute, if the element is a submit button and has such an attribute, or the value of its form owner's action attribute, if it has one, or else the empty string.


The method and formmethod content attributes are enumerated attributes with the following keywords and states:

The method attribute's invalid value default and missing value default are both the GET state.

The formmethod attribute's invalid value default is the GET state. It has no missing value default.

The method of an element is one of those states. If the element is a submit button and has a formmethod attribute, then the element's method is that attribute's state; otherwise, it is the form owner's method attribute's state.

Here the method attribute is used to explicitly specify the default value, "get", so that the search query is submitted in the URL:

<form method="get" action="/search.cgi">
 <p><label>Search terms: <input type=search name=q></label></p>
 <p><input type=submit></p>
</form>

On the other hand, here the method attribute is used to specify the value "post", so that the user's message is submitted in the HTTP request's body:

<form method="post" action="/post-message.cgi">
 <p><label>Message: <input type=text name=m></label></p>
 <p><input type=submit value="Submit message"></p>
</form>

In this example, a form is used with a dialog. The method attribute's "dialog" keyword is used to have the dialog automatically close when the form is submitted.

<dialog id="ship">
 <form method=dialog>
  <p>A ship has arrived in the harbour.</p>
  <button type=submit value="board">Board the ship</button>
  <button type=submit value="call">Call to the captain</button>
 </form>
</dialog>
<script>
 var ship = document.getElementById('ship');
 ship.showModal();
 ship.onclose = function (event) {
   if (ship.returnValue == 'board') {
     // ...
   } else {
     // ...
   }
 };
</script>

The enctype and formenctype content attributes are enumerated attributes with the following keywords and states:

The enctype attribute's invalid value default and missing value default are both the application/x-www-form-urlencoded state.

The formenctype attribute's invalid value default is the application/x-www-form-urlencoded state. It has no missing value default.

The enctype of an element is one of those three states. If the element is a submit button and has a formenctype attribute, then the element's enctype is that attribute's state; otherwise, it is the form owner's enctype attribute's state.


The target and formtarget content attributes, if specified, must have values that are valid browsing context names or keywords.


The novalidate and formnovalidate content attributes are boolean attributes. If present, they indicate that the form is not to be validated during submission.

The no-validate state of an element is true if the element is a submit button and the element's formnovalidate attribute is present, or if the element's form owner's novalidate attribute is present, and false otherwise.

This attribute is useful to include "save" buttons on forms that have validation constraints, to allow users to save their progress even though they haven't fully entered the data in the form. The following example shows a simple form that has two required fields. There are three buttons: one to submit the form, which requires both fields to be filled in; one to save the form so that the user can come back and fill it in later; and one to cancel the form altogether.

<form action="editor.cgi" method="post">
 <p><label>Name: <input required name=fn></label></p>
 <p><label>Essay: <textarea required name=essay></textarea></label></p>
 <p><input type=submit name=submit value="Submit essay"></p>
 <p><input type=submit formnovalidate name=save value="Save essay"></p>
 <p><input type=submit formnovalidate name=cancel value="Cancel"></p>
</form>

HTMLFormElement/action

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLFormElement/target

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLFormElement/method

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLFormElement/enctype

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLFormElement/encoding

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The action IDL attribute must reflect the content attribute of the same name, except that on getting, when the content attribute is missing or its value is the empty string, the element's node document's URL must be returned instead. The target IDL attribute must reflect the content attribute of the same name. The method and enctype IDL attributes must reflect the respective content attributes of the same name, limited to only known values. The encoding IDL attribute must reflect the enctype content attribute, limited to only known values. The noValidate IDL attribute must reflect the novalidate content attribute. The formAction IDL attribute must reflect the formaction content attribute, except that on getting, when the content attribute is missing or its value is the empty string, the element's node document's URL must be returned instead. The formEnctype IDL attribute must reflect the formenctype content attribute, limited to only known values. The formMethod IDL attribute must reflect the formmethod content attribute, limited to only known values. The formNoValidate IDL attribute must reflect the formnovalidate content attribute. The formTarget IDL attribute must reflect the formtarget content attribute.

4.10.18.7 自动填充
4.10.18.7.1 Autofilling form controls: the autocomplete attribute

Attributes/autocomplete

FirefoxYesSafari?Chrome66+
OperaYesEdge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidYesSafari iOS?Chrome Android66+WebView Android66+Samsung Internet9.0+Opera AndroidYes

User agents sometimes have features for helping users fill forms in, for example prefilling the user's address based on earlier user input. The autocomplete content attribute can be used to hint to the user agent how to, or indeed whether to, provide such a feature.

There are two ways this attribute is used. When wearing the autofill expectation mantle, the autocomplete attribute describes what input is expected from users. When wearing the autofill anchor mantle, the autocomplete attribute describes the meaning of the given value.

On an input element whose type attribute is in the Hidden state, the autocomplete attribute wears the autofill anchor mantle. In all other cases, it wears the autofill expectation mantle.

When wearing the autofill expectation mantle, the autocomplete attribute, if specified, must have a value that is an ordered set of space-separated tokens consisting of either a single token that is an ASCII case-insensitive match for the string "off", or a single token that is an ASCII case-insensitive match for the string "on", or autofill detail tokens.

When wearing the autofill anchor mantle, the autocomplete attribute, if specified, must have a value that is an ordered set of space-separated tokens consisting of just autofill detail tokens (i.e. the "on" and "off" keywords are not allowed).

Autofill detail tokens are the following, in the order given below:

  1. Optionally, a token whose first eight characters are an ASCII case-insensitive match for the string "section-", meaning that the field belongs to the named group.

    For example, if there are two shipping addresses in the form, then they could be marked up as:

    <fieldset>
     <legend>Ship the blue gift to...</legend>
     <p> <label> Address:     <textarea name=ba autocomplete="section-blue shipping street-address"></textarea> </label>
     <p> <label> City:        <input name=bc autocomplete="section-blue shipping address-level2"> </label>
     <p> <label> Postal Code: <input name=bp autocomplete="section-blue shipping postal-code"> </label>
    </fieldset>
    <fieldset>
     <legend>Ship the red gift to...</legend>
     <p> <label> Address:     <textarea name=ra autocomplete="section-red shipping street-address"></textarea> </label>
     <p> <label> City:        <input name=rc autocomplete="section-red shipping address-level2"> </label>
     <p> <label> Postal Code: <input name=rp autocomplete="section-red shipping postal-code"> </label>
    </fieldset>
  2. Optionally, a token that is an ASCII case-insensitive match for one of the following strings:

  3. Either of the following two options:

As noted earlier, the meaning of the attribute and its keywords depends on the mantle that the attribute is wearing.

When wearing the autofill expectation mantle...

The "off" keyword indicates either that the control's input data is particularly sensitive (for example the activation code for a nuclear weapon); or that it is a value that will never be reused (for example a one-time-key for a bank login) and the user will therefore have to explicitly enter the data each time, instead of being able to rely on the UA to prefill the value for them; or that the document provides its own autocomplete mechanism and does not want the user agent to provide autocompletion values.

The "on" keyword indicates that the user agent is allowed to provide the user with autocompletion values, but does not provide any further information about what kind of data the user might be expected to enter. User agents would have to use heuristics to decide what autocompletion values to suggest.

The autofill field listed above indicate that the user agent is allowed to provide the user with autocompletion values, and specifies what kind of value is expected. The meaning of each such keyword is described in the table below.

If the autocomplete attribute is omitted, the default value corresponding to the state of the element's form owner's autocomplete attribute is used instead (either "on" or "off"). If there is no form owner, then the value "on" is used.

When wearing the autofill anchor mantle...

The autofill field listed above indicate that the value of the particular kind of value specified is that value provided for this element. The meaning of each such keyword is described in the table below.

In this example the page has explicitly specified the currency and amount of the transaction. The form requests a credit card and other billing details. The user agent could use this information to suggest a credit card that it knows has sufficient balance and that supports the relevant currency.

<form method=post action="step2.cgi">
 <input type=hidden autocomplete=transaction-currency value="CHF">
 <input type=hidden autocomplete=transaction-amount value="15.00">
 <p><label>Credit card number: <input type=text inputmode=numeric autocomplete=cc-number></label>
 <p><label>Expiry Date: <input type=month autocomplete=cc-exp></label>
 <p><input type=submit value="Continue...">
</form>

The autofill field keywords relate to each other as described in the table below. Each field name listed on a row of this table corresponds to the meaning given in the cell for that row in the column labeled "Meaning". Some fields correspond to subparts of other fields; for example, a credit card expiry date can be expressed as one field giving both the month and year of expiry ("cc-exp"), or as two fields, one giving the month ("cc-exp-month") and one the year ("cc-exp-year"). In such cases, the names of the broader fields cover multiple rows, in which the narrower fields are defined.

Generally, authors are encouraged to use the broader fields rather than the narrower fields, as the narrower fields tend to expose Western biases. For example, while it is common in some Western cultures to have a given name and a family name, in that order (and thus often referred to as a first name and a surname), many cultures put the family name first and the given name second, and many others simply have one name (a mononym). Having a single field is therefore more flexible.

Some fields are only appropriate for certain form controls. An autofill field name is inappropriate for a control if the control does not belong to the group listed for that autofill field in the fifth column of the first row describing that autofill field in the table below. What controls fall into each group is described below the table.

Field name Meaning Canonical Format Canonical Format Example Control group
"name" Full name Free-form text, no newlines Sir Timothy John Berners-Lee, OM, KBE, FRS, FREng, FRSA Text
"honorific-prefix" Prefix or title (e.g. "Mr.", "Ms.", "Dr.", "Mlle") Free-form text, no newlines Sir Text
"given-name" Given name (in some Western cultures, also known as the first name) Free-form text, no newlines Timothy Text
"additional-name" Additional names (in some Western cultures, also known as middle names, forenames other than the first name) Free-form text, no newlines John Text
"family-name" Family name (in some Western cultures, also known as the last name or surname) Free-form text, no newlines Berners-Lee Text
"honorific-suffix" Suffix (e.g. "Jr.", "B.Sc.", "MBASW", "II") Free-form text, no newlines OM, KBE, FRS, FREng, FRSA Text
"nickname" Nickname, screen name, handle: a typically short name used instead of the full name Free-form text, no newlines Tim Text
"organization-title" Job title (e.g. "Software Engineer", "Senior Vice President", "Deputy Managing Director") Free-form text, no newlines Professor Text
"username" A username Free-form text, no newlines timbl Username
"new-password" A new password (e.g. when creating an account or changing a password) Free-form text, no newlines GUMFXbadyrS3 Password
"current-password" The current password for the account identified by the username field (e.g. when logging in) Free-form text, no newlines qwerty Password
"one-time-code" One-time code used for verifying user identity Free-form text, no newlines 123456 Password
"organization" Company name corresponding to the person, address, or contact information in the other fields associated with this field Free-form text, no newlines World Wide Web Consortium Text
"street-address" Street address (multiple lines, newlines preserved) Free-form text 32 Vassar Street
MIT Room 32-G524
Multiline
"address-line1" Street address (one line per field) Free-form text, no newlines 32 Vassar Street Text
"address-line2" Free-form text, no newlines MIT Room 32-G524 Text
"address-line3" Free-form text, no newlines Text
"address-level4" The most fine-grained administrative level, in addresses with four administrative levels Free-form text, no newlines Text
"address-level3" The third administrative level, in addresses with three or more administrative levels Free-form text, no newlines Text
"address-level2" The second administrative level, in addresses with two or more administrative levels; in the countries with two administrative levels, this would typically be the city, town, village, or other locality within which the relevant street address is found Free-form text, no newlines Cambridge Text
"address-level1" The broadest administrative level in the address, i.e. the province within which the locality is found; for example, in the US, this would be the state; in Switzerland it would be the canton; in the UK, the post town Free-form text, no newlines MA Text
"country" Country code Valid ISO 3166-1-alpha-2 country code [ISO3166] US Text
"country-name" Country name Free-form text, no newlines; derived from country in some cases US Text
"postal-code" Postal code, post code, ZIP code, CEDEX code (if CEDEX, append "CEDEX", and the arrondissement, if relevant, to the address-level2 field) Free-form text, no newlines 02139 Text
"cc-name" Full name as given on the payment instrument Free-form text, no newlines Tim Berners-Lee Text
"cc-given-name" Given name as given on the payment instrument (in some Western cultures, also known as the first name) Free-form text, no newlines Tim Text
"cc-additional-name" Additional names given on the payment instrument (in some Western cultures, also known as middle names, forenames other than the first name) Free-form text, no newlines Text
"cc-family-name" Family name given on the payment instrument (in some Western cultures, also known as the last name or surname) Free-form text, no newlines Berners-Lee Text
"cc-number" Code identifying the payment instrument (e.g. the credit card number) ASCII digits 4114360123456785 Text
"cc-exp" Expiration date of the payment instrument Valid month string 2014-12 Month
"cc-exp-month" Month component of the expiration date of the payment instrument Valid integer in the range 1..12 12 Numeric
"cc-exp-year" Year component of the expiration date of the payment instrument Valid integer greater than zero 2014 Numeric
"cc-csc" Security code for the payment instrument (also known as the card security code (CSC), card validation code (CVC), card verification value (CVV), signature panel code (SPC), credit card ID (CCID), etc) ASCII digits 419 Text
"cc-type" Type of payment instrument Free-form text, no newlines Visa Text
"transaction-currency" The currency that the user would prefer the transaction to use ISO 4217 currency code [ISO4217] GBP Text
"transaction-amount" The amount that the user would like for the transaction (e.g. when entering a bid or sale price) Valid floating-point number 401.00 Numeric
"language" Preferred language Valid BCP 47 language tag [BCP47] en Text
"bday" Birthday Valid date string 1955-06-08 Date
"bday-day" Day component of birthday Valid integer in the range 1..31 8 Numeric
"bday-month" Month component of birthday Valid integer in the range 1..12 6 Numeric
"bday-year" Year component of birthday Valid integer greater than zero 1955 Numeric
"sex" Gender identity (e.g. Female, Fa'afafine) Free-form text, no newlines Male Text
"url" Home page or other web page corresponding to the company, person, address, or contact information in the other fields associated with this field Valid URL string https://www.w3.org/People/Berners-Lee/ URL
"photo" Photograph, icon, or other image corresponding to the company, person, address, or contact information in the other fields associated with this field Valid URL string https://www.w3.org/Press/Stock/Berners-Lee/2001-europaeum-eighth.jpg URL
"tel" Full telephone number, including country code ASCII digits and U+0020 SPACE characters, prefixed by a U+002B PLUS SIGN character (+) +1 617 253 5702 Tel
"tel-country-code" Country code component of the telephone number ASCII digits prefixed by a U+002B PLUS SIGN character (+) +1 Text
"tel-national" Telephone number without the county code component, with a country-internal prefix applied if applicable ASCII digits and U+0020 SPACE characters 617 253 5702 Text
"tel-area-code" Area code component of the telephone number, with a country-internal prefix applied if applicable ASCII digits 617 Text
"tel-local" Telephone number without the country code and area code components ASCII digits 2535702 Text
"tel-local-prefix" First part of the component of the telephone number that follows the area code, when that component is split into two components ASCII digits 253 Text
"tel-local-suffix" Second part of the component of the telephone number that follows the area code, when that component is split into two components ASCII digits 5702 Text
"tel-extension" Telephone number internal extension code ASCII digits 1000 Text
"email" Email address Valid email address timbl@w3.org Username
"impp" URL representing an instant messaging protocol endpoint (for example, "aim:goim?screenname=example" or "xmpp:fred@example.net") Valid URL string irc://example.org/timbl,isuser URL

The groups correspond to controls as follows:

Text
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
textarea elements
select elements
Multiline
input elements with a type attribute in the Hidden state
textarea elements
select elements
Password
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the Password state
textarea elements
select elements
URL
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the URL state
textarea elements
select elements
Username
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the Email state
textarea elements
select elements
Tel
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the Telephone state
textarea elements
select elements
Numeric
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the Number state
textarea elements
select elements
Month
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the Month state
textarea elements
select elements
Date
input elements with a type attribute in the Hidden state
input elements with a type attribute in the Text state
input elements with a type attribute in the Search state
input elements with a type attribute in the Date state
textarea elements
select elements

Address levels: The "address-level1" – "address-level4" fields are used to describe the locality of the street address. Different locales have different numbers of levels. For example, the US uses two levels (state and town), the UK uses one or two depending on the address (the post town, and in some cases the locality), and China can use three (province, city, district). The "address-level1" field represents the widest administrative division. Different locales order the fields in different ways; for example, in the US the town (level 2) precedes the state (level 1); while in Japan the prefecture (level 1) precedes the city (level 2) which precedes the district (level 3). Authors are encouraged to provide forms that are presented in a way that matches the country's conventions (hiding, showing, and rearranging fields accordingly as the user changes the country).

4.10.18.7.2 Processing model

Each input element to which the autocomplete attribute applies, each select element, and each textarea element, has an autofill hint set, an autofill scope, an autofill field name, and an IDL-exposed autofill value.

The autofill field name specifies the specific kind of data expected in the field, e.g. "street-address" or "cc-exp".

The autofill hint set identifies what address or contact information type the user agent is to look at, e.g. "shipping fax" or "billing".

The autofill scope identifies the group of fields whose information concerns the same subject, and consists of the autofill hint set with, if applicable, the "section-*" prefix, e.g. "billing", "section-parent shipping", or "section-child shipping home".

These values are defined as the result of running the following algorithm:

  1. If the element has no autocomplete attribute, then jump to the step labeled default.

  2. Let tokens be the result of splitting the attribute's value on ASCII whitespace.

  3. If tokens is empty, then jump to the step labeled default.

  4. Let index be the index of the last token in tokens.

  5. If the indexth token in tokens is not an ASCII case-insensitive match for one of the tokens given in the first column of the following table, or if the number of tokens in tokens is greater than the maximum number given in the cell in the second column of that token's row, then jump to the step labeled default. Otherwise, let field be the string given in the cell of the first column of the matching row, and let category be the value of the cell in the third column of that same row.

    Token Maximum number of tokens Category
    "off" 1 Off
    "on" 1 Automatic
    "name" 3 Normal
    "honorific-prefix" 3 Normal
    "given-name" 3 Normal
    "additional-name" 3 Normal
    "family-name" 3 Normal
    "honorific-suffix" 3 Normal
    "nickname" 3 Normal
    "organization-title" 3 Normal
    "username" 3 Normal
    "new-password" 3 Normal
    "current-password" 3 Normal
    "one-time-code" 3 Normal
    "organization" 3 Normal
    "street-address" 3 Normal
    "address-line1" 3 Normal
    "address-line2" 3 Normal
    "address-line3" 3 Normal
    "address-level4" 3 Normal
    "address-level3" 3 Normal
    "address-level2" 3 Normal
    "address-level1" 3 Normal
    "country" 3 Normal
    "country-name" 3 Normal
    "postal-code" 3 Normal
    "cc-name" 3 Normal
    "cc-given-name" 3 Normal
    "cc-additional-name" 3 Normal
    "cc-family-name" 3 Normal
    "cc-number" 3 Normal
    "cc-exp" 3 Normal
    "cc-exp-month" 3 Normal
    "cc-exp-year" 3 Normal
    "cc-csc" 3 Normal
    "cc-type" 3 Normal
    "transaction-currency" 3 Normal
    "transaction-amount" 3 Normal
    "language" 3 Normal
    "bday" 3 Normal
    "bday-day" 3 Normal
    "bday-month" 3 Normal
    "bday-year" 3 Normal
    "sex" 3 Normal
    "url" 3 Normal
    "photo" 3 Normal
    "tel" 4 Contact
    "tel-country-code" 4 Contact
    "tel-national" 4 Contact
    "tel-area-code" 4 Contact
    "tel-local" 4 Contact
    "tel-local-prefix" 4 Contact
    "tel-local-suffix" 4 Contact
    "tel-extension" 4 Contact
    "email" 4 Contact
    "impp" 4 Contact
  6. If category is Off or Automatic but the element's autocomplete attribute is wearing the autofill anchor mantle, then jump to the step labeled default.

  7. If category is Off, let the element's autofill field name be the string "off", let its autofill hint set be empty, and let its IDL-exposed autofill value be the string "off". Then, return.

  8. If category is Automatic, let the element's autofill field name be the string "on", let its autofill hint set be empty, and let its IDL-exposed autofill value be the string "on". Then, return.

  9. Let scope tokens be an empty list.

  10. Let hint tokens be an empty set.

  11. Let IDL value have the same value as field.

  12. If the indexth token in tokens is the first entry, then skip to the step labeled done.

  13. Decrement index by one.

  14. If category is Contact and the indexth token in tokens is an ASCII case-insensitive match for one of the strings in the following list, then run the substeps that follow:

    The substeps are:

    1. Let contact be the matching string from the list above.

    2. Insert contact at the start of scope tokens.

    3. Add contact to hint tokens.

    4. Let IDL value be the concatenation of contact, a U+0020 SPACE character, and the previous value of IDL value (which at this point will always be field).

    5. If the indexth entry in tokens is the first entry, then skip to the step labeled done.

    6. Decrement index by one.

  15. If the indexth token in tokens is an ASCII case-insensitive match for one of the strings in the following list, then run the substeps that follow:

    The substeps are:

    1. Let mode be the matching string from the list above.

    2. Insert mode at the start of scope tokens.

    3. Add mode to hint tokens.

    4. Let IDL value be the concatenation of mode, a U+0020 SPACE character, and the previous value of IDL value (which at this point will either be field or the concatenation of contact, a space, and field).

    5. If the indexth entry in tokens is the first entry, then skip to the step labeled done.

    6. Decrement index by one.

  16. If the indexth entry in tokens is not the first entry, then jump to the step labeled default.

  17. If the first eight characters of the indexth token in tokens are not an ASCII case-insensitive match for the string "section-", then jump to the step labeled default.

  18. Let section be the indexth token in tokens, converted to ASCII lowercase.

  19. Insert section at the start of scope tokens.

  20. Let IDL value be the concatenation of section, a U+0020 SPACE character, and the previous value of IDL value.

  21. Done: Let the element's autofill hint set be hint tokens.

  22. Let the element's autofill scope be scope tokens.

  23. Let the element's autofill field name be field.

  24. Let the element's IDL-exposed autofill value be IDL value.

  25. Return.

  26. Default: Let the element's IDL-exposed autofill value be the empty string, and its autofill hint set and autofill scope be empty.

  27. If the element's autocomplete attribute is wearing the autofill anchor mantle, then let the element's autofill field name be the empty string and return.

  28. Let form be the element's form owner, if any, or null otherwise.

  29. If form is not null and form's autocomplete attribute is in the off state, then let the element's autofill field name be "off".

    Otherwise, let the element's autofill field name be "on".


For the purposes of autofill, a control's data depends on the kind of control:

An input element with its type attribute in the Email state and with the multiple attribute specified
The element's values.
Any other input element
A textarea element
The element's value.
A select element with its multiple attribute specified
The option elements in the select element's list of options that have their selectedness set to true.
Any other select element
The option element in the select element's list of options that has its selectedness set to true.

How to process the autofill hint set, autofill scope, and autofill field name depends on the mantle that the autocomplete attribute is wearing.

When wearing the autofill expectation mantle...

When an element's autofill field name is "off", the user agent should not remember the control's data, and should not offer past values to the user.

In addition, when an element's autofill field name is "off", values are reset when traversing the history.

Banks frequently do not want UAs to prefill login information:

<p><label>Account: <input type="text" name="ac" autocomplete="off"></label></p>
<p><label>PIN: <input type="password" name="pin" autocomplete="off"></label></p>

When an element's autofill field name is not "off", the user agent may store the control's data, and may offer previously stored values to the user.

For example, suppose a user visits a page with this control:

<select name="country">
 <option>Afghanistan
 <option>Albania
 <option>Algeria
 <option>Andorra
 <option>Angola
 <option>Antigua and Barbuda
 <option>Argentina
 <option>Armenia
 <!-- ... -->
 <option>Yemen
 <option>Zambia
 <option>Zimbabwe
</select>

This might render as follows:

A drop-down control with a long alphabetical list of countries.

Suppose that on the first visit to this page, the user selects "Zambia". On the second visit, the user agent could duplicate the entry for Zambia at the top of the list, so that the interface instead looks like this:

The same drop-down control with the alphabetical list of countries, but with Zambia as an entry at the top.

When the autofill field name is "on", the user agent should attempt to use heuristics to determine the most appropriate values to offer the user, e.g. based on the element's name value, the position of the element in its tree, what other fields exist in the form, and so forth.

When the autofill field name is one of the names of the autofill fields described above, the user agent should provide suggestions that match the meaning of the field name as given in the table earlier in this section. The autofill hint set should be used to select amongst multiple possible suggestions.

For example, if a user once entered one address into fields that used the "shipping" keyword, and another address into fields that used the "billing" keyword, then in subsequent forms only the first address would be suggested for form controls whose autofill hint set contains the keyword "shipping". Both addresses might be suggested, however, for address-related form controls whose autofill hint set does not contain either keyword.

When wearing the autofill anchor mantle...

When the autofill field name is not the empty string, then the user agent must act as if the user had specified the control's data for the given autofill hint set, autofill scope, and autofill field name combination.

When the user agent autofills form controls, elements with the same form owner and the same autofill scope must use data relating to the same person, address, payment instrument, and contact details. When a user agent autofills "country" and "country-name" fields with the same form owner and autofill scope, and the user agent has a value for the country" field(s), then the "country-name" field(s) must be filled using a human-readable name for the same country. When a user agent fills in multiple fields at once, all fields with the same autofill field name, form owner and autofill scope must be filled with the same value.

Suppose a user agent knows of two phone numbers, +1 555 123 1234 and +1 555 666 7777. It would not be conforming for the user agent to fill a field with autocomplete="shipping tel-local-prefix" with the value "123" and another field in the same form with autocomplete="shipping tel-local-suffix" with the value "7777". The only valid prefilled values given the aforementioned information would be "123" and "1234", or "666" and "7777", respectively.

Similarly, if a form for some reason contained both a "cc-exp" field and a "cc-exp-month" field, and the user agent prefilled the form, then the month component of the former would have to match the latter.

This requirement interacts with the autofill anchor mantle also. Consider the following markup snippet:

<form>
 <input type=hidden autocomplete="nickname" value="TreePlate">
 <input type=text autocomplete="nickname">
</form>

The only value that a conforming user agent could suggest in the text control is "TreePlate", the value given by the hidden input element.

The "section-*" tokens in the autofill scope are opaque; user agents must not attempt to derive meaning from the precise values of these tokens.

For example, it would not be conforming if the user agent decided that it should offer the address it knows to be the user's daughter's address for "section-child" and the addresses it knows to be the user's spouses' addresses for "section-spouse".

The autocompletion mechanism must be implemented by the user agent acting as if the user had modified the control's data, and must be done at a time where the element is mutable (e.g. just after the element has been inserted into the document, or when the user agent stops parsing). User agents must only prefill controls using values that the user could have entered.

For example, if a select element only has option elements with values "Steve" and "Rebecca", "Jay", and "Bob", and has an autofill field name "given-name", but the user agent's only idea for what to prefill the field with is "Evan", then the user agent cannot prefill the field. It would not be conforming to somehow set the select element to the value "Evan", since the user could not have done so themselves.

A user agent prefilling a form control must not discriminate between form controls that are in a document tree and those that are connected; that is, it is not conforming to make the decision on whether or not to autofill based on whether the element's root is a shadow root versus a Document.

A user agent prefilling a form control's value must not cause that control to suffer from a type mismatch, suffer from being too long, suffer from being too short, suffer from an underflow, suffer from an overflow, or suffer from a step mismatch. A user agent prefilling a form control's value must not cause that control to suffer from a pattern mismatch either. Where possible given the control's constraints, user agents must use the format given as canonical in the aforementioned table. Where it's not possible for the canonical format to be used, user agents should use heuristics to attempt to convert values so that they can be used.

For example, if the user agent knows that the user's middle name is "Ines", and attempts to prefill a form control that looks like this:

<input name=middle-initial maxlength=1 autocomplete="additional-name">

...then the user agent could convert "Ines" to "I" and prefill it that way.

A more elaborate example would be with month values. If the user agent knows that the user's birthday is the 27th of July 2012, then it might try to prefill all of the following controls with slightly different values, all driven from this information:

<input name=b type=month autocomplete="bday">
2012-07 The day is dropped since the Month state only accepts a month/year combination. (Note that this example is non-conforming, because the autofill field name bday is not allowed with the Month state.)
<select name=c autocomplete="bday">
 <option>Jan
 <option>Feb
 ...
 <option>Jul
 <option>Aug
 ...
</select>
July The user agent picks the month from the listed options, either by noticing there are twelve options and picking the 7th, or by recognizing that one of the strings (three characters "Jul" followed by a newline and a space) is a close match for the name of the month (July) in one of the user agent's supported languages, or through some other similar mechanism.
<input name=a type=number min=1 max=12 autocomplete="bday-month">
7 User agent converts "July" to a month number in the range 1..12, like the field.
<input name=a type=number min=0 max=11 autocomplete="bday-month">
6 User agent converts "July" to a month number in the range 0..11, like the field.
<input name=a type=number min=1 max=11 autocomplete="bday-month">
User agent doesn't fill in the field, since it can't make a good guess as to what the form expects.

A user agent may allow the user to override an element's autofill field name, e.g. to change it from "off" to "on" to allow values to be remembered and prefilled despite the page author's objections, or to always "off", never remembering values.

More specifically, user agents may in particular consider replacing the autofill field name of form controls that match the description given in the first column of the following table, when their autofill field name is either "on" or "off", with the value given in the second cell of that row. If this table is used, the replacements must be done in tree order, since all but the first row references the autofill field name of earlier elements. When the descriptions below refer to form controls being preceded or followed by others, they mean in the list of listed elements that share the same form owner.

Form control New autofill field name
an input element whose type attribute is in the Text state that is followed by an input element whose type attribute is in the Password state "username"
an input element whose type attribute is in the Password state that is preceded by an input element whose autofill field name is "username" "current-password"
an input element whose type attribute is in the Password state that is preceded by an input element whose autofill field name is "current-password" "new-password"
an input element whose type attribute is in the Password state that is preceded by an input element whose autofill field name is "new-password" "new-password"

The autocomplete IDL attribute, on getting, must return the element's IDL-exposed autofill value, and on setting, must reflect the content attribute of the same name.

4.10.19 APIs for the text control selections

The input and textarea elements define several attributes and methods for handling their selection. Their shared algorithms are defined here.

element . select()

Selects everything in the text control.

element . selectionStart [ = value ]

Returns the offset to the start of the selection.

Can be set, to change the start of the selection.

element . selectionEnd [ = value ]

Returns the offset to the end of the selection.

Can be set, to change the end of the selection.

element . selectionDirection [ = value ]

Returns the current direction of the selection.

Can be set, to change the direction of the selection.

The possible values are "forward", "backward", and "none".

element . setSelectionRange(start, end [, direction] )

HTMLInputElement/setSelectionRange

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Changes the selection to cover the given substring in the given direction. If the direction is omitted, it will be reset to be the platform default (none or forward).

element . setRangeText(replacement [, start, end [, selectionMode ] ] )

HTMLInputElement/setRangeText

Support in all current engines.

Firefox27+Safari7+Chrome24+
Opera15+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android27+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android14+

Replaces a range of text with the new text. If the start and end arguments are not provided, the range is assumed to be the selection.

The final argument determines how the selection will be set after the text has been replaced. The possible values are:

"select"
Selects the newly inserted text.
"start"
Moves the selection to just before the inserted text.
"end"
Moves the selection to just after the selected text.
"preserve"
Attempts to preserve the selection. This is the default.

All input elements to which these APIs apply, and all textarea elements, have either a selection or a text entry cursor position at all times (even for elements that are not being rendered), measured in offsets into the code units of the control's relevant value. The initial state must consist of a text entry cursor at the beginning of the control.

For input elements, these APIs must operate on the element's value. For textarea elements, these APIs must operate on the element's API value. In the below algorithms, we call the value string being operated on the relevant value.

The use of API value instead of raw value for textarea elements means that U+000D (CR) characters are normalized away. For example,

<textarea id="demo"></textarea>
<script>
 demo.value = "A\r\nB";
 demo.setRangeText("replaced", 0, 2);
 assert(demo.value === "replacedB");
</script>

If we had operated on the raw value of "A\r\nB", then we would have replaced the characters "A\r", ending up with a result of "replaced\nB". But since we used the API value of "A\nB", we replaced the characters "A\n", giving "replacedB".

Characters with no visible rendering, such as U+200D ZERO WIDTH JOINER, still count as characters. Thus, for instance, the selection can include just an invisible character, and the text insertion cursor can be placed to one side or another of such a character.

Whenever the relevant value changes for an element to which these APIs apply, run these steps:

  1. If the element has a selection:

    1. If the start of the selection is now past the end of the relevant value, set it to the end of the relevant value.

    2. If the end of the selection is now past the end of the relevant value, set it to the end of the relevant value.

    3. If the user agent does not support empty selection, and both the start and end of the selection are now pointing to the end of the relevant value, then instead set the element's text entry cursor position to the end of the relevant value, removing any selection.

  2. Otherwise, the element must have a text entry cursor position position. If it is now past the end of the relevant value, set it to the end of the relevant value.

In some cases where the relevant value changes, other parts of the specification will also modify the text entry cursor position, beyond just the clamping steps above. For example, see the value setter for textarea.

Where possible, user interface features for changing the text selection in input and textarea elements must be implemented using the set the selection range algorithm so that, e.g., all the same events fire.

The selections of input and textarea elements have a selection direction, which is either "forward", "backward", or "none". The exact meaning of the selection direction depends on the platform. This direction is set when the user manipulates the selection. The initial selection direction must be "none" if the platform supports that direction, or "forward" otherwise.

To set the selection direction of an element to a given direction, update the element's selection direction to the given direction, unless the direction is "none" and the platform does not support that direction; in that case, update the element's selection direction to "forward".

On Windows, the direction indicates the position of the caret relative to the selection: a "forward" selection has the caret at the end of the selection and a "backward" selection has the caret at the start of the selection. Windows has no "none" direction.

On Mac, the direction indicates which end of the selection is affected when the user adjusts the size of the selection using the arrow keys with the Shift modifier: the "forward" direction means the end of the selection is modified, and the "backward" direction means the start of the selection is modified. The "none" direction is the default on Mac, it indicates that no particular direction has yet been selected. The user sets the direction implicitly when first adjusting the selection, based on which directional arrow key was used.

HTMLInputElement/select

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

HTMLInputElement/select

The select() method, when invoked, must run the following steps:

  1. If this element is an input element, and either select() does not apply to this element or the corresponding control has no selectable text, return.

    For instance, in a user agent where <input type=color> is rendered as a color well with a picker, as opposed to a text control accepting a hexadecimal color code, there would be no selectable text, and thus calls to the method are ignored.

  2. Set the selection range with 0 and infinity.

The selectionStart attribute's getter must run the following steps:

  1. If this element is an input element, and selectionStart does not apply to this element, return null.

  2. If there is no selection, return the code unit offset within the relevant value to the character that immediately follows the text entry cursor.

  3. Return the code unit offset within the relevant value to the character that immediately follows the start of the selection.

The selectionStart attribute's setter must run the following steps:

  1. If this element is an input element, and selectionStart does not apply to this element, throw an "InvalidStateError" DOMException.

  2. Let end be the value of this element's selectionEnd attribute.

  3. If end is less than the given value, set end to the given value.

  4. Set the selection range with the given value, end, and the value of this element's selectionDirection attribute.

The selectionEnd attribute's getter must run the following steps:

  1. If this element is an input element, and selectionEnd does not apply to this element, return null.

  2. If there is no selection, return the code unit offset within the relevant value to the character that immediately follows the text entry cursor.

  3. Return the code unit offset within the relevant value to the character that immediately follows the end of the selection.

The selectionEnd attribute's setter must run the following steps:

  1. If this element is an input element, and selectionEnd does not apply to this element, throw an "InvalidStateError" DOMException.

  2. Set the selection range with the value of this element's selectionStart attribute, the given value, and the value of this element's selectionDirection attribute.

The selectionDirection attribute's getter must run the following steps:

  1. If this element is an input element, and selectionDirection does not apply to this element, return null.

  2. Return this element's selection direction.

The selectionDirection attribute's setter must run the following steps:

  1. If this element is an input element, and selectionDirection does not apply to this element, throw an "InvalidStateError" DOMException.

  2. Set the selection range with the value of this element's selectionStart attribute, the value of this element's selectionEnd attribute, and the given value.

The setSelectionRange(start, end, direction) method, when invoked, must run the following steps:

  1. If this element is an input element, and setSelectionRange() does not apply to this element, throw an "InvalidStateError" DOMException.

  2. Set the selection range with start, end, and direction.

To set the selection range with an integer or null start, an integer or null or the special value infinity end, and optionally a string direction, run the following steps:

  1. If start is null, let start be zero.

  2. If end is null, let end be zero.

  3. Set the selection of the text control to the sequence of code units within the relevant value starting with the code unit at the startth position (in logical order) and ending with the code unit at the (end-1)th position. Arguments greater than the length of the relevant value of the text control (including the special value infinity) must be treated as pointing at the end of the text control. If end is less than or equal to start then the start of the selection and the end of the selection must both be placed immediately before the character with offset end. In UAs where there is no concept of an empty selection, this must set the cursor to be just before the character with offset end.

  4. If direction is not identical to either "backward" or "forward", or if the direction argument was not given, set direction to "none".

  5. Set the selection direction of the text control to direction.

  6. If the previous steps caused the selection of the text control to be modified (in either extent or direction), then queue an element task on the user interaction task source given the element to fire an event named select at the element, with the bubbles attribute initialized to true.

The setRangeText(replacement, start, end, selectMode) method, when invoked, must run the following steps:

  1. If this element is an input element, and setRangeText() does not apply to this element, throw an "InvalidStateError" DOMException.

  2. Set this element's dirty value flag to true.

  3. If the method has only one argument, then let start and end have the values of the selectionStart attribute and the selectionEnd attribute respectively.

    Otherwise, let start, end have the values of the second and third arguments respectively.

  4. If start is greater than end, then throw an "IndexSizeError" DOMException.

  5. If start is greater than the length of the relevant value of the text control, then set it to the length of the relevant value of the text control.

  6. If end is greater than the length of the relevant value of the text control, then set it to the length of the relevant value of the text control.

  7. Let selection start be the current value of the selectionStart attribute.

  8. Let selection end be the current value of the selectionEnd attribute.

  9. If start is less than end, delete the sequence of code units within the element's relevant value starting with the code unit at the startth position and ending with the code unit at the (end-1)th position.

  10. Insert the value of the first argument into the text of the relevant value of the text control, immediately before the startth code unit.

  11. Let new length be the length of the value of the first argument.

  12. Let new end be the sum of start and new length.

  13. Run the appropriate set of substeps from the following list:

    If the fourth argument's value is "select"

    Let selection start be start.

    Let selection end be new end.

    If the fourth argument's value is "start"

    Let selection start and selection end be start.

    If the fourth argument's value is "end"

    Let selection start and selection end be new end.

    If the fourth argument's value is "preserve"
    If the method has only one argument
    1. Let old length be end minus start.

    2. Let delta be new length minus old length.

    3. If selection start is greater than end, then increment it by delta. (If delta is negative, i.e. the new text is shorter than the old text, then this will decrease the value of selection start.)

      Otherwise: if selection start is greater than start, then set it to start. (This snaps the start of the selection to the start of the new text if it was in the middle of the text that it replaced.)

    4. If selection end is greater than end, then increment it by delta in the same way.

      Otherwise: if selection end is greater than start, then set it to new end. (This snaps the end of the selection to the end of the new text if it was in the middle of the text that it replaced.)

  14. Set the selection range with selection start and selection end.

The setRangeText() method uses the following enumeration:

enum SelectionMode {
  "select",
  "start",
  "end",
  "preserve" // default
};

To obtain the currently selected text, the following JavaScript suffices:

var selectionText = control.value.substring(control.selectionStart, control.selectionEnd);

...where control is the input or textarea element.

To add some text at the start of a text control, while maintaining the text selection, the three attributes must be preserved:

var oldStart = control.selectionStart;
var oldEnd = control.selectionEnd;
var oldDirection = control.selectionDirection;
var prefix = "http://";
control.value = prefix + control.value;
control.setSelectionRange(oldStart + prefix.length, oldEnd + prefix.length, oldDirection);

...where control is the input or textarea element.

4.10.20 约束

4.10.20.1 定义

可提交元素 都是 约束验证候选项, 除非有条件 禁止了该元素的约束验证。 (例如,object 元素就会 禁止约束验证。)

元素可以定义 自定义验证错误信息。 元素必须把它的 自定义验证错误信息 初始化为空字符串。当它的值不是空字符串时,该元素就 处于自定义错误状态。 可以使用 setCustomValidity() 方法设置它。 用户代理应该使用 自定义验证错误信息 把控件的错误提示给用户。

元素可以有很多种约束方式。下面的 合法性状态 列表给出了约束验证下表单控件可能的状态。 (下面的定义是非规范的;本规范的其他地方更精确地定义了每个状态是否适用。)

处于缺失状态

当一个控件没有 但设置了 required 属性时(input required, textarea required); 另外一种情况是 select 元素和 单选按钮组 中的控件, 规则较复杂,它们的定义请参考相应章节。

处于类型不匹配状态

当允许任意用户输入的控件有 但值的语法不正确时 (E-mail, URL)。

处于模式不匹配状态

当控件有 但值不符合 pattern 属性时。

处于长度超出限制状态

当控件有 但长度超过了 表单控件的 maxlength 属性input maxlength, textarea maxlength)。

处于长度不够状态

当控件有 但长度小于 表单控件 minlength 属性input minlength, textarea minlength)。

处于下溢出状态

当控件有 且非空字符串, 而小于 min 属性时。

处于下溢出状态

当控件有 且非空字符串, 而小于 max 属性时。

处于步长不匹配状态

当控件有 但不匹配 step 属性给出的规则时。

处于非法输入状态

当控件的输入不完整,且用户代理认为用户不应该以当前状态提交表单时。

处于自定义错误状态

当控件的 自定义验证错误信息 (通过元素的 setCustomValidity() 方法设置) 是非空字符串时。

即使元素被 禁用,也可能处于上述状态; 因此即使表单提交时的表单验证不向用户指出问题,这些状态也可以表示在 DOM 中。

如果一个元素没有处于任何上述 合法性状态, 就说这个元素 符合它的约束

4.10.20.2 Constraint validation

When the user agent is required to statically validate the constraints of form element form, it must run the following steps, which return either a positive result (all the controls in the form are valid) or a negative result (there are invalid controls) along with a (possibly empty) list of elements that are invalid and for which no script has claimed responsibility:

  1. Let controls be a list of all the submittable elements whose form owner is form, in tree order.

  2. Let invalid controls be an initially empty list of elements.

  3. For each element field in controls, in tree order:

    1. If field is not a candidate for constraint validation, then move on to the next element.

    2. Otherwise, if field satisfies its constraints, then move on to the next element.

    3. Otherwise, add field to invalid controls.

  4. If invalid controls is empty, then return a positive result.

  5. Let unhandled invalid controls be an initially empty list of elements.

  6. For each element field in invalid controls, if any, in tree order:

    1. Let notCanceled be the result of firing an event named invalid at field, with the cancelable attribute initialized to true.

    2. If notCanceled is true, then add field to unhandled invalid controls.

  7. Return a negative result with the list of elements in the unhandled invalid controls list.

If a user agent is to interactively validate the constraints of form element form, then the user agent must run the following steps:

  1. Statically validate the constraints of form, and let unhandled invalid controls be the list of elements returned if the result was negative.

  2. If the result was positive, then return that result.

  3. Report the problems with the constraints of at least one of the elements given in unhandled invalid controls to the user.

  4. Return a negative result.

4.10.20.3 The constraint validation API
element . willValidate

HTMLObjectElement/willValidate

Support in all current engines.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns true if the element will be validated when the form is submitted; false otherwise.

element . setCustomValidity(message)

HTMLObjectElement/setCustomValidity

Support in all current engines.

Firefox4+Safari5.1+Chrome10+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

HTMLSelectElement/setCustomValidity

Support in all current engines.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Sets a custom error, so that the element would fail to validate. The given message is the message to be shown to the user when reporting the problem to the user.

If the argument is the empty string, clears the custom error.

element . validity . valueMissing

Returns true if the element has no value but is a required field; false otherwise.

element . validity . typeMismatch

Returns true if the element's value is not in the correct syntax; false otherwise.

element . validity . patternMismatch

Returns true if the element's value doesn't match the provided pattern; false otherwise.

element . validity . tooLong

ValidityState/tooLong

Support in all current engines.

Firefox4+Safari5+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android64+Safari iOS5+Chrome Android18+WebView Android4+Samsung Internet1.0+Opera Android12.1+

Returns true if the element's value is longer than the provided maximum length; false otherwise.

element . validity . tooShort

ValidityState/tooShort

Support in all current engines.

Firefox51+Safari10+Chrome40+
Opera27+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android64+Safari iOS10+Chrome Android40+WebView Android67+Samsung Internet4.0+Opera Android27+

Returns true if the element's value, if it is not the empty string, is shorter than the provided minimum length; false otherwise.

element . validity . rangeUnderflow

Returns true if the element's value is lower than the provided minimum; false otherwise.

element . validity . rangeOverflow

Returns true if the element's value is higher than the provided maximum; false otherwise.

element . validity . stepMismatch

Returns true if the element's value doesn't fit the rules given by the step attribute; false otherwise.

element . validity . badInput

ValidityState/badInput

Support in all current engines.

Firefox29+Safari7+Chrome25+
Opera15+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android64+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android14+

Returns true if the user has provided input in the user interface that the user agent is unable to convert to a value; false otherwise.

element . validity . customError

Returns true if the element has a custom error; false otherwise.

element . validity . valid

Returns true if the element's value has no validity problems; false otherwise.

valid = element . checkValidity()

HTMLObjectElement/checkValidity

Support in all current engines.

Firefox4+Safari5.1+Chrome10+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

HTMLSelectElement/checkValidity

Support in all current engines.

Firefox4+Safari5+Chrome4+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

Returns true if the element's value has no validity problems; false otherwise. Fires an invalid event at the element in the latter case.

valid = element . reportValidity()

HTMLFormElement/reportValidity

Support in all current engines.

Firefox49+Safari10.1+Chrome40+
Opera27+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android49+Safari iOS10.3+Chrome Android40+WebView Android40+Samsung Internet4.0+Opera Android27+

HTMLInputElement/reportValidity

Support in all current engines.

Firefox49+Safari10.1+Chrome40+
Opera27+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android64+Safari iOS10.3+Chrome Android40+WebView Android40+Samsung Internet4.0+Opera Android27+

Returns true if the element's value has no validity problems; otherwise, returns false, fires an invalid event at the element, and (if the event isn't canceled) reports the problem to the user.

element . validationMessage

HTMLObjectElement/validationMessage

Support in all current engines.

Firefox4+Safari5.1+Chrome10+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the error message that would be shown to the user if the element was to be checked for validity.

The willValidate attribute's getter must return true, if this element is a candidate for constraint validation, and false otherwise (i.e., false if any conditions are barring it from constraint validation).

ElementInternals/willValidate

Firefox98+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOSNoChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

The willValidate attribute of ElementInternals interface, on getting, must throw a "NotSupportedError" DOMException if the target element is not a form-associated custom element. Otherwise, it must return true if the target element is a candidate for constraint validation, and false otherwise.

HTMLInputElement/setCustomValidity

Support in all current engines.

Firefox4+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The setCustomValidity(message) method, when invoked, must set the custom validity error message to message.

In the following example, a script checks the value of a form control each time it is edited, and whenever it is not a valid value, uses the setCustomValidity() method to set an appropriate message.

<label>Feeling: <input name=f type="text" oninput="check(this)"></label>
<script>
 function check(input) {
   if (input.value == "good" ||
       input.value == "fine" ||
       input.value == "tired") {
     input.setCustomValidity('"' + input.value + '" is not a feeling.');
   } else {
     // input is fine -- reset the error message
     input.setCustomValidity('');
   }
 }
</script>

HTMLObjectElement/validity

Support in all current engines.

Firefox4+Safari5.1+Chrome10+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The validity attribute's getter must return a ValidityState object that represents the validity states of this element. This object is live.

ElementInternals/validity

Firefox98+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOSNoChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

The validity attribute of ElementInternals interface, on getting, must throw a "NotSupportedError" DOMException if the target element is not a form-associated custom element. Otherwise, it must return a ValidityState object that represents the validity states of the target element. This object is live.

[Exposed=Window]
interface ValidityState {
  readonly attribute boolean valueMissing;
  readonly attribute boolean typeMismatch;
  readonly attribute boolean patternMismatch;
  readonly attribute boolean tooLong;
  readonly attribute boolean tooShort;
  readonly attribute boolean rangeUnderflow;
  readonly attribute boolean rangeOverflow;
  readonly attribute boolean stepMismatch;
  readonly attribute boolean badInput;
  readonly attribute boolean customError;
  readonly attribute boolean valid;
};

A ValidityState object has the following attributes. On getting, they must return true if the corresponding condition given in the following list is true, and false otherwise.

valueMissing

The control is suffering from being missing.

typeMismatch

ValidityState/typeMismatch

Support in all current engines.

Firefox4+Safari5+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The control is suffering from a type mismatch.

patternMismatch

ValidityState/patternMismatch

Support in all current engines.

Firefox4+Safari5+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The control is suffering from a pattern mismatch.

tooLong

The control is suffering from being too long.

tooShort

The control is suffering from being too short.

rangeUnderflow

ValidityState/rangeUnderflow

Support in all current engines.

Firefox4+Safari5+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The control is suffering from an underflow.

rangeOverflow

ValidityState/rangeOverflow

Support in all current engines.

Firefox4+Safari5+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The control is suffering from an overflow.

stepMismatch

ValidityState/stepMismatch

Support in all current engines.

Firefox4+Safari5+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The control is suffering from a step mismatch.

badInput

The control is suffering from bad input.

customError

The control is suffering from a custom error.

valid

None of the other conditions are true.

The check validity steps for an element element are:

  1. If element is a candidate for constraint validation and does not satisfy its constraints, then:

    1. Fire an event named invalid at element, with the cancelable attribute initialized to true (though canceling has no effect).

    2. Return false.

  2. Return true.

The checkValidity() method, when invoked, must run the check validity steps on this element.

ElementInternals/checkValidity

Firefox98+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOSNoChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

The checkValidity() method of the ElementInternals interface must run these steps:

  1. Let element be this ElementInternals's target element.

  2. If element is not a form-associated custom element, then throw a "NotSupportedError" DOMException.

  3. Run the check validity steps on element.

The report validity steps for an element element are:

  1. If element is a candidate for constraint validation and does not satisfy its constraints, then:

    1. Let report be the result of firing an event named invalid at element, with the cancelable attribute initialized to true.

    2. If report is true, then report the problems with the constraints of this element to the user. When reporting the problem with the constraints to the user, the user agent may run the focusing steps for element, and may change the scrolling position of the document, or perform some other action that brings element to the user's attention. User agents may report more than one constraint violation, if element suffers from multiple problems at once. If element is not being rendered, then the user agent may, instead of notifying the user, report the error for the running script.

    3. Return false.

  2. Return true.

The reportValidity() method, when invoked, must run the report validity steps on this element.

ElementInternals/reportValidity

Firefox98+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOSNoChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

The reportValidity() method of the ElementInternals interface must run these steps:

  1. Let element be this ElementInternals's target element.

  2. If element is not a form-associated custom element, then throw a "NotSupportedError" DOMException.

  3. Run the report validity steps on element.

The validationMessage attribute's getter must run these steps:

  1. If this element is not a candidate for constraint validation or if this element satisfies its constraints, then return the empty string.

  2. Return a suitably localized message that the user agent would show the user if this were the only form control with a validity constraint problem. If the user agent would not actually show a textual message in such a situation (e.g., it would show a graphical cue instead), then return a suitably localized message that expresses (one or more of) the validity constraint(s) that the control does not satisfy. If the element is a candidate for constraint validation and is suffering from a custom error, then the custom validity error message should be present in the return value.

4.10.20.4 安全性

服务器不应依赖客户端验证。恶意用户可以轻松绕过客户端验证, 没实现这些功能的旧的用户代理或自动化工具也会让用户无意地绕过客户端验证。 约束验证功能只是为了提升用户体验,并未提供任何安全机制。

4.10.21 表单提交

4.10.21.1 概述

This section is non-normative.

提交表单时,表单中的数据会转换为 enctype 指定的结构, 然后使用给定的 method 发送到 action 指定的目的地址。

例如下面的表单:

<form action="/find.cgi" method=get>
 <input type=text name=t>
 <input type=search name=q>
 <input type=submit>
</form>

如果用户在第一个字段输入 "cats",在第二个字段输入 "fur",然后点击提交按钮, 那么用户代理就会加载 /find.cgi?t=cats&q=fur

另一方面考虑这个表单:

<form action="/find.cgi" method=post enctype="multipart/form-data">
 <input type=text name=t>
 <input type=search name=q>
 <input type=submit>
</form>

给同样的用户输入,提交的结果会非常不同:用户代理会发一个 HTTP POST 请求到给定的 URL,消息体是像这样的文本:

------kYFrd4jNJEgCervE
Content-Disposition: form-data; name="t"

cats
------kYFrd4jNJEgCervE
Content-Disposition: form-data; name="q"

fur
------kYFrd4jNJEgCervE--
4.10.21.2 隐式提交

form 元素的 默认按钮表单 owner 是这个 form 元素的 按照 树序 的第一个 提交按钮

如果用户代理支持用户隐式地提交表单(例如在某些平台下当文本控件 获得焦点 时按下回车键就会暗示提交表单), 然后如果表单的 默认按钮激活行为 且不处于 禁用状态 就必须提交表单, 而且用户代理就必须在那个 默认按钮触发一个 click 事件

Web 上有些页面只有在隐式提交表单时才可用,因此强烈建议用户代理支持此功能。

对于表单没有 提交按钮 的情况,如果多个字段 阻止了隐式提交, 那么隐式提交机制必须什么都不做; 否则用户代理必须从 form 元素自己 提交 form 元素。

上一段中,form 元素中 阻止隐式提交 的元素是指, 表单 ownerform 元素 的 type 属性处于以下状态的 input 元素: Text, Search, URL, Telephone, E-mail, Password, Date, Month, Week, Time, Local Date and Time, Number

4.10.21.3 Form submission algorithm

Each form element has a constructing entry list boolean, initially false.

Each form element has a firing submission events boolean, initially false.

When a form element form is submitted from an element submitter (typically a button), optionally with a submitted from submit() method flag set, the user agent must run the following steps:

  1. If form cannot navigate, then return.

  2. If form's constructing entry list is true, then return.

  3. Let form document be form's node document.

  4. If form document's active sandboxing flag set has its sandboxed forms browsing context flag set, then return.

  5. Let form browsing context be the browsing context of form document.

  6. If the submitted from submit() method flag is not set, then:

    1. If form's firing submission events is true, then return.

    2. Set form's firing submission events to true.

    3. If the submitter element's no-validate state is false, then interactively validate the constraints of form and examine the result. If the result is negative (i.e., the constraint validation concluded that there were invalid fields and probably informed the user of this), then:

      1. Set form's firing submission events to false.

      2. Return.

    4. Let submitterButton be null if submitter is form. Otherwise, let submitterButton be submitter.

    5. Let continue be the result of firing an event named submit at form using SubmitEvent, with the submitter attribute initialized to submitterButton, the bubbles attribute initialized to true, and the cancelable attribute initialized to true.

    6. Set form's firing submission events to false.

    7. If continue is false, then return.

    8. If form cannot navigate, then return.

      Cannot navigate is run again as dispatching the submit event could have changed the outcome.

  7. Let encoding be the result of picking an encoding for the form.

  8. Let entry list be the result of constructing the entry list with form, submitter, and encoding.

  9. If form cannot navigate, then return.

    Cannot navigate is run again as dispatching the formdata event in constructing the entry list could have changed the outcome.

  10. Let action be the submitter element's action.

  11. If action is the empty string, let action be the URL of the form document.

  12. Parse the URL action, relative to the submitter element's node document. If this fails, return.

  13. Let parsed action be the resulting URL record.

  14. Let scheme be the scheme of parsed action.

  15. Let enctype be the submitter element's enctype.

  16. Let method be the submitter element's method.

  17. Let target be the submitter element's formtarget attribute value, if the element is a submit button and has such an attribute. Otherwise, let it be the result of getting an element's target given submitter's form owner.

  18. Let noopener be the result of getting an element's noopener with form and targetAttributeValue.

  19. Let target browsing context and windowType be the result of applying the rules for choosing a browsing context using target, form browsing context, and noopener.

  20. Let historyHandling be "replace" if windowType is either "new and unrestricted" or "new with no opener"; otherwise "default".

  21. If target browsing context is null, then return.

  22. If form document has not yet completely loaded and the submitted from submit() method flag is set, then set historyHandling to "replace".

  23. If the value of method is dialog then jump to the submit dialog steps.

    Otherwise, select the appropriate row in the table below based on the value of scheme as given by the first cell of each row. Then, select the appropriate cell on that row based on the value of method as given in the first cell of each column. Then, jump to the steps named in that cell and defined below the table.

    GET POST
    http Mutate action URL Submit as entity body
    https Mutate action URL Submit as entity body
    ftp Get action URL Get action URL
    javascript Get action URL Get action URL
    data Mutate action URL Get action URL
    mailto Mail with headers Mail as body

    If scheme is not one of those listed in this table, then the behavior is not defined by this specification. User agents should, in the absence of another specification defining this, act in a manner analogous to that defined in this specification for similar schemes.

    Each form element has a planned navigation, which is either null or a task; when the form is first created, its planned navigation must be set to null. In the behaviors described below, when the user agent is required to plan to navigate to a particular resource destination, it must run the following steps:

    1. If destination is not a request, then set destination to a new request whose URL is destination.

    2. If the form element's link types include the noreferrer keyword, then set destination's referrer to "no-referrer".

    3. If the form has a non-null planned navigation, remove it from its task queue.

    4. Queue an element task on the DOM manipulation task source given the form element and the following steps:

      1. Set the form's planned navigation to null.

      2. Navigate target browsing context to destination, with historyHandling set to historyHandling and navigationType set to "form-submission".

    5. Set the form's planned navigation to the just-queued task.

    The behaviors are as follows:

    Mutate action URL

    Let query be the result of running the application/x-www-form-urlencoded serializer with entry list and encoding.

    Set parsed action's query component to query.

    Plan to navigate to parsed action.

    Submit as entity body

    Switch on enctype:

    application/x-www-form-urlencoded

    Let body be the result of running the application/x-www-form-urlencoded serializer with entry list and encoding.

    Set body to the result of encoding body.

    Let MIME type be "application/x-www-form-urlencoded".

    multipart/form-data

    Let body be the result of running the multipart/form-data encoding algorithm with entry list and encoding.

    Let MIME type be the concatenation of the string "multipart/form-data;", a U+0020 SPACE character, the string "boundary=", and the multipart/form-data boundary string generated by the multipart/form-data encoding algorithm.

    text/plain

    Let body be the result of running the text/plain encoding algorithm with entry list.

    Set body to the result of encoding body using encoding.

    Let MIME type be "text/plain".

    Plan to navigate to a new request whose url is parsed action, method is method, header list consists of `Content-Type`/MIME type, and body is body.

    Get action URL

    Plan to navigate to parsed action.

    entry list is discarded.

    Mail with headers

    Let headers be the result of running the application/x-www-form-urlencoded serializer with entry list and encoding.

    Replace occurrences of U+002B PLUS SIGN characters (+) in headers with the string "%20".

    Set parsed action's query to headers.

    Plan to navigate to parsed action.

    Mail as body

    Switch on enctype:

    text/plain

    Let body be the result of running the text/plain encoding algorithm with entry list.

    Set body to the result of running UTF-8 percent-encode on body using the default encode set. [URL]

    Otherwise

    Let body be the result of running the application/x-www-form-urlencoded serializer with entry list and encoding.

    If parsed action's query is null, then set it to the empty string.

    If parsed action's query is not the empty string, then append a single U+0026 AMPERSAND character (&) to it.

    Append "body=" to parsed action's query.

    Append body to parsed action's query.

    Plan to navigate to parsed action.

    Submit dialog

    Let subject be the nearest ancestor dialog element of form, if any.

    If there isn't one, or if it does not have an open attribute, do nothing. Otherwise, proceed as follows:

    If submitter is an input element whose type attribute is in the Image Button state, then let result be the string formed by concatenating the selected coordinate's x-component, expressed as a base-ten number using ASCII digits, a U+002C COMMA character (,), and the selected coordinate's y-component, expressed in the same way as the x-component.

    Otherwise, if submitter has a value, then let result be that value.

    Otherwise, there is no result.

    Then, close the dialog subject. If there is a result, let that be the return value.

4.10.21.4 Constructing the entry list

The algorithm to construct the entry list given a form, an optional submitter, and an optional encoding, is as follows. If not specified otherwise, submitter is null.

  1. If form's constructing entry list is true, then return null.

  2. Set form's constructing entry list to true.

  3. Let controls be a list of all the submittable elements whose form owner is form, in tree order.

  4. Let entry list be a new empty list of entries.

  5. For each element field in controls, in tree order:

    1. If any of the following is true:

      Then continue.

    2. If the field element is an input element whose type attribute is in the Image Button state, then:

      1. If the field element has a name attribute specified and its value is not the empty string, let name be that value followed by a single U+002E FULL STOP character (.). Otherwise, let name be the empty string.

      2. Let namex be the string consisting of the concatenation of name and a single U+0078 LATIN SMALL LETTER X character (x).

      3. Let namey be the string consisting of the concatenation of name and a single U+0079 LATIN SMALL LETTER Y character (y).

      4. The field element is submitter, and before this algorithm was invoked the user indicated a coordinate. Let x be the x-component of the coordinate selected by the user, and let y be the y-component of the coordinate selected by the user.

      5. Append an entry to entry list with namex and x.

      6. Append an entry to entry list with namey and y.

      7. Continue.

    3. If the field is a form-associated custom element, then perform the entry construction algorithm given field and entry list, then continue.

    4. If either the field element does not have a name attribute specified, or its name attribute's value is the empty string, then continue.

    5. Let name be the value of the field element's name attribute.

    6. If the field element is a select element, then for each option element in the select element's list of options whose selectedness is true and that is not disabled, append an entry to entry list with name and the value of the option element.

    7. Otherwise, if the field element is an input element whose type attribute is in the Checkbox state or the Radio Button state, then:

      1. If the field element has a value attribute specified, then let value be the value of that attribute; otherwise, let value be the string "on".

      2. Append an entry to entry list with name and value.

    8. Otherwise, if the field element is an input element whose type attribute is in the File Upload state, then:

      1. If there are no selected files, then append an entry to entry list with name and a new File object with an empty name, application/octet-stream as type, and an empty body.

      2. Otherwise, for each file in selected files, append an entry to entry list with name and a File object representing the file.

    9. Otherwise, if the field element is an object element: try to obtain a form submission value from the plugin, and if that is successful, append an entry to entry list with name and the returned form submission value.

    10. Otherwise, if the field element is an input element whose type attribute is in the Hidden state and name is an ASCII case-insensitive match for "_charset_":

      1. Let charset be the name of encoding if encoding is given, and "UTF-8" otherwise.

      2. Append an entry to entry list with name and charset.

    11. Otherwise, if the field element is a textarea element, append an entry to entry list with name and the value of the field element, and the prevent line break normalization flag set.

      In the case of the value of textarea elements, the line break normalization is already performed during the conversion of the control's raw value into the control's value (which also performs any necessary line wrapping).

    12. Otherwise, append an entry to entry list with name and the value of the field element.

    13. If the element has a dirname attribute, and that attribute's value is not the empty string, then:

      1. Let dirname be the value of the element's dirname attribute.

      2. Let dir be the string "ltr" if the directionality of the element is 'ltr', and "rtl" otherwise (i.e., when the directionality of the element is 'rtl').

      3. Append an entry to entry list with dirname and dir.

      An element can only have a dirname attribute if it is a textarea element or an input element whose type attribute is in either the Text state or the Search state.

  6. Let form data be a new FormData object associated with entry list.

  7. Fire an event named formdata at form using FormDataEvent, with the formData attribute initialized to form data and the bubbles attribute initialized to true.

  8. Set form's constructing entry list to false.

  9. Return a clone of entry list.

To append an entry to entry list, given name, value, and optional prevent line break normalization flag, run these steps:

  1. For name, replace every occurrence of U+000D (CR) not followed by U+000A (LF), and every occurrence of U+000A (LF) not preceded by U+000D (CR), by a string consisting of a U+000D (CR) and U+000A (LF).

  2. Replace name with the result of converting to a sequence of Unicode scalar values.

  3. If value is not a File object, then:

    1. If the prevent line break normalization flag is unset, then replace every occurrence of U+000D (CR) not followed by U+000A (LF), and every occurrence of U+000A (LF) not preceded by U+000D (CR) in value, by a string consisting of a U+000D (CR) and U+000A (LF).

    2. Replace value with the result of converting to a sequence of Unicode scalar values.

  4. Create an entry with name and value, and append it to entry list.

4.10.21.5 Selecting a form submission encoding

If the user agent is to pick an encoding for a form, it must run the following steps:

  1. Let encoding be the document's character encoding.

  2. If the form element has an accept-charset attribute, set encoding to the return value of running these substeps:

    1. Let input be the value of the form element's accept-charset attribute.

    2. Let candidate encoding labels be the result of splitting input on ASCII whitespace.

    3. Let candidate encodings be an empty list of character encodings.

    4. For each token in candidate encoding labels in turn (in the order in which they were found in input), get an encoding for the token and, if this does not result in failure, append the encoding to candidate encodings.

    5. If candidate encodings is empty, return UTF-8.

    6. Return the first encoding in candidate encodings.

  3. Return the result of getting an output encoding from encoding.

4.10.21.6 URL 编码的表单数据

application/x-www-form-urlencoded 的细节请参考 WHATWG URL 标准。[URL]

4.10.21.7 Multipart form data

The multipart/form-data encoding algorithm, given an entry list and encoding, is as follows:

  1. Let result be the empty string.

  2. For each entry in entry list:

    1. For each character in the entry's name and value that cannot be expressed using the selected character encoding, replace the character by a string consisting of a U+0026 AMPERSAND character (&), a U+0023 NUMBER SIGN character (#), one or more ASCII digits representing the code point of the character in base ten, and finally a U+003B (;).

  3. Encode the (now mutated) entry list using the rules described by RFC 7578, Returning Values from Forms: multipart/form-data, and return the resulting byte stream. [RFC7578]

    Each entry in entry list is a field, the name of the entry is the field name and the value of the entry is the field value.

    The order of parts must be the same as the order of fields in entry list. Multiple entries with the same name must be treated as distinct fields.

    The parts of the generated multipart/form-data resource that correspond to non-file fields must not have a `Content-Type` header specified. Their names and values must be encoded using the character encoding selected above.

    File names included in the generated multipart/form-data resource (as part of file fields) must use the character encoding selected above, though the precise name may be approximated if necessary (e.g. newlines could be removed from file names, quotes could be changed to "%22", and characters not expressible in the selected character encoding could be replaced by other characters).

    The boundary used by the user agent in generating the return value of this algorithm is the multipart/form-data boundary string. (This value is used to generate the MIME type of the form submission payload generated by this algorithm.)

For details on how to interpret multipart/form-data payloads, see RFC 7578. [RFC7578]

4.10.21.8 Plain text form data

The text/plain encoding algorithm, given an entry list, is as follows:

  1. Let result be the empty string.

  2. For each entry in entry list:

    1. If the entry's value is a File object, then set its value to the File object's name.

    2. Append the entry's name to result.

    3. Append a single U+003D EQUALS SIGN character (=) to result.

    4. Append the entry's value to result.

    5. Append a U+000D CARRIAGE RETURN (CR) U+000A LINE FEED (LF) character pair to result.

  3. Return result.

Payloads using the text/plain format are intended to be human readable. They are not reliably interpretable by computer, as the format is ambiguous (for example, there is no way to distinguish a literal newline in a value from the newline at the end of the value).

4.10.21.9 The SubmitEvent interface

SubmitEvent

Support in all current engines.

Firefox75+Safari15+Chrome81+
Opera68+Edge81+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS15+Chrome Android81+WebView Android81+Samsung Internet13.0+Opera Android58+

SubmitEvent/SubmitEvent

Support in all current engines.

Firefox75+Safari15+Chrome81+
Opera68+Edge81+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS15+Chrome Android81+WebView Android81+Samsung Internet13.0+Opera Android58+
[Exposed=Window]
interface SubmitEvent : Event {
  constructor(DOMString type, optional SubmitEventInit eventInitDict = {});

  readonly attribute HTMLElement? submitter;
};

dictionary SubmitEventInit : EventInit {
  HTMLElement? submitter = null;
};
event . submitter

Returns the element representing the submit button that triggered the form submission, or null if the submission was not triggered by a button.

The submitter attribute must return the value it was initialized to.

4.10.21.10 The FormDataEvent interface

FormDataEvent/FormDataEvent

Support in all current engines.

Firefox72+Safari15+Chrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS15+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

FormDataEvent

Support in all current engines.

Firefox72+Safari15+Chrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS15+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+
[Exposed=Window]
interface FormDataEvent : Event {
  constructor(DOMString type, FormDataEventInit eventInitDict);

  readonly attribute FormData formData;
};

dictionary FormDataEventInit : EventInit {
  required FormData formData;
};
event . formData

Returns a FormData object representing names and values of elements associated to the target form. Operations on the FormData object will affect form data to be submitted.

The formData attribute must return the value it was initialized to. It represents a FormData object associated to the entry list that is constructed when the form is submitted.

4.10.22 表单重置

重置 form 元素 form 时,要执行这些步骤:

  1. form触发一个 名为 reset 的事件, 其 bubblescancelable 属性初始化为 true, 令 reset 为上述触发事件操作的结果。

  2. 如果 reset 为 true,就调用每个 表单 ownerform可重置元素重置算法

每个 可重置元素 定义了它自己的 重置算法。 这些算法中对表单控件的改变,不计为用户引起的改变 (因此,不会引发 input 事件)。

4.11 Interactive elements

4.11.1 The details element

Element/details

Support in all current engines.

Firefox49+Safari6+Chrome12+
Opera15+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android49+Safari iOS6+Chrome AndroidYesWebView AndroidYesSamsung InternetYesOpera Android14+

HTMLDetailsElement

Support in all current engines.

Firefox49+Safari6+Chrome10+
Opera15+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android49+Safari iOS6+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
Categories:
Flow content.
Sectioning root.
Interactive content.
Palpable content.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
One summary element followed by flow content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
open — Whether the details are visible
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLDetailsElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean open;
};

The details element represents a disclosure widget from which the user can obtain additional information or controls.

The details element is not appropriate for footnotes. Please see the section on footnotes for details on how to mark up footnotes.

The first summary element child of the element, if any, represents the summary or legend of the details. If there is no child summary element, the user agent should provide its own legend (e.g. "Details").

The rest of the element's contents represents the additional information or controls.

The open content attribute is a boolean attribute. If present, it indicates that both the summary and the additional information is to be shown to the user. If the attribute is absent, only the summary is to be shown.

When the element is created, if the attribute is absent, the additional information should be hidden; if the attribute is present, that information should be shown. Subsequently, if the attribute is removed, then the information should be hidden; if the attribute is added, the information should be shown.

The user agent should allow the user to request that the additional information be shown or hidden. To honor a request for the details to be shown, the user agent must set the open attribute on the element to the empty string. To honor a request for the information to be hidden, the user agent must remove the open attribute from the element.

This ability to request that additional information be shown or hidden may simply be the activation behavior of the appropriate summary element, in the case such an element exists. However, if no such element exists, user agents can still provide this ability through some other user interface affordance.

Whenever the open attribute is added to or removed from a details element, the user agent must queue an element task on the DOM manipulation task source given then details element that runs the following steps, which are known as the details notification task steps, for this details element:

  1. If another task has been queued to run the details notification task steps for this details element, then return.

    When the open attribute is toggled several times in succession, these steps essentially get coalesced so that only one event is fired.

  2. Fire an event named toggle at the details element.

The open IDL attribute must reflect the open content attribute.

The following example shows the details element being used to hide technical details in a progress report.

<section class="progress window">
 <h1>Copying "Really Achieving Your Childhood Dreams"</h1>
 <details>
  <summary>Copying... <progress max="375505392" value="97543282"></progress> 25%</summary>
  <dl>
   <dt>Transfer rate:</dt> <dd>452KB/s</dd>
   <dt>Local filename:</dt> <dd>/home/rpausch/raycd.m4v</dd>
   <dt>Remote filename:</dt> <dd>/var/www/lectures/raycd.m4v</dd>
   <dt>Duration:</dt> <dd>01:16:27</dd>
   <dt>Color profile:</dt> <dd>SD (6-1-6)</dd>
   <dt>Dimensions:</dt> <dd>320×240</dd>
  </dl>
 </details>
</section>

The following shows how a details element can be used to hide some controls by default:

<details>
 <summary><label for=fn>Name & Extension:</label></summary>
 <p><input type=text id=fn name=fn value="Pillar Magazine.pdf">
 <p><label><input type=checkbox name=ext checked> Hide extension</label>
</details>

One could use this in conjunction with other details in a list to allow the user to collapse a set of fields down to a small set of headings, with the ability to open each one.

In these examples, the summary really just summarizes what the controls can change, and not the actual values, which is less than ideal.

Because the open attribute is added and removed automatically as the user interacts with the control, it can be used in CSS to style the element differently based on its state. Here, a style sheet is used to animate the color of the summary when the element is opened or closed:

<style>
 details > summary { transition: color 1s; color: black; }
 details[open] > summary { color: red; }
</style>
<details>
 <summary>Automated Status: Operational</summary>
 <p>Velocity: 12m/s</p>
 <p>Direction: North</p>
</details>

4.11.2 The summary element

Element/summary

Support in all current engines.

Firefox49+Safari6+Chrome12+
Opera15+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android49+Safari iOSYesChrome AndroidYesWebView Android4+Samsung InternetYesOpera Android14+
Categories:
None.
Contexts in which this element can be used:
As the first child of a details element.
Content model:
Phrasing content, optionally intermixed with heading content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
Uses HTMLElement.

The summary element represents a summary, caption, or legend for the rest of the contents of the summary element's parent details element, if any.

A summary element is a summary for its parent details if the following algorithm returns true:

  1. If this summary element has no parent, then return false.

  2. Let parent be this summary element's parent.

  3. If parent is not a details element, then return false.

  4. If parent's first summary element child is not this summary element, then return false.

  5. Return true.

The activation behavior of summary elements is to run the following steps:

  1. If this summary element is not the summary for its parent details, then return.

  2. Let parent be this summary element's parent.

  3. If the open attribute is present on parent, then remove it. Otherwise, set parent's open attribute to the empty string.

    This will then run the details notification task steps.

4.11.3 命令

4.11.3.1 Facets

A command is the abstraction behind menu items, buttons, and links. Once a command is defined, other parts of the interface can refer to the same command, allowing many access points to a single feature to share facets such as the Disabled State.

Commands are defined to have the following facets:

Label
The name of the command as seen by the user.
Access Key
A key combination selected by the user agent that triggers the command. A command might not have an Access Key.
Hidden State
Whether the command is hidden or not (basically, whether it should be shown in menus).
Disabled State
Whether the command is relevant and can be triggered or not.
Action
The actual effect that triggering the command will have. This could be a scripted event handler, a URL to which to navigate, or a form submission.

User agents may expose the commands that match the following criteria:

User agents are encouraged to do this especially for commands that have Access Keys, as a way to advertise those keys to the user.

For example, such commands could be listed in the user agent's menu bar.

4.11.3.2 使用 a 元素来定义命令

href 属性的 a 元素 会定义命令

这个命令的 Label 是该元素的 textContent IDL 属性给出的字符串。

这个命令的 AccessKey 是该元素 被指定的访问键,如果有的话。

如果这个元素有 hidden 属性, 它的 Hidden State 就是 true(隐藏), 否则是 false。

如果这个元素或它的一个祖先是 不活动的, 那么这个命令的 Disabled State 就是 true, 否则是 false。

这个命令的 Action 会在这个元素上 触发一个 click 事件

4.11.3.3 使用 button 元素来定义命令

button 元素总会 定义一个命令

这个命令的 Label, Access Key, Hidden StateAction 的确定方式与 a 元素 相同(参考前一章)。

如果这个元素或它的一个祖先是 不活动的, 或者设置了这个元素的 disabled 状态, 那么这个命令的 Disabled State 就是 true, 否则是 false。

4.11.3.4 使用 input 元素来定义命令

type 属性处于 Submit Button, Reset Button, Image Button, Button, Radio Button, 或 Checkbox 状态之一的 input 元素 定义了命令

这个命令的 Label 按如下过程确定:

这个命令的 AccessKey 就是这个元素 被指定的访问键(如果有的话)。

如果这个元素有 hidden 属性, 它的 Hidden State 就是 true(隐藏), 否则是 false。

如果这个元素或它的一个祖先是 不活动的, 或者设置了这个元素的 disabled 状态, 那么这个命令的 Disabled State 就是 true, 否则是 false。

这个命令的 Action 会在这个元素上 触发一个 click 事件

4.11.3.5 Using the option element to define a command

An option element with an ancestor select element and either no value attribute or a value attribute that is not the empty string defines a command.

The Label of the command is the value of the option element's label attribute, if there is one, or else the option element's descendant text content, with ASCII whitespace stripped and collapsed.

The Access Key of the command is the element's assigned access key, if any.

The Hidden State of the command is true (hidden) if the element has a hidden attribute, and false otherwise.

The Disabled State of the command is true if the element is disabled, or if its nearest ancestor select element is disabled, or if it or one of its ancestors is inert, and false otherwise.

If the option's nearest ancestor select element has a multiple attribute, the Action of the command is to toggle the option element. Otherwise, the Action is to pick the option element.

4.11.3.6legend 元素上 使用 accesskey 属性 来定义一个命令

指定的访问键legend 元素, 如果其祖先 fieldset 元素有一个不是 labellegend 的后代元素(而且不是 legend 元素的后代元素),而且这个后代元素 定义了一个命令,那么这个 legend 元素就 定义了一个命令

命令的 Label 是该元素的 textContent IDL 属性给出的字符串。

命令的 AccessKey 是该元素的 指定的访问键

命令的 Hidden State, Disabled StateActionlegend 元素的父元素的 按照树序 的第一个 定义了命令 的, 而且不是 legend 元素的后代,也不是 labellegend 元素的, 后代元素的相应属性相同。

4.11.3.7 使用 accesskey 属性给其他元素定义命令

指定的访问键 的元素 定义了一个命令

如果前面的章节中定义了一个元素 会定义命令, 那么应该遵循对应章节的定义,并忽略本小节。否则,本小节就适用于那个元素。

命令的 Label 取决于元素本身。 如果该元素是 有标签的控件, 那么 Label 就是给这个控件 打标签label 元素中, 按照 树序 的第一个元素的 textContent 给出的字符串。 (在 DOM 术语中,这个字符串就是 element.labels[0].textContent)。 否则 Label 就是元素自己的 textContent

命令的 AccessKey 就是元素的 被指定的访问键

如果这个元素有 hidden 属性, 它的 Hidden State 就是 true(隐藏), 否则是 false。

如果这个元素或它的一个祖先是 不活动的, 那么这个命令的 Disabled State 就是 true, 否则是 false。

这个命令的 Action 是执行以下步骤:

  1. 为这个元素执行 聚焦步骤
  2. 在这个元素上 触发一个 click 事件

4.11.4 The dialog element

Element/dialog

Support in all current engines.

Firefox98+Safari15.4+Chrome37+
Opera24+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOS15.4+Chrome Android37+WebView Android37+Samsung Internet3.0+Opera Android24+

HTMLDialogElement

Support in all current engines.

Firefox98+Safari15.4+Chrome37+
Opera24+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOS15.4+Chrome Android37+WebView Android37+Samsung Internet3.0+Opera Android24+
Categories:
Flow content.
Sectioning root.
Contexts in which this element can be used:
Where flow content is expected.
Content model:
Flow content.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
open — Whether the dialog box is showing
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLDialogElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean open;
  attribute DOMString returnValue;
  [CEReactions] undefined show();
  [CEReactions] undefined showModal();
  [CEReactions] undefined close(optional DOMString returnValue);
};

The dialog element represents a part of an application that a user interacts with to perform a task, for example a dialog box, inspector, or window.

The open attribute is a boolean attribute. When specified, it indicates that the dialog element is active and that the user can interact with it.

A dialog element without an open attribute specified should not be shown to the user. This requirement may be implemented indirectly through the style layer. For example, user agents that support the suggested default rendering implement this requirement using the CSS rules described in the rendering section.

Removing the open attribute will usually hide the dialog. However, doing so has a number of strange additional consequences:

For these reasons, it is generally better to never remove the open attribute manually. Instead, use the close() method to close the dialog, or the hidden attribute to hide it.

The tabindex attribute must not be specified on dialog elements.

dialog . show()

HTMLDialogElement/show

Support in all current engines.

Firefox98+Safari15.4+Chrome37+
Opera24+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOS15.4+Chrome Android37+WebView Android37+Samsung Internet3.0+Opera Android24+

Displays the dialog element.

dialog . showModal()

HTMLDialogElement/showModal

Support in all current engines.

Firefox98+Safari15.4+Chrome37+
Opera24+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOS15.4+Chrome Android37+WebView Android37+Samsung Internet3.0+Opera Android24+

Displays the dialog element and makes it the top-most modal dialog.

This method honors the autofocus attribute.

dialog . close( [ result ] )

HTMLDialogElement/close

Support in all current engines.

Firefox98+Safari15.4+Chrome37+
Opera24+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOS15.4+Chrome Android37+WebView Android37+Samsung Internet3.0+Opera Android24+

Closes the dialog element.

The argument, if provided, provides a return value.

dialog . returnValue [ = result ]

HTMLDialogElement/returnValue

Support in all current engines.

Firefox98+Safari15.4+Chrome37+
Opera24+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOS15.4+Chrome Android37+WebView Android37+Samsung Internet3.0+Opera Android24+

Returns the dialog's return value.

Can be set, to update the return value.

When the show() method is invoked, the user agent must run the following steps:

  1. If the element already has an open attribute, then return.

  2. Add an open attribute to the dialog element, whose value is the empty string.

  3. Run the dialog focusing steps for the dialog element.

When the showModal() method is invoked, the user agent must run the following steps:

  1. Let subject be the dialog element on which the method was invoked.

  2. If subject already has an open attribute, then throw an "InvalidStateError" DOMException.

  3. If subject is not connected, then throw an "InvalidStateError" DOMException.

  4. Add an open attribute to subject, whose value is the empty string.

  5. Set the is modal flag of subject to true.

  6. Let subject's node document be blocked by the modal dialog subject.

    This will cause the focused area of the document to become inert (unless that currently focused area is a shadow-including descendant of subject). In such cases, the focus fixup rule will kick in and reset the focused area of the document to the viewport for now. In a couple steps we will attempt to find a better candidate to focus.

  7. If subject's node document's top layer does not already contain subject, then add subject to subject's node document's top layer.

  8. Run the dialog focusing steps for subject.

The dialog focusing steps for a dialog element subject are as follows:

  1. If subject is inert, return.

  2. Let control be the first descendant element of subject, in tree order, that is not inert and has the autofocus attribute specified.

    If there isn't one, then let control be the first non-inert descendant element of subject, in tree order.

    If there isn't one of those either, then let control be subject.

  3. Run the focusing steps for control.

    If control is not focusable, this will do nothing. For modal dialogs, this means that any earlier modifications to the focused area of the document will apply.

  4. Let topDocument be the active document of control's node document's browsing context's top-level browsing context.

  5. If control's node document's origin is not the same as the origin of topDocument, then return.

  6. Empty topDocument's autofocus candidates.

  7. Set topDocument's autofocus processed flag to true.

If at any time a dialog element is removed from a Document, then if that dialog is in that Document's top layer, it must be removed from it.

When the close() method is invoked, the user agent must close the dialog that the method was invoked on. If the method was invoked with an argument, that argument must be used as the return value; otherwise, there is no return value.

When a dialog element subject is to be closed, optionally with a return value result, the user agent must run the following steps:

  1. If subject does not have an open attribute, then return.

  2. Remove subject's open attribute.

  3. Set the is modal flag of subject to false.

  4. If the argument result was provided, then set the returnValue attribute to the value of result.

  5. If subject is in its Document's top layer, then remove it.

  6. Queue an element task on the user interaction task source given the subject element to fire an event named close at subject.

The returnValue IDL attribute, on getting, must return the last value to which it was set. On setting, it must be set to the new value. When the element is created, it must be set to the empty string.


Canceling dialogs: When Document is blocked by a modal dialog dialog, user agents may provide a user interface that, upon activation, queues an element task on the user interaction task source given the dialog element to run these steps:

  1. Let close be the result of firing an event named cancel at dialog, with the cancelable attribute initialized to true.

  2. If close is true and dialog has an open attribute, then close the dialog with no return value.

An example of such a UI mechanism would be the user pressing the "Escape" key.


Each dialog element has an is modal flag. When a dialog element is created, this flag must be set to false.


HTMLDialogElement/open

Support in all current engines.

Firefox98+Safari15.4+Chrome37+
Opera24+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOS15.4+Chrome Android37+WebView Android37+Samsung Internet3.0+Opera Android24+

The open IDL attribute must reflect the open content attribute.

This dialog box has some small print. The strong element is used to draw the user's attention to the more important part.

<dialog>
 <h1>Add to Wallet</h1>
 <p><strong><label for=amt>How many gold coins do you want to add to your wallet?</label></strong></p>
 <p><input id=amt name=amt type=number min=0 step=0.01 value=100></p>
 <p><small>You add coins at your own risk.</small></p>
 <p><label><input name=round type=checkbox> Only add perfectly round coins </label></p>
 <p><input type=button onclick="submit()" value="Add Coins"></p>
</dialog>

4.12 脚本

脚本使作者可以给他们的文档添加交互。

鼓励作者尽量使用声明式的标记替代脚本,因为声明式的机制更容易维护,而且很多用户禁用了脚本。

例如,显示和隐藏细节内容部分的脚本可以使用 details 元素替代。

也鼓励作者在没有脚本支持时对其应用优雅降级。

例如,如果作者在表格标题提供了一个重新排序的链接, 就可以把这个链接做成去服务器请求排好序的表格, 这样在没有脚本支持时也能完成功能。

4.12.1 The script element

Element/script

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

HTMLScriptElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
Categories:
Metadata content.
Flow content.
Phrasing content.
Script-supporting element.
Contexts in which this element can be used:
Where metadata content is expected.
Where phrasing content is expected.
Where script-supporting elements are expected.
Content model:
If there is no src attribute, depends on the value of the type attribute, but must match script content restrictions.
If there is a src attribute, the element must be either empty or contain only script documentation that also matches script content restrictions.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
src — Address of the resource
type — Type of script
nomodule — Prevents execution in user agents that support module scripts
async — Execute script when available, without blocking while fetching
defer — Defer script execution
crossorigin — How the element handles crossorigin requests
integrity — Integrity metadata used in Subresource Integrity checks [SRI]
referrerpolicyReferrer policy for fetches initiated by the element
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLScriptElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute boolean noModule;
  [CEReactions] attribute boolean async;
  [CEReactions] attribute boolean defer;
  [CEReactions] attribute DOMString? crossOrigin;
  [CEReactions] attribute DOMString text;
  [CEReactions] attribute DOMString integrity;
  [CEReactions] attribute DOMString referrerPolicy;

  // also has obsolete members
};

The script element allows authors to include dynamic script and data blocks in their documents. The element does not represent content for the user.

Element/script#attr-type

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

The type attribute allows customization of the type of script represented:

The requirement that data blocks must be denoted using a valid MIME type string is in place to avoid potential future collisions. If this specification ever adds additional types of script, they will be triggered by setting the type attribute to something which is not a MIME type, like how the "module" value denotes module scripts. By using a valid MIME type string now, you ensure that your data block will not ever be reinterpreted as a different script type, even in future user agents.

Classic scripts and module scripts can be embedded inline, or be imported from an external file using the src attribute, which if specified gives the URL of the external script resource to use. If src is specified, it must be a valid non-empty URL potentially surrounded by spaces. The contents of inline script elements, or the external script resource, must conform with the requirements of the JavaScript specification's Script or Module productions, for classic scripts and module scripts respectively. [JAVASCRIPT]

When used to include data blocks, the data must be embedded inline, the format of the data must be given using the type attribute, and the contents of the script element must conform to the requirements defined for the format used. The src, async, nomodule, defer, crossorigin, integrity, and referrerpolicy attributes must not be specified.

The nomodule attribute is a boolean attribute that prevents a script from being executed in user agents that support module scripts. This allows selective execution of module scripts in modern user agents and classic scripts in older user agents, as shown below. The nomodule attribute must not be specified on module scripts (and will be ignored if it is).

Element/script#attr-async

Support in all current engines.

Firefox1+SafariYesChrome1+
OperaYesEdge79+
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Element/script#attr-defer

Support in all current engines.

Firefox3.5+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

The async and defer attributes are boolean attributes that indicate how the script should be evaluated. Classic scripts may specify defer or async, but must not specify either unless the src attribute is present. Module scripts may specify the async attribute, but must not specify the defer attribute.

There are several possible modes that can be selected using these attributes, and depending on the script's type.

For classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available (potentially before parsing completes). If the async attribute is not present but the defer attribute is present, then the classic script will be fetched in parallel and evaluated when the page has finished parsing. If neither attribute is present, then the script is fetched and evaluated immediately, blocking parsing until these are both complete.

For module scripts, if the async attribute is present, then the module script and all its dependencies will be fetched in parallel to parsing, and the module script will be evaluated as soon as it is available (potentially before parsing completes). Otherwise, the module script and its dependencies will be fetched in parallel to parsing and evaluated when the page has finished parsing. (The defer attribute has no effect on module scripts.)

This is all summarized in the following schematic diagram:

With <script>, parsing is interrupted by fetching and execution. With <script defer>, fetching is parallel to parsing and execution takes place after all parsing has finished. And with <script async>, fetching is parallel to parsing but once it finishes parsing is interrupted to execute the script. The story for <script type="module"> is similar to <script defer>, but the dependencies will be fetched as well, and the story for <script type="module" async> is similar to <script async> with the extra dependency fetching.

The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation requirements are therefore by necessity scattered throughout the specification. The algorithms below (in this section) describe the core of this processing, but these algorithms reference and are referenced by the parsing rules for script start and end tags in HTML, in foreign content, and in XML, the rules for the document.write() method, the handling of scripting, etc.

The defer attribute may be specified even if the async attribute is specified, to cause legacy web browsers that only support defer (and not async) to fall back to the defer behavior instead of the blocking behavior that is the default.

The crossorigin attribute is a CORS settings attribute. For classic scripts, it controls whether error information will be exposed, when the script is obtained from other origins. For module scripts, it controls the credentials mode used for cross-origin requests.

Unlike classic scripts, module scripts require the use of the CORS protocol for cross-origin fetching.

The integrity attribute represents the integrity metadata for requests which this element is responsible for. The value is text. The integrity attribute must not be specified when the src attribute is not specified. [SRI]

The referrerpolicy attribute is a referrer policy attribute. Its purpose is to set the referrer policy used when fetching the script, as well as any scripts imported from it. [REFERRERPOLICY]

An example of a script element's referrer policy being used when fetching imported scripts but not other subresources:

<script referrerpolicy="origin">
  fetch('/api/data');    // not fetched with <script>'s referrer policy
  import('./utils.mjs'); // is fetched with <script>'s referrer policy ("origin" in this case)
</script>

Changing the src, type, nomodule, async, defer, crossorigin, integrity, and referrerpolicy attributes dynamically has no direct effect; these attributes are only used at specific times described below.

The IDL attributes src, type, defer, and integrity, must each reflect the respective content attributes of the same name.

HTMLScriptElement/referrerPolicy

Support in all current engines.

Firefox65+Safari14+Chrome70+
Opera57+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android65+Safari iOS14+Chrome Android70+WebView Android70+Samsung Internet10.0+Opera Android49+

The referrerPolicy IDL attribute must reflect the referrerpolicy content attribute, limited to only known values.

The crossOrigin IDL attribute must reflect the crossorigin content attribute, limited to only known values.

The noModule IDL attribute must reflect the nomodule content attribute.

The async IDL attribute controls whether the element will execute asynchronously or not. If the element's "non-blocking" flag is set, then, on getting, the async IDL attribute must return true, and on setting, the "non-blocking" flag must first be unset, and then the content attribute must be removed if the IDL attribute's new value is false, and must be set to the empty string if the IDL attribute's new value is true. If the element's "non-blocking" flag is not set, the IDL attribute must reflect the async content attribute.

script . text [ = value ]

Returns the child text content of the element.

Can be set, to replace the element's children with the given value.

The text attribute's getter must return this script element's child text content.

The text attribute's setter must string replace all with the given value within this script element.

When inserted using the document.write() method, script elements usually execute (typically blocking further script execution or HTML parsing). When inserted using the innerHTML and outerHTML attributes, they do not execute at all.

In this example, two script elements are used. One embeds an external classic script, and the other includes some data as a data block.

<script src="game-engine.js"></script>
<script type="text/x-game-map">
........U.........e
o............A....e
.....A.....AAA....e
.A..AAA...AAAAA...e
</script>

The data in this case might be used by the script to generate the map of a video game. The data doesn't have to be used that way, though; maybe the map data is actually embedded in other parts of the page's markup, and the data block here is just used by the site's search engine to help users who are looking for particular features in their game maps.

The following sample shows how a script element can be used to define a function that is then used by other parts of the document, as part of a classic script. It also shows how a script element can be used to invoke script while the document is being parsed, in this case to initialize the form's output.

<script>
 function calculate(form) {
   var price = 52000;
   if (form.elements.brakes.checked)
     price += 1000;
   if (form.elements.radio.checked)
     price += 2500;
   if (form.elements.turbo.checked)
     price += 5000;
   if (form.elements.sticker.checked)
     price += 250;
   form.elements.result.value = price;
 }
</script>
<form name="pricecalc" onsubmit="return false" onchange="calculate(this)">
 <fieldset>
  <legend>Work out the price of your car</legend>
  <p>Base cost: £52000.</p>
  <p>Select additional options:</p>
  <ul>
   <li><label><input type=checkbox name=brakes> Ceramic brakes (£1000)</label></li>
   <li><label><input type=checkbox name=radio> Satellite radio (£2500)</label></li>
   <li><label><input type=checkbox name=turbo> Turbo charger (£5000)</label></li>
   <li><label><input type=checkbox name=sticker> "XZ" sticker (£250)</label></li>
  </ul>
  <p>Total: £<output name=result></output></p>
 </fieldset>
 <script>
  calculate(document.forms.pricecalc);
 </script>
</form>

The following sample shows how a script element can be used to include an external module script.

<script type="module" src="app.mjs"></script>

This module, and all its dependencies (expressed through JavaScript import statements in the source file), will be fetched. Once the entire resulting module graph has been imported, and the document has finished parsing, the contents of app.mjs will be evaluated.

Additionally, if code from another script element in the same Window imports the module from app.mjs (e.g. via import "./app.mjs";), then the same module script created by the former script element will be imported.

This example shows how to include a module script for modern user agents, and a classic script for older user agents:

<script type="module" src="app.mjs"></script>
<script nomodule defer src="classic-app-bundle.js"></script>

In modern user agents that support module scripts, the script element with the nomodule attribute will be ignored, and the script element with a type of "module" will be fetched and evaluated (as a module script). Conversely, older user agents will ignore the script element with a type of "module", as that is an unknown script type for them — but they will have no problem fetching and evaluating the other script element (as a classic script), since they do not implement the nomodule attribute.

The following sample shows how a script element can be used to write an inline module script that performs a number of substitutions on the document's text, in order to make for a more interesting reading experience (e.g. on a news site): [XKCD1288]

<script type="module">
 import { walkAllTextNodeDescendants } from "./dom-utils.mjs";

 const substitutions = new Map([
   ["witnesses", "these dudes I know"]
   ["allegedly", "kinda probably"]
   ["new study", "Tumblr post"]
   ["rebuild", "avenge"]
   ["space", "spaaace"]
   ["Google glass", "Virtual Boy"]
   ["smartphone", "Pokédex"]
   ["electric", "atomic"]
   ["Senator", "Elf-Lord"]
   ["car", "cat"]
   ["election", "eating contest"]
   ["Congressional leaders", "river spirits"]
   ["homeland security", "Homestar Runner"]
   ["could not be reached for comment", "is guilty and everyone knows it"]
 ]);

 function substitute(textNode) {
   for (const [before, after] of substitutions.entries()) {
     textNode.data = textNode.data.replace(new RegExp(`\\b${before}\\b`, "ig"), after);
   }
 }

 walkAllTextNodeDescendants(document.body, substitute);
</script>

Some notable features gained by using a module script include the ability to import functions from other JavaScript modules, strict mode by default, and how top-level declarations do not introduce new properties onto the global object. Also note that no matter where this script element appears in the document, it will not be evaluated until both document parsing has complete and its dependency (dom-utils.mjs) has been fetched and evaluated.

4.12.1.1 Processing model

A script element has several associated pieces of state.

A script element has a flag indicating whether or not it has been "already started". Initially, script elements must have this flag unset (script blocks, when created, are not "already started"). The cloning steps for script elements must set the "already started" flag on the copy if it is set on the element being cloned.

A script element has a parser document, which is either null or a Document. Initially, its value must be null. It is set by the HTML parser and the XML parser on script elements they insert, and affects the processing of those elements. script elements with non-null parser documents are known as "parser-inserted".

A script element has a flag indicating whether the element will be "non-blocking". Initially, script elements must have this flag set. It is unset by the HTML parser and the XML parser on script elements they insert. In addition, whenever a script element whose "non-blocking" flag is set has an async content attribute added, the element's "non-blocking" flag must be unset.

A script element has a flag indicating whether or not the script block is "ready to be parser-executed". Initially, script elements must have this flag unset (script blocks, when created, are not "ready to be parser-executed"). This flag is used only for elements that are also "parser-inserted", to let the parser know when to execute the script.

The script's type for a script element is either "classic" or "module". It is determined when the script is prepared, based on the type attribute of the element at that time.

A script element has a preparation-time document, which is a Document determined near the beginning of the prepare a script algorithm. It is used to prevent scripts that move between documents during preparation from executing.

A script element has a flag indicating whether or not the script is from an external file. It is determined when the script is prepared, based on the src attribute of the element at that time.

The script's script for a script element is either null or a script resulting from preparing the element. This is set asynchronously after the classic script or module graph is fetched. Once it is set, either to a script in the case of success or to null in the case of failure, the fetching algorithms will note that the script is ready, which can trigger other actions. The user agent must delay the load event of the element's node document until the script is ready.


When a script element that is not "parser-inserted" experiences one of the events listed in the following list, the user agent must immediately prepare the script element:

To prepare a script, the user agent must act as follows:

  1. If the script element is marked as having "already started", then return. The script is not executed.

  2. Let parser document be the element's parser document.

  3. Set the element's parser document to null.

    This is done so that if parser-inserted script elements fail to run when the parser tries to run them, e.g. because they are empty or specify an unsupported scripting language, another script can later mutate them and cause them to run again.

  4. If parser document is non-null and the element does not have an async attribute, then set the element's "non-blocking" flag to true.

    This is done so that if a parser-inserted script element fails to run when the parser tries to run it, but it is later executed after a script dynamically updates it, it will execute in a non-blocking fashion even if the async attribute isn't set.

  5. Let source text be the element's child text content.

  6. If the element has no src attribute, and source text is the empty string, then return. The script is not executed.

  7. If the element is not connected, then return. The script is not executed.

  8. If either:

    ...let the script block's type string for this script element be "text/javascript".

    Otherwise, if the script element has a type attribute, let the script block's type string for this script element be the value of that attribute with leading and trailing ASCII whitespace stripped.

    Otherwise, the element has a non-empty language attribute; let the script block's type string for this script element be the concatenation of the string "text/" followed by the value of the language attribute.

    The language attribute is never conforming, and is always ignored if there is a type attribute present.

    Determine the script's type as follows:

  9. If parser document is non-null, then set the element's parser document back to parser document and set the element's "non-blocking" flag to false.

  10. Set the element's "already started" flag.

  11. Set the element's preparation-time document to its node document.

  12. If parser document is non-null, and parser document is not equal to the element's preparation-time document, then return.

  13. If scripting is disabled for the script element, then return. The script is not executed.

    The definition of scripting is disabled means that, amongst others, the following scripts will not execute: scripts in XMLHttpRequest's responseXML documents, scripts in DOMParser-created documents, scripts in documents created by XSLTProcessor's transformToDocument feature, and scripts that are first inserted by a script into a Document that was created using the createDocument() API. [XHR] [DOMPARSING] [XSLTP] [DOM]

  14. If the script element has a nomodule content attribute and the script's type is "classic", then return. The script is not executed.

    This means specifying nomodule on a module script has no effect; the algorithm continues onward.

  15. If the script element does not have a src content attribute, and the Should element's inline behavior be blocked by Content Security Policy? algorithm returns "Blocked" when executed upon the script element, "script", and source text, then return. The script is not executed. [CSP]

  16. If the script element has an event attribute and a for attribute, and the script's type is "classic", then:

    1. Let for be the value of the for attribute.

    2. Let event be the value of the event attribute.

    3. Strip leading and trailing ASCII whitespace from event and for.

    4. If for is not an ASCII case-insensitive match for the string "window", then return. The script is not executed.

    5. If event is not an ASCII case-insensitive match for either the string "onload" or the string "onload()", then return. The script is not executed.

  17. If the script element has a charset attribute, then let encoding be the result of getting an encoding from the value of the charset attribute.

    If the script element does not have a charset attribute, or if getting an encoding failed, let encoding be the same as the encoding of the script element's node document.

    If the script's type is "module", this encoding will be ignored.

  18. Let classic script CORS setting be the current state of the element's crossorigin content attribute.

  19. Let module script credentials mode be the CORS settings attribute credentials mode for the element's crossorigin content attribute.

  20. Let cryptographic nonce be the element's [[CryptographicNonce]] internal slot's value.

  21. If the script element has an integrity attribute, then let integrity metadata be that attribute's value.

    Otherwise, let integrity metadata be the empty string.

  22. Let referrer policy be the current state of the element's referrerpolicy content attribute.

  23. Let parser metadata be "parser-inserted" if the script element is "parser-inserted", and "not-parser-inserted" otherwise.

  24. Let options be a script fetch options whose cryptographic nonce is cryptographic nonce, integrity metadata is integrity metadata, parser metadata is parser metadata, credentials mode is module script credentials mode, and referrer policy is referrer policy.

  25. Let settings object be the element's node document's relevant settings object.

  26. If the element has a src content attribute, then:

    1. Let src be the value of the element's src attribute.

    2. If src is the empty string, queue a task to fire an event named error at the element, and return.

    3. Set the element's from an external file flag.

    4. Parse src relative to the element's node document.

    5. If the previous step failed, queue a task to fire an event named error at the element, and return. Otherwise, let url be the resulting URL record.

    6. Switch on the script's type:

      "classic"

      Fetch a classic script given url, settings object, options, classic script CORS setting, and encoding.

      "module"

      Fetch an external module script graph given url, settings object, and options.

      When the chosen algorithm asynchronously completes, set the script's script to the result. At that time, the script is ready.

      For performance reasons, user agents may start fetching the classic script or module graph (as defined above) as soon as the src attribute is set, instead, in the hope that the element will be inserted into the document (and that the crossorigin attribute won't change value in the meantime). Either way, once the element is inserted into the document, the load must have started as described in this step. If the UA performs such prefetching, but the element is never inserted in the document, or the src attribute is dynamically changed, or the crossorigin attribute is dynamically changed, then the user agent will not execute the script so obtained, and the fetching process will have been effectively wasted.

  27. If the element does not have a src content attribute, run these substeps:

    1. Let base URL be the script element's node document's document base URL.

    2. Switch on the script's type:

      "classic"
      1. Let script be the result of creating a classic script using source text, settings object, base URL, and options.

      2. Set the script's script to script.

      3. The script is ready.

      "module"
      1. Fetch an inline module script graph, given source text, base URL, settings object, and options. When this asynchronously completes, set the script's script to the result. At that time, the script is ready.

  28. Then, follow the first of the following options that describes the situation:

    If the script's type is "classic", and the element has a src attribute, and the element has a defer attribute, and the element is "parser-inserted", and the element does not have an async attribute
    If the script's type is "module", and the element is "parser-inserted", and the element does not have an async attribute

    Add the element to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

    When the script is ready, set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

    If the script's type is "classic", and the element has a src attribute, and the element is "parser-inserted", and the element does not have an async attribute

    The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

    When the script is ready, set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

    If the script's type is "classic", and the element has a src attribute, and the element does not have an async attribute, and the element does not have the "non-blocking" flag set
    If the script's type is "module", and the element does not have an async attribute, and the element does not have the "non-blocking" flag set

    Add the element to the end of the list of scripts that will execute in order as soon as possible associated with the element's preparation-time document.

    When the script is ready, run the following steps:

    1. If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but return without executing the script yet.

    2. Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.

    3. Remove the first element from this list of scripts that will execute in order as soon as possible.

    4. If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.

    If the script's type is "classic", and the element has a src attribute
    If the script's type is "module"

    The element must be added to the set of scripts that will execute as soon as possible of the element's preparation-time document.

    When the script is ready, execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

    If the element does not have a src attribute, and the element is "parser-inserted", and either the parser that created the script is an XML parser or it's an HTML parser whose script nesting level is not greater than one, and the element's parser document has a style sheet that is blocking scripts

    The element is the pending parsing-blocking script of its parser document. (There can only be one such script per Document at a time.)

    Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

    Otherwise
    Immediately execute the script block, even if other scripts are already executing.

The pending parsing-blocking script of a Document is used by the Document's parser(s).

If a script element that blocks a parser gets moved to another Document before it would normally have stopped blocking that parser, it nonetheless continues blocking that parser until the condition that causes it to be blocking the parser no longer applies (e.g., if the script is a pending parsing-blocking script because the original Document has a style sheet that is blocking scripts when it was parsed, but then the script is moved to another Document before the blocking style sheet(s) loaded, the script still blocks the parser until the style sheets are all loaded, at which time the script executes and the parser is unblocked).

To execute a script block given a script element scriptElement:

  1. Let document be scriptElement's node document.

  2. If scriptElement's preparation-time document is not equal to document, then return.

  3. If the script's script is null for scriptElement, then fire an event named error at scriptElement, and return.

  4. If scriptElement is from an external file, or the script's type for scriptElement is "module", then increment document's ignore-destructive-writes counter.

  5. Switch on the script's type for scriptElement:

    "classic"
    1. Let oldCurrentScript be the value to which document's currentScript object was most recently set.

    2. If scriptElement's root is not a shadow root, then set document's currentScript attribute to scriptElement. Otherwise, set it to null.

      This does not use the in a document tree check, as scriptElement could have been removed from the document prior to execution, and in that scenario currentScript still needs to point to it.

    3. Run the classic script given by the script's script for scriptElement.

    4. Set document's currentScript attribute to oldCurrentScript.

    "module"
    1. Assert: document's currentScript attribute is null.

    2. Run the module script given by the script's script for scriptElement.

  6. Decrement the ignore-destructive-writes counter of document, if it was incremented in the earlier step.

  7. If scriptElement is from an external file, then fire an event named load at scriptElement.

4.12.1.2 Scripting languages

User agents are not required to support JavaScript. This standard needs to be updated if a language other than JavaScript comes along and gets similar wide adoption by web browsers. Until such a time, implementing other languages is in conflict with this standard, given the processing model defined for the script element.

Servers should use text/javascript for JavaScript resources. Servers should not use other JavaScript MIME types for JavaScript resources, and must not use non-JavaScript MIME types.

For external JavaScript resources, MIME type parameters in `Content-Type` headers are generally ignored. (In some cases the `charset` parameter has an effect.) However, for the script element's type attribute they are significant; it uses the JavaScript MIME type essence match concept.

For example, scripts with their type attribute set to "text/javascript; charset=utf-8" will not be evaluated, even though that is a valid JavaScript MIME type when parsed.

Furthermore, again for external JavaScript resources, special considerations apply around `Content-Type` header processing as detailed in the prepare a script algorithm and Fetch. [FETCH]

4.12.1.3 script 元素内容的限制

避免本章中描述的这些奇怪限制的最简单安全的方式就是总是转义 "<!--" 为 "<\!--", "<script" 为 "<\script", "</script" 为 "<\/script" (例如在字符串中、正则表达式中,或者注释中),同时避免编写在表达式中使用这些构造的代码。 这样就可以避免本章中的限制产生的陷阱: 即,由于历史原因在 HTML 中解析 script 块是一个奇怪的过程, 碰到这些序列时表现地很不直观。

script 元素的 textContent 必须匹配 下面的 script 的 ABNF 生成式,其中的字符集是 Unicode。 [ABNF]

script        = outer *( comment-open inner comment-close outer )

outer         = < any string that doesn't contain a substring that matches not-in-outer >
not-in-outer  = comment-open
inner         = < any string that doesn't contain a substring that matches not-in-inner >
not-in-inner  = comment-close / script-open

comment-open  = "<!--"
comment-close = "-->"
script-open   = "<" s c r i p t tag-end

s             =  %x0053 ; U+0053 LATIN CAPITAL LETTER S
s             =/ %x0073 ; U+0073 LATIN SMALL LETTER S
c             =  %x0043 ; U+0043 LATIN CAPITAL LETTER C
c             =/ %x0063 ; U+0063 LATIN SMALL LETTER C
r             =  %x0052 ; U+0052 LATIN CAPITAL LETTER R
r             =/ %x0072 ; U+0072 LATIN SMALL LETTER R
i             =  %x0049 ; U+0049 LATIN CAPITAL LETTER I
i             =/ %x0069 ; U+0069 LATIN SMALL LETTER I
p             =  %x0050 ; U+0050 LATIN CAPITAL LETTER P
p             =/ %x0070 ; U+0070 LATIN SMALL LETTER P
t             =  %x0054 ; U+0054 LATIN CAPITAL LETTER T
t             =/ %x0074 ; U+0074 LATIN SMALL LETTER T

tag-end       =  %x0009 ; U+0009 CHARACTER TABULATION (tab)
tag-end       =/ %x000A ; U+000A LINE FEED (LF)
tag-end       =/ %x000C ; U+000C FORM FEED (FF)
tag-end       =/ %x0020 ; U+0020 SPACE
tag-end       =/ %x002F ; U+002F SOLIDUS (/)
tag-end       =/ %x003E ; U+003E GREATER-THAN SIGN (>)

script 元素包含 脚本文档 时, 对该元素的内容有更多的限制,描述如下。

下面的脚本演示了这个问题,假设你有一个标签包含这样的字符串:

var example = 'Consider this string: <!-- <script>';
console.log(example);

如果有人直接把这个字符串放到 script 块中,就会违反上述限制: restrictions above:

<script>
  var example = 'Consider this string: <!-- <script>';
  console.log(example);
</script>

更大的问题(也即违反那些规则的原因)是脚本的解析会很奇怪: 上述脚本块并未结束。 也就是说,看起来是结束标签的 "</script>" 实际上仍然是 script 块的内容。这个脚本不会执行(因为它没有结束); 如果它最终还是执行了(比如下面的情况),它会因为脚本不合法(下面有高亮)而失败:

<script>
  var example = 'Consider this string: <!-- <script>';
  console.log(example);
</script>
<!-- despite appearances, this is actually part of the script still! -->
<script>
 ... // this is the same script block still...
</script>

这种行为是历史原因造成的,在 HTML 中 script 元素中的 "<!--" 和 "<script" 字符串需要匹配,才能让解析器认为块已经结束。

参照本章开始提到的方式转义这个出问题的字符串,就可以完全避免这个问题:

<script>
  var example = 'Consider this string: <\!-- <\script>';
  console.log(example);
</script>
<!-- this is just a comment between script blocks -->
<script>
 ... // this is a new script block
</script>

这种字符序列在正常的脚本表达式中也可能出现,比如下面这个例子:

if (x<!--y) { ... }
if ( player<script ) { ... }

这种情况下无法转义这些字符,但可以重写表达式来避免这个字符序列,如:

if (x < !--y) { ... }
if (!--y > x) { ... }
if (!(--y) > x) { ... }
if (player < script) { ... }
if (script > player) { ... }

这样做还能避免另一个陷阱:由于相关的历史原因, 在 经典脚本 中字符串 "<!--" 实际上被处理为行注释的开始,就像 "//" 一样。

4.12.1.4 Inline documentation for external scripts

If a script element's src attribute is specified, then the contents of the script element, if any, must be such that the value of the text IDL attribute, which is derived from the element's contents, matches the documentation production in the following ABNF, the character set for which is Unicode. [ABNF]

documentation = *( *( space / tab / comment ) [ line-comment ] newline )
comment       = slash star *( not-star / star not-slash ) 1*star slash
line-comment  = slash slash *not-newline

; characters
tab           = %x0009 ; U+0009 CHARACTER TABULATION (tab)
newline       = %x000A ; U+000A LINE FEED (LF)
space         = %x0020 ; U+0020 SPACE
star          = %x002A ; U+002A ASTERISK (*)
slash         = %x002F ; U+002F SOLIDUS (/)
not-newline   = %x0000-0009 / %x000B-10FFFF
                ; a scalar value other than U+000A LINE FEED (LF)
not-star      = %x0000-0029 / %x002B-10FFFF
                ; a scalar value other than U+002A ASTERISK (*)
not-slash     = %x0000-002E / %x0030-10FFFF
                ; a scalar value other than U+002F SOLIDUS (/)

This corresponds to putting the contents of the element in JavaScript comments.

This requirement is in addition to the earlier restrictions on the syntax of contents of script elements.

This allows authors to include documentation, such as license information or API information, inside their documents while still referring to external script files. The syntax is constrained so that authors don't accidentally include what looks like valid script while also providing a src attribute.

<script src="cool-effects.js">
 // create new instances using:
 //    var e = new Effect();
 // start the effect using .play, stop using .stop:
 //    e.play();
 //    e.stop();
</script>
4.12.1.5 Interaction of script elements and XSLT

This section is non-normative.

This specification does not define how XSLT interacts with the script element. However, in the absence of another specification actually defining this, here are some guidelines for implementers, based on existing implementations:

The main distinction between the first two cases and the last case is that the first two operate on Documents and the last operates on a fragment.

4.12.2 The noscript element

Element/noscript

Support in all current engines.

Firefox1+SafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes
Categories:
Metadata content.
Flow content.
Phrasing content.
Contexts in which this element can be used:
In a head element of an HTML document, if there are no ancestor noscript elements.
Where phrasing content is expected in HTML documents, if there are no ancestor noscript elements.
Content model:
When scripting is disabled, in a head element: in any order, zero or more link elements, zero or more style elements, and zero or more meta elements.
When scripting is disabled, not in a head element: transparent, but there must be no noscript element descendants.
Otherwise: text that conforms to the requirements given in the prose.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
DOM interface:
Uses HTMLElement.

The noscript element represents nothing if scripting is enabled, and represents its children if scripting is disabled. It is used to present different markup to user agents that support scripting and those that don't support scripting, by affecting how the document is parsed.

When used in HTML documents, the allowed content model is as follows:

In a head element, if scripting is disabled for the noscript element

The noscript element must contain only link, style, and meta elements.

In a head element, if scripting is enabled for the noscript element

The noscript element must contain only text, except that invoking the HTML fragment parsing algorithm with the noscript element as the context element and the text contents as the input must result in a list of nodes that consists only of link, style, and meta elements that would be conforming if they were children of the noscript element, and no parse errors.

Outside of head elements, if scripting is disabled for the noscript element

The noscript element's content model is transparent, with the additional restriction that a noscript element must not have a noscript element as an ancestor (that is, noscript can't be nested).

Outside of head elements, if scripting is enabled for the noscript element

The noscript element must contain only text, except that the text must be such that running the following algorithm results in a conforming document with no noscript elements and no script elements, and such that no step in the algorithm throws an exception or causes an HTML parser to flag a parse error:

  1. Remove every script element from the document.
  2. Make a list of every noscript element in the document. For every noscript element in that list, perform the following steps:
    1. Let s be the child text content of the noscript element.
    2. Set the outerHTML attribute of the noscript element to the value of s. (This, as a side-effect, causes the noscript element to be removed from the document.) [DOMPARSING]

All these contortions are required because, for historical reasons, the noscript element is handled differently by the HTML parser based on whether scripting was enabled or not when the parser was invoked.

The noscript element must not be used in XML documents.

The noscript element is only effective in HTML 语法, it has no effect in XML 语法. This is because the way it works is by essentially "turning off" the parser when scripts are enabled, so that the contents of the element are treated as pure text and not as real elements. XML does not define a mechanism by which to do this.

The noscript element has no other requirements. In particular, children of the noscript element are not exempt from form submission, scripting, and so forth, even when scripting is enabled for the element.

In the following example, a noscript element is used to provide fallback for a script.

<form action="calcSquare.php">
 <p>
  <label for=x>Number</label>:
  <input id="x" name="x" type="number">
 </p>
 <script>
  var x = document.getElementById('x');
  var output = document.createElement('p');
  output.textContent = 'Type a number; it will be squared right then!';
  x.form.appendChild(output);
  x.form.onsubmit = function () { return false; }
  x.oninput = function () {
    var v = x.valueAsNumber;
    output.textContent = v + ' squared is ' + v * v;
  };
 </script>
 <noscript>
  <input type=submit value="Calculate Square">
 </noscript>
</form>

When script is disabled, a button appears to do the calculation on the server side. When script is enabled, the value is computed on-the-fly instead.

The noscript element is a blunt instrument. Sometimes, scripts might be enabled, but for some reason the page's script might fail. For this reason, it's generally better to avoid using noscript, and to instead design the script to change the page from being a scriptless page to a scripted page on the fly, as in the next example:

<form action="calcSquare.php">
 <p>
  <label for=x>Number</label>:
  <input id="x" name="x" type="number">
 </p>
 <input id="submit" type=submit value="Calculate Square">
 <script>
  var x = document.getElementById('x');
  var output = document.createElement('p');
  output.textContent = 'Type a number; it will be squared right then!';
  x.form.appendChild(output);
  x.form.onsubmit = function () { return false; }
  x.oninput = function () {
    var v = x.valueAsNumber;
    output.textContent = v + ' squared is ' + v * v;
  };
  var submit = document.getElementById('submit');
  submit.parentNode.removeChild(submit);
 </script>
</form>

The above technique is also useful in XML documents, since noscript is not allowed there.

4.12.3 The template element

Element/template

Support in all current engines.

Firefox22+Safari8+Chrome26+
Opera15+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android22+Safari iOS8+Chrome Android26+WebView AndroidYesSamsung Internet1.5+Opera Android?

HTMLTemplateElement

Support in all current engines.

Firefox22+Safari8+Chrome26+
Opera15+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android22+Safari iOS8+Chrome Android26+WebView Android4.4+Samsung Internet1.5+Opera Android14+
Categories:
Metadata content.
Flow content.
Phrasing content.
Script-supporting element.
Contexts in which this element can be used:
Where metadata content is expected.
Where phrasing content is expected.
Where script-supporting elements are expected.
As a child of a colgroup element that doesn't have a span attribute.
Content model:
Nothing (for clarification, see example).
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLTemplateElement : HTMLElement {
  [HTMLConstructor] constructor();

  readonly attribute DocumentFragment content;
};

The template element is used to declare fragments of HTML that can be cloned and inserted in the document by script.

In a rendering, the template element represents nothing.

The template contents of a template element are not children of the element itself.

It is also possible, as a result of DOM manipulation, for a template element to contain Text nodes and element nodes; however, having any is a violation of the template element's content model, since its content model is defined as nothing.

For example, consider the following document:

<!doctype html>
<html lang="en">
 <head>
  <title>Homework</title>
 <body>
  <template id="template"><p>Smile!</p></template>
  <script>
   let num = 3;
   const fragment = document.getElementById('template').content.cloneNode(true);
   while (num-- > 1) {
     fragment.firstChild.before(fragment.firstChild.cloneNode(true));
     fragment.firstChild.textContent += fragment.lastChild.textContent;
   }
   document.body.appendChild(fragment);
  </script>
</html>

The p element in the template is not a child of the template in the DOM; it is a child of the DocumentFragment returned by the template element's content IDL attribute.

If the script were to call appendChild() on the template element, that would add a child to the template element (as for any other element); however, doing so is a violation of the template element's content model.

template . content

HTMLTemplateElement/content

Support in all current engines.

Firefox22+Safari8+Chrome26+
Opera15+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android22+Safari iOS8+Chrome Android26+WebView Android4.4+Samsung Internet1.5+Opera Android14+

Returns the template contents (a DocumentFragment).

Each template element has an associated DocumentFragment object that is its template contents. The template contents have no conformance requirements. When a template element is created, the user agent must run the following steps to establish the template contents:

  1. Let doc be the template element's node document's appropriate template contents owner document.

  2. Create a DocumentFragment object whose node document is doc and host is the template element.

  3. Set the template element's template contents to the newly created DocumentFragment object.

A Document doc's appropriate template contents owner document is the Document returned by the following algorithm:

  1. If doc is not a Document created by this algorithm, then:

    1. If doc does not yet have an associated inert template document, then:

      1. Let new doc be a new Document (whose browsing context is null). This is "a Document created by this algorithm" for the purposes of the step above.

      2. If doc is an HTML document, mark new doc as an HTML document also.

      3. Let doc's associated inert template document be new doc.

    2. Set doc to doc's associated inert template document.

    Each Document not created by this algorithm thus gets a single Document to act as its proxy for owning the template contents of all its template elements, so that they aren't in a browsing context and thus remain inert (e.g. scripts do not run). Meanwhile, template elements inside Document objects that are created by this algorithm just reuse the same Document owner for their contents.

  2. Return doc.

The adopting steps (with node and oldDocument as parameters) for template elements are the following:

  1. Let doc be node's node document's appropriate template contents owner document.

    node's node document is the Document object that node was just adopted into.

  2. Adopt node's template contents (a DocumentFragment object) into doc.

The content IDL attribute must return the template element's template contents.


The cloning steps for a template element node being cloned to a copy copy must run the following steps:

  1. If the clone children flag is not set in the calling clone algorithm, return.

  2. Let copied contents be the result of cloning all the children of node's template contents, with document set to copy's template contents's node document, and with the clone children flag set.

  3. Append copied contents to copy's template contents.

In this example, a script populates a table four-column with data from a data structure, using a template to provide the element structure instead of manually generating the structure from markup.

<!DOCTYPE html>
<html lang='en'>
<title>Cat data</title>
<script>
 // Data is hard-coded here, but could come from the server
 var data = [
   { name: 'Pillar', color: 'Ticked Tabby', sex: 'Female (neutered)', legs: 3 },
   { name: 'Hedral', color: 'Tuxedo', sex: 'Male (neutered)', legs: 4 },
 ];
</script>
<table>
 <thead>
  <tr>
   <th>Name <th>Color <th>Sex <th>Legs
 <tbody>
  <template id="row">
   <tr><td><td><td><td>
  </template>
</table>
<script>
 var template = document.querySelector('#row');
 for (var i = 0; i < data.length; i += 1) {
   var cat = data[i];
   var clone = template.content.cloneNode(true);
   var cells = clone.querySelectorAll('td');
   cells[0].textContent = cat.name;
   cells[1].textContent = cat.color;
   cells[2].textContent = cat.sex;
   cells[3].textContent = cat.legs;
   template.parentNode.appendChild(clone);
 }
</script>

This example uses cloneNode() on the template's contents; it could equivalently have used document.importNode(), which does the same thing. The only difference between these two APIs is when the node document is updated: with cloneNode() it is updated when the nodes are appended with appendChild(), with document.importNode() it is updated when the nodes are cloned.

4.12.3.1 Interaction of template elements with XSLT and XPath

This section is non-normative.

This specification does not define how XSLT and XPath interact with the template element. However, in the absence of another specification actually defining this, here are some guidelines for implementers, which are intended to be consistent with other processing described in this specification:

4.12.4 The slot element

Element/slot

Support in all current engines.

Firefox63+Safari10+Chrome53+
Opera40+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10+Chrome Android53+WebView Android53+Samsung Internet6.0+Opera Android41+

HTMLSlotElement

Support in all current engines.

Firefox63+Safari10+Chrome53+
Opera40+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10+Chrome Android53+WebView Android53+Samsung Internet6.0+Opera Android41+
Categories:
Flow content.
Phrasing content.
Contexts in which this element can be used:
Where phrasing content is expected.
Content model:
Transparent
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
name — Name of shadow tree slot
Accessibility considerations:
For authors.
For implementers.
DOM interface:
[Exposed=Window]
interface HTMLSlotElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString name;
  sequence<Node> assignedNodes(optional AssignedNodesOptions options = {});
  sequence<Element> assignedElements(optional AssignedNodesOptions options = {});
};

dictionary AssignedNodesOptions {
  boolean flatten = false;
};

The slot element defines a slot. It is typically used in a shadow tree. A slot element represents its assigned nodes, if any, and its contents otherwise.

The name content attribute may contain any string value. It represents a slot's name.

The name attribute is used to assign slots to other elements: a slot element with a name attribute creates a named slot to which any element is assigned if that element has a slot attribute whose value matches that name attribute's value, and the slot element is a child of the shadow tree whose root's host has that corresponding slot attribute value.

slot . name

HTMLSlotElement/name

Support in all current engines.

Firefox63+Safari10+Chrome53+
Opera40+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10+Chrome Android53+WebView Android53+Samsung Internet6.0+Opera Android41+
Can be used to get and set slot's name.
slot . assignedNodes()

HTMLSlotElement/assignedNodes

Support in all current engines.

Firefox63+Safari10+Chrome53+
Opera40+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10+Chrome Android53+WebView Android53+Samsung Internet6.0+Opera Android41+
Returns slot's assigned nodes.
slot . assignedNodes({ flatten: true })
Returns slot's assigned nodes, if any, and slot's children otherwise, and does the same for any slot elements encountered therein, recursively, until there are no slot elements left.
slot . assignedElements()

HTMLSlotElement/assignedElements

Support in all current engines.

Firefox66+Safari12.1+Chrome65+
Opera52+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android66+Safari iOS12.2+Chrome Android65+WebView Android65+Samsung Internet9.0+Opera Android47+
Returns slot's assigned nodes, limited to elements.
slot . assignedElements({ flatten: true })
Returns the same as assignedNodes({ flatten: true }), limited to elements.

The name IDL attribute must reflect the content attribute of the same name.

The assignedNodes(options) method, when invoked, must run these steps:

  1. If the value of options's flatten member is false, then return this element's assigned nodes.

  2. Return the result of finding flattened slottables with this element.

The assignedElements(options) method, when invoked, must run these steps:

  1. If the value of options's flatten member is false, then return this element's assigned nodes, filtered to contain only Element nodes.

  2. Return the result of finding flattened slottables with this element, filtered to contain only Element nodes.

4.12.5 The canvas element

Element/canvas

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

HTMLCanvasElement

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
Categories:
Flow content.
Phrasing content.
Embedded content.
Palpable content.
Contexts in which this element can be used:
Where embedded content is expected.
Content model:
Transparent, but with no interactive content descendants except for a elements, img elements with usemap attributes, button elements, input elements whose type attribute are in the Checkbox or Radio Button states, input elements that are buttons, and select elements with a multiple attribute or a display size greater than 1.
text/html 中的标签省略
哪个标签都不能省略。
Content attributes:
Global attributes
width — Horizontal dimension
height — Vertical dimension
Accessibility considerations:
For authors.
For implementers.
DOM interface:
typedef (CanvasRenderingContext2D or ImageBitmapRenderingContext or WebGLRenderingContext or WebGL2RenderingContext) RenderingContext;

[Exposed=Window]
interface HTMLCanvasElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute unsigned long width;
  [CEReactions] attribute unsigned long height;

  RenderingContext? getContext(DOMString contextId, optional any options = null);

  USVString toDataURL(optional DOMString type = "image/png", optional any quality);
  undefined toBlob(BlobCallback _callback, optional DOMString type = "image/png", optional any quality);
  OffscreenCanvas transferControlToOffscreen();
};

callback BlobCallback = undefined (Blob? blob);

The canvas element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, art, or other visual images on the fly.

Authors should not use the canvas element in a document when a more suitable element is available. For example, it is inappropriate to use a canvas element to render a page heading: if the desired presentation of the heading is graphically intense, it should be marked up using appropriate elements (typically h1) and then styled using CSS and supporting technologies such as shadow trees.

When authors use the canvas element, they must also provide content that, when presented to the user, conveys essentially the same function or purpose as the canvas's bitmap. This content may be placed as content of the canvas element. The contents of the canvas element, if any, are the element's fallback content.


In interactive visual media, if scripting is enabled for the canvas element, and if support for canvas elements has been enabled, then the canvas element represents embedded content consisting of a dynamically created image, the element's bitmap.

In non-interactive, static, visual media, if the canvas element has been previously associated with a rendering context (e.g. if the page was viewed in an interactive visual medium and is now being printed, or if some script that ran during the page layout process painted on the element), then the canvas element represents embedded content with the element's current bitmap and size. Otherwise, the element represents its fallback content instead.

In non-visual media, and in visual media if scripting is disabled for the canvas element or if support for canvas elements has been disabled, the canvas element represents its fallback content instead.

When a canvas element represents embedded content, the user can still focus descendants of the canvas element (in the fallback content). When an element is focused, it is the target of keyboard interaction events (even though the element itself is not visible). This allows authors to make an interactive canvas keyboard-accessible: authors should have a one-to-one mapping of interactive regions to focusable areas in the fallback content. (Focus has no effect on mouse interaction events.) [UIEVENTS]

An element whose nearest canvas element ancestor is being rendered and represents embedded content is an element that is being used as relevant canvas fallback content.


The canvas element has two attributes to control the size of the element's bitmap: width and height. These attributes, when specified, must have values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The width attribute defaults to 300, and the height attribute defaults to 150.

When setting the value of the width or height attribute, if the context mode of the canvas element is set to placeholder, the user agent must throw an "InvalidStateError" DOMException and leave the attribute's value unchanged.

The intrinsic dimensions of the canvas element when it represents embedded content are equal to the dimensions of the element's bitmap.

The user agent must use a square pixel density consisting of one pixel of image data per coordinate space unit for the bitmaps of a canvas and its rendering contexts.

A canvas element can be sized arbitrarily by a style sheet, its bitmap is then subject to the 'object-fit' CSS property.


The bitmaps of canvas elements, the bitmaps of ImageBitmap objects, as well as some of the bitmaps of rendering contexts, such as those described in the sections on the CanvasRenderingContext2D and ImageBitmapRenderingContext objects below, have an origin-clean flag, which can be set to true or false. Initially, when the canvas element or ImageBitmap object is created, its bitmap's origin-clean flag must be set to true.

A canvas element can have a rendering context bound to it. Initially, it does not have a bound rendering context. To keep track of whether it has a rendering context or not, and what kind of rendering context it is, a canvas also has a canvas context mode, which is initially none but can be changed to either placeholder, 2d, bitmaprenderer, webgl, or webgl2 by algorithms defined in this specification.

When its canvas context mode is none, a canvas element has no rendering context, and its bitmap must be transparent black with an intrinsic width equal to the numeric value of the element's width attribute and an intrinsic height equal to the numeric value of the element's height attribute, those values being interpreted in CSS pixels, and being updated as the attributes are set, changed, or removed.

When its canvas context mode is placeholder, a canvas element has no rendering context. It serves as a placeholder for an OffscreenCanvas object, and the content of the canvas element is updated by calling the commit() method of the OffscreenCanvas object's rendering context.

When a canvas element represents embedded content, it provides a paint source whose width is the element's intrinsic width, whose height is the element's intrinsic height, and whose appearance is the element's bitmap.

Whenever the width and height content attributes are set, removed, changed, or redundantly set to the value they already have, then the user agent must perform the action from the row of the following table that corresponds to the canvas element's context mode.

Context Mode

Action

2d

Follow the steps to set bitmap dimensions to the numeric values of the width and height content attributes.

webgl or webgl2

Follow the behavior defined in the WebGL specifications. [WEBGL]

bitmaprenderer

If the context's bitmap mode is set to blank, run the steps to set an ImageBitmapRenderingContext's output bitmap, passing the canvas element's rendering context.

placeholder

Do nothing.

none

Do nothing.

HTMLCanvasElement/height

Support in all current engines.

Firefox1.5+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

HTMLCanvasElement/width

Support in all current engines.

Firefox1.5+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

The width and height IDL attributes must reflect the respective content attributes of the same name, with the same defaults.


context = canvas . getContext(contextId [, options ] )

HTMLCanvasElement/getContext

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Returns an object that exposes an API for drawing on the canvas. contextId specifies the desired API: "2d", "bitmaprenderer", "webgl", or "webgl2". options is handled by that API.

This specification defines the "2d" and "bitmaprenderer" contexts below. The WebGL specifications define the "webgl" and "webgl2" contexts. [WEBGL]

Returns null if contextId is not supported, or if the canvas has already been initialized with another context type (e.g., trying to get a "2d" context after getting a "webgl" context).

The getContext(contextId, options) method of the canvas element, when invoked, must run these steps:

  1. If options is not an object, then set options to null.

  2. Set options to the result of converting options to a JavaScript value.

  3. Run the steps in the cell of the following table whose column header matches this canvas element's canvas context mode and whose row header matches contextId:

    none 2d bitmaprenderer webgl or webgl2 placeholder
    "2d" Follow the 2D context creation algorithm defined in the section below, passing it this canvas element and options, to obtain a CanvasRenderingContext2D object; if this does not throw an exception, then set this canvas element's context mode to 2d, and return the CanvasRenderingContext2D object. Return the same object as was returned the last time the method was invoked with this same first argument. Return null. Return null. Throw an "InvalidStateError" DOMException.
    "bitmaprenderer" Follow the ImageBitmapRenderingContext creation algorithm defined in the section below, passing it this canvas element and options, to obtain an ImageBitmapRenderingContext object; then set this canvas element's context mode to bitmaprenderer, and return the ImageBitmapRenderingContext object. Return null. Return the same object as was returned the last time the method was invoked with this same first argument. Return null. Throw an "InvalidStateError" DOMException.
    "webgl" or "webgl2", if the user agent supports the WebGL feature in its current configuration Follow the instructions given in the WebGL specifications' Context Creation sections to obtain a WebGLRenderingContext, WebGL2RenderingContext, or null; if the returned value is null, then return null; otherwise, set this canvas element's context mode to webgl or webgl2, and return the WebGLRenderingContext or WebGL2RenderingContext object. [WEBGL] Return null. Return null. Return the same object as was returned the last time the method was invoked with this same first argument. Throw an "InvalidStateError" DOMException.
    An unsupported value* Return null. Return null. Return null. Return null. Throw an "InvalidStateError" DOMException.

    * For example, the "webgl" or "webgl2" value in the case of a user agent having exhausted the graphics hardware's abilities and having no software fallback implementation.


url = canvas . toDataURL( [ type [, quality ] ] )

HTMLCanvasElement/toDataURL

Support in all current engines.

Firefox2+Safari4+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

Returns a data: URL for the image in the canvas.

The first argument, if provided, controls the type of the image to be returned (e.g. PNG or JPEG). The default is "image/png"; that type is also used if the given type isn't supported. The second argument applies if the type is an image format that supports variable quality (such as "image/jpeg"), and is a number in the range 0.0 to 1.0 inclusive indicating the desired quality level for the resulting image.

When trying to use types other than "image/png", authors can check if the image was really returned in the requested format by checking to see if the returned string starts with one of the exact strings "data:image/png," or "data:image/png;". If it does, the image is PNG, and thus the requested type was not supported. (The one exception to this is if the canvas has either no height or no width, in which case the result might simply be "data:,".)

canvas . toBlob(callback [, type [, quality ] ] )

HTMLCanvasElement/toBlob

Support in all current engines.

Firefox18+Safari11+Chrome50+
Opera37+Edge79+
Edge (Legacy)NoInternet Explorer🔰 10+
Firefox Android18+Safari iOS11+Chrome Android50+WebView Android50+Samsung Internet5.0+Opera Android37+

Creates a Blob object representing a file containing the image in the canvas, and invokes a callback with a handle to that object.

The second argument, if provided, controls the type of the image to be returned (e.g. PNG or JPEG). The default is "image/png"; that type is also used if the given type isn't supported. The third argument applies if the type is an image format that supports variable quality (such as "image/jpeg"), and is a number in the range 0.0 to 1.0 inclusive indicating the desired quality level for the resulting image.

canvas . transferControlToOffscreen()

HTMLCanvasElement/transferControlToOffscreen

Firefox🔰 44+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome Android69+WebView Android69+Samsung Internet10.0+Opera Android48+

Returns a newly created OffscreenCanvas object that uses the canvas element as a placeholder. Once the canvas element has become a placeholder for an OffscreenCanvas object, its intrinsic size can no longer be changed, and it cannot have a rendering context. The content of the placeholder canvas is updated by calling the commit() method of the OffscreenCanvas object's rendering context.

The toDataURL(type, quality) method, when invoked, must run these steps:

  1. If this canvas element's bitmap's origin-clean flag is set to false, then throw a "SecurityError" DOMException.

  2. If this canvas element's bitmap has no pixels (i.e. either its horizontal dimension or its vertical dimension is zero) then return the string "data:,". (This is the shortest data: URL; it represents the empty string in a text/plain resource.)

  3. Let file be a serialization of this canvas element's bitmap as a file, passing type and quality if given.

  4. If file is null then return "data:,".

  5. Return a data: URL representing file. [RFC2397]

The toBlob(callback, type, quality) method, when invoked, must run these steps:

  1. If this canvas element's bitmap's origin-clean flag is set to false, then throw a "SecurityError" DOMException.

  2. Let result be null.

  3. If this canvas element's bitmap has pixels (i.e., neither its horizontal dimension nor its vertical dimension is zero), then set result to a copy of this canvas element's bitmap.

  4. Run these steps in parallel:

    1. If result is non-null, then set result to a serialization of result as a file with type and quality if given.

    2. Queue an element task on the canvas blob serialization task source given the canvas element to run these steps:

      1. If result is non-null, then set result to a new Blob object, created in the relevant Realm of this canvas element, representing result. [FILEAPI]

      2. Invoke callback with « result ».

The transferControlToOffscreen() method, when invoked, must run these steps:

  1. If this canvas element's context mode is not set to none, throw an "InvalidStateError" DOMException.

  2. Let offscreenCanvas be a new OffscreenCanvas object with its width and height equal to the values of the width and height content attributes of this canvas element.

  3. Set the placeholder canvas element of offscreenCanvas to be a weak reference to this canvas element.

  4. Set this canvas element's context mode to placeholder.

  5. Return offscreenCanvas.

4.12.5.1 The 2D rendering context

CanvasRenderingContext2D

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

CanvasImageSource

CanvasGradient

Support in all current engines.

Firefox1.5+Safari5.1+Chrome6+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS6+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android10.1+

CanvasPattern

Support in all current engines.

Firefox1.5+Safari4+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

TextMetrics

Support in all current engines.

Firefox1.5+Safari4+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android31+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

ImageData

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+
typedef (HTMLImageElement or
         SVGImageElement) HTMLOrSVGImageElement;

typedef (HTMLOrSVGImageElement or
         HTMLVideoElement or
         HTMLCanvasElement or
         ImageBitmap or
         OffscreenCanvas) CanvasImageSource;

enum CanvasFillRule { "nonzero", "evenodd" };

dictionary CanvasRenderingContext2DSettings {
  boolean alpha = true;
  boolean desynchronized = false;
};

enum ImageSmoothingQuality { "low", "medium", "high" };

[Exposed=Window]
interface CanvasRenderingContext2D {
  // back-reference to the canvas
  readonly attribute HTMLCanvasElement canvas;

  CanvasRenderingContext2DSettings getContextAttributes();
};
CanvasRenderingContext2D includes CanvasState;
CanvasRenderingContext2D includes CanvasTransform;
CanvasRenderingContext2D includes CanvasCompositing;
CanvasRenderingContext2D includes CanvasImageSmoothing;
CanvasRenderingContext2D includes CanvasFillStrokeStyles;
CanvasRenderingContext2D includes CanvasShadowStyles;
CanvasRenderingContext2D includes CanvasFilters;
CanvasRenderingContext2D includes CanvasRect;
CanvasRenderingContext2D includes CanvasDrawPath;
CanvasRenderingContext2D includes CanvasUserInterface;
CanvasRenderingContext2D includes CanvasText;
CanvasRenderingContext2D includes CanvasDrawImage;
CanvasRenderingContext2D includes CanvasImageData;
CanvasRenderingContext2D includes CanvasPathDrawingStyles;
CanvasRenderingContext2D includes CanvasTextDrawingStyles;
CanvasRenderingContext2D includes CanvasPath;

interface mixin CanvasState {
  // state
  undefined save(); // push state on state stack
  undefined restore(); // pop state stack and restore state
};

interface mixin CanvasTransform {
  // transformations (default transform is the identity matrix)
  undefined scale(unrestricted double x, unrestricted double y);
  undefined rotate(unrestricted double angle);
  undefined translate(unrestricted double x, unrestricted double y);
  undefined transform(unrestricted double a, unrestricted double b, unrestricted double c, unrestricted double d, unrestricted double e, unrestricted double f);

  [NewObject] DOMMatrix getTransform();
  undefined setTransform(unrestricted double a, unrestricted double b, unrestricted double c, unrestricted double d, unrestricted double e, unrestricted double f);
  undefined setTransform(optional DOMMatrix2DInit transform = {});
  undefined resetTransform();

};

interface mixin CanvasCompositing {
  // compositing
  attribute unrestricted double globalAlpha; // (default 1.0)
  attribute DOMString globalCompositeOperation; // (default source-over)
};

interface mixin CanvasImageSmoothing {
  // image smoothing
  attribute boolean imageSmoothingEnabled; // (default true)
  attribute ImageSmoothingQuality imageSmoothingQuality; // (default low)

};

interface mixin CanvasFillStrokeStyles {
  // colors and styles (see also the CanvasPathDrawingStyles and CanvasTextDrawingStyles interfaces)
  attribute (DOMString or CanvasGradient or CanvasPattern) strokeStyle; // (default black)
  attribute (DOMString or CanvasGradient or CanvasPattern) fillStyle; // (default black)
  CanvasGradient createLinearGradient(double x0, double y0, double x1, double y1);
  CanvasGradient createRadialGradient(double x0, double y0, double r0, double x1, double y1, double r1);
  CanvasPattern? createPattern(CanvasImageSource image, [LegacyNullToEmptyString] DOMString repetition);

};

interface mixin CanvasShadowStyles {
  // shadows
  attribute unrestricted double shadowOffsetX; // (default 0)
  attribute unrestricted double shadowOffsetY; // (default 0)
  attribute unrestricted double shadowBlur; // (default 0)
  attribute DOMString shadowColor; // (default transparent black)
};

interface mixin CanvasFilters {
  // filters
  attribute DOMString filter; // (default "none")
};

interface mixin CanvasRect {
  // rects
  undefined clearRect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h);
  undefined fillRect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h);
  undefined strokeRect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h);
};

interface mixin CanvasDrawPath {
  // path API (see also CanvasPath)
  undefined beginPath();
  undefined fill(optional CanvasFillRule fillRule = "nonzero");
  undefined fill(Path2D path, optional CanvasFillRule fillRule = "nonzero");
  undefined stroke();
  undefined stroke(Path2D path);
  undefined clip(optional CanvasFillRule fillRule = "nonzero");
  undefined clip(Path2D path, optional CanvasFillRule fillRule = "nonzero");
  boolean isPointInPath(unrestricted double x, unrestricted double y, optional CanvasFillRule fillRule = "nonzero");
  boolean isPointInPath(Path2D path, unrestricted double x, unrestricted double y, optional CanvasFillRule fillRule = "nonzero");
  boolean isPointInStroke(unrestricted double x, unrestricted double y);
  boolean isPointInStroke(Path2D path, unrestricted double x, unrestricted double y);
};

interface mixin CanvasUserInterface {
  undefined drawFocusIfNeeded(Element element);
  undefined drawFocusIfNeeded(Path2D path, Element element);
  undefined scrollPathIntoView();
  undefined scrollPathIntoView(Path2D path);
};

interface mixin CanvasText {
  // text (see also the CanvasPathDrawingStyles and CanvasTextDrawingStyles interfaces)
  undefined fillText(DOMString text, unrestricted double x, unrestricted double y, optional unrestricted double maxWidth);
  undefined strokeText(DOMString text, unrestricted double x, unrestricted double y, optional unrestricted double maxWidth);
  TextMetrics measureText(DOMString text);
};

interface mixin CanvasDrawImage {
  // drawing images
  undefined drawImage(CanvasImageSource image, unrestricted double dx, unrestricted double dy);
  undefined drawImage(CanvasImageSource image, unrestricted double dx, unrestricted double dy, unrestricted double dw, unrestricted double dh);
  undefined drawImage(CanvasImageSource image, unrestricted double sx, unrestricted double sy, unrestricted double sw, unrestricted double sh, unrestricted double dx, unrestricted double dy, unrestricted double dw, unrestricted double dh);
};

interface mixin CanvasImageData {
  // pixel manipulation
  ImageData createImageData(long sw, long sh);
  ImageData createImageData(ImageData imagedata);
  ImageData getImageData(long sx, long sy, long sw, long sh);
  undefined putImageData(ImageData imagedata, long dx, long dy);
  undefined putImageData(ImageData imagedata, long dx, long dy, long dirtyX, long dirtyY, long dirtyWidth, long dirtyHeight);
};

enum CanvasLineCap { "butt", "round", "square" };
enum CanvasLineJoin { "round", "bevel", "miter" };
enum CanvasTextAlign { "start", "end", "left", "right", "center" };
enum CanvasTextBaseline { "top", "hanging", "middle", "alphabetic", "ideographic", "bottom" };
enum CanvasDirection { "ltr", "rtl", "inherit" };

interface mixin CanvasPathDrawingStyles {
  // line caps/joins
  attribute unrestricted double lineWidth; // (default 1)
  attribute CanvasLineCap lineCap; // (default "butt")
  attribute CanvasLineJoin lineJoin; // (default "miter")
  attribute unrestricted double miterLimit; // (default 10)

  // dashed lines
  undefined setLineDash(sequence<unrestricted double> segments); // default empty
  sequence<unrestricted double> getLineDash();
  attribute unrestricted double lineDashOffset;
};

interface mixin CanvasTextDrawingStyles {
  // text
  attribute DOMString font; // (default 10px sans-serif)
  attribute CanvasTextAlign textAlign; // (default: "start")
  attribute CanvasTextBaseline textBaseline; // (default: "alphabetic")
  attribute CanvasDirection direction; // (default: "inherit")
};

interface mixin CanvasPath {
  // shared path API methods
  undefined closePath();
  undefined moveTo(unrestricted double x, unrestricted double y);
  undefined lineTo(unrestricted double x, unrestricted double y);
  undefined quadraticCurveTo(unrestricted double cpx, unrestricted double cpy, unrestricted double x, unrestricted double y);
  undefined bezierCurveTo(unrestricted double cp1x, unrestricted double cp1y, unrestricted double cp2x, unrestricted double cp2y, unrestricted double x, unrestricted double y);
  undefined arcTo(unrestricted double x1, unrestricted double y1, unrestricted double x2, unrestricted double y2, unrestricted double radius); 
  undefined rect(unrestricted double x, unrestricted double y, unrestricted double w, unrestricted double h);
  undefined arc(unrestricted double x, unrestricted double y, unrestricted double radius, unrestricted double startAngle, unrestricted double endAngle, optional boolean anticlockwise = false); 
  undefined ellipse(unrestricted double x, unrestricted double y, unrestricted double radiusX, unrestricted double radiusY, unrestricted double rotation, unrestricted double startAngle, unrestricted double endAngle, optional boolean anticlockwise = false); 
};

[Exposed=(Window,Worker)]
interface CanvasGradient {
  // opaque object
  undefined addColorStop(double offset, DOMString color);
};

[Exposed=(Window,Worker)]
interface CanvasPattern {
  // opaque object
  undefined setTransform(optional DOMMatrix2DInit transform = {});
};

[Exposed=(Window,Worker)]
interface TextMetrics {
  // x-direction
  readonly attribute double width; // advance width
  readonly attribute double actualBoundingBoxLeft;
  readonly attribute double actualBoundingBoxRight;

  // y-direction
  readonly attribute double fontBoundingBoxAscent;
  readonly attribute double fontBoundingBoxDescent;
  readonly attribute double actualBoundingBoxAscent;
  readonly attribute double actualBoundingBoxDescent;
  readonly attribute double emHeightAscent;
  readonly attribute double emHeightDescent;
  readonly attribute double hangingBaseline;
  readonly attribute double alphabeticBaseline;
  readonly attribute double ideographicBaseline;
};

[Exposed=(Window,Worker),
 Serializable]
interface ImageData {
  constructor(unsigned long sw, unsigned long sh);
  constructor(Uint8ClampedArray data, unsigned long sw, optional unsigned long sh);

  readonly attribute unsigned long width;
  readonly attribute unsigned long height;
  readonly attribute Uint8ClampedArray data;
};

[Exposed=(Window,Worker)]
interface Path2D {
  constructor(optional (Path2D or DOMString) path);

  undefined addPath(Path2D path, optional DOMMatrix2DInit transform = {});
};
Path2D includes CanvasPath;

To maintain compatibility with existing web content, user agents need to enumerate methods defined in CanvasUserInterface immediately after the stroke() method on CanvasRenderingContext2D objects.

context = canvas . getContext('2d' [, { [ alpha: true ] [, desynchronized: false ] } ] )

Returns a CanvasRenderingContext2D object that is permanently bound to a particular canvas element.

If the alpha member is false, then the context is forced to always be opaque.

If the desynchronized member is true, then the context might be desynchronized.

context . canvas

CanvasRenderingContext2D/canvas

Support in all current engines.

Firefox1.5+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the canvas element.

attributes = canvas . getContextAttributes()

Returns an object whose:

A CanvasRenderingContext2D object has an output bitmap that is initialized when the object is created.

The output bitmap has an origin-clean flag, which can be set to true or false. Initially, when one of these bitmaps is created, its origin-clean flag must be set to true.

The CanvasRenderingContext2D object also has an alpha boolean. When a CanvasRenderingContext2D object's alpha is false, then its alpha channel must be fixed to 1.0 (fully opaque) for all pixels, and attempts to change the alpha component of any pixel must be silently ignored.

Thus, the bitmap of such a context starts off as opaque black instead of transparent black; clearRect() always results in opaque black pixels, every fourth byte from getImageData() is always 255, the putImageData() method effectively ignores every fourth byte in its input, and so on. However, the alpha component of styles and images drawn onto the canvas are still honoured up to the point where they would impact the output bitmap's alpha channel; for instance, drawing a 50% transparent white square on a freshly created output bitmap with its alpha set to false will result in a fully-opaque gray square.

The CanvasRenderingContext2D object also has a desynchronized boolean. When a CanvasRenderingContext2D object's desynchronized is true, then the user agent may optimize the rendering of the canvas to reduce the latency, as measured from input events to rasterization, by desynchronizing the canvas paint cycle from the event loop, bypassing the ordinary user agent rendering algorithm, or both. Insofar as this mode involves bypassing the usual paint mechanisms, rasterization, or both, it might introduce visible tearing artifacts.

The user agent usually renders on a buffer which is not being displayed, quickly swapping it and the one being scanned out for presentation; the former buffer is called back buffer and the latter front buffer. A popular technique for reducing latency is called front buffer rendering, also known as single buffer rendering, where rendering happens in parallel and racily with the scanning out process. This technique reduces the latency at the price of potentially introducing tearing artifacts and can be used to implement in total or part of the desynchronized boolean. [MULTIPLEBUFFERING]

The desynchronized boolean can be useful when implementing certain kinds of applications, such as drawing applications, where the latency between input and rasterization is critical.

The getContextAttributes() method, when invoked, must return a CanvasRenderingContext2DSettings dictionary containing the following members:


The CanvasRenderingContext2D 2D rendering context represents a flat linear Cartesian surface whose origin (0,0) is at the top left corner, with the coordinate space having x values increasing when going right, and y values increasing when going down. The x-coordinate of the right-most edge is equal to the width of the rendering context's output bitmap in CSS pixels; similarly, the y-coordinate of the bottom-most edge is equal to the height of the rendering context's output bitmap in CSS pixels.

The size of the coordinate space does not necessarily represent the size of the actual bitmaps that the user agent will use internally or during rendering. On high-definition displays, for instance, the user agent may internally use bitmaps with four device pixels per unit in the coordinate space, so that the rendering remains at high quality throughout. Anti-aliasing can similarly be implemented using oversampling with bitmaps of a higher resolution than the final image on the display.

Using CSS pixels to describe the size of a rendering context's output bitmap does not mean that when rendered the canvas will cover an equivalent area in CSS pixels. CSS pixels are reused for ease of integration with CSS features, such as text layout.

In other words, the canvas element below's rendering context has a 200x200 output bitmap (which internally uses CSS pixels as a unit for ease of integration with CSS) and is rendered as 100x100 CSS pixels:

<canvas width=200 height=200 style=width:100px;height:100px>

The 2D context creation algorithm, which is passed a target (a canvas element) and options, consists of running these steps:

  1. Let settings be the result of converting options to the dictionary type CanvasRenderingContext2DSettings. (This can throw an exception.).

  2. Let context be a new CanvasRenderingContext2D object.

  3. Initialize context's canvas attribute to point to target.

  4. Set context's output bitmap to the same bitmap as target's bitmap (so that they are shared).

  5. Set bitmap dimensions to the numeric values of target's width and height content attributes.

  6. Set context's alpha to settings's alpha.

  7. Set context's desynchronized to settings's desynchronized.

  8. Return context.


When the user agent is to set bitmap dimensions to width and height, it must run these steps:

  1. Reset the rendering context to its default state.

  2. Resize the output bitmap to the new width and height and clear it to transparent black.

  3. Let canvas be the canvas element to which the rendering context's canvas attribute was initialized.

  4. If the numeric value of canvas's width content attribute differs from width, then set canvas's width content attribute to the shortest possible string representing width as a valid non-negative integer.

  5. If the numeric value of canvas's height content attribute differs from height, then set canvas's height content attribute to the shortest possible string representing height as a valid non-negative integer.

Only one square appears to be drawn in the following example:

// canvas is a reference to a <canvas> element
var context = canvas.getContext('2d');
context.fillRect(0,0,50,50);
canvas.setAttribute('width', '300'); // clears the canvas
context.fillRect(0,100,50,50);
canvas.width = canvas.width; // clears the canvas
context.fillRect(100,0,50,50); // only this square remains

The canvas attribute must return the value it was initialized to when the object was created.


The CanvasFillRule enumeration is used to select the fill rule algorithm by which to determine if a point is inside or outside a path.

The value "nonzero" value indicates the nonzero winding rule, wherein a point is considered to be outside a shape if the number of times a half-infinite straight line drawn from that point crosses the shape's path going in one direction is equal to the number of times it crosses the path going in the other direction.

The "evenodd" value indicates the even-odd rule, wherein a point is considered to be outside a shape if the number of times a half-infinite straight line drawn from that point crosses the shape's path is even.

If a point is not outside a shape, it is inside the shape.


The ImageSmoothingQuality enumeration is used to express a preference for the interpolation quality to use when smoothing images.

The "low" value indicates a preference for a low level of image interpolation quality. Low-quality image interpolation may be more computationally efficient than higher settings.

The "medium" value indicates a preference for a medium level of image interpolation quality.

The "high" value indicates a preference for a high level of image interpolation quality. High-quality image interpolation may be more computationally expensive than lower settings.

Bilinear scaling is an example of a relatively fast, lower-quality image-smoothing algorithm. Bicubic or Lanczos scaling are examples of image-smoothing algorithms that produce higher-quality output. This specification does not mandate that specific interpolation algorithms be used.

4.12.5.1.1 实现说明

This section is non-normative.

输出位图,当没有被用户代理直接直接显示时, 实现中可以只记录已经应用的绘图操作序列,而不更新整个位图,直到需要位图的实际数据时。 (例如调用了 drawImage()createImageBitmap() 工厂方法) 很多情况下这样可以提高内存的使用效率。

canvas 元素的位图在实践中总是需要的, 渲染上下文的 输出位图(如果有的话) 只是 canvas 元素的位图的别名。

有时也会需要额外的位图,比如为了使 canvas 在绘制大小与其 固有尺寸 不同时更快, 或者为了实现双缓冲来使得绘制命令继续执行的同时图像可以持续地更新(比如在页面滚动时)。

4.12.5.1.2 Canvas 状态

实现 CanvasState 接口的对象维护一个绘图状态栈。 绘图状态 这样组成:

当前默认路径 和渲染上下文的位图不属于绘图状态。 当前默认路径 是持久的,只能使用 beginPath() 方法重置。 位图取决于渲染上下文是否(以及如何)绑定到 canvas 元素。

context . save()

CanvasRenderingContext2D/save

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

把当前状态推入栈中。

context . restore()

CanvasRenderingContext2D/restore

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

把栈顶部状态弹出并恢复到这个状态。

save() 方法被调用时, 必须把当前绘图状态拷贝一份然后推入到绘图状态栈。

restore() 方法被调用时, 必须把绘图状态栈顶的项目弹出,按它的描述重置绘图状态。 如果没有保存的状态,这个方法必须什么都不做。

当用户代理要 重置渲染上下文到默认状态 时, 它必须清除绘图状态栈,并把构成 绘图状态 的所有东西设置回初始值。

4.12.5.1.3 Line styles
context . lineWidth [ = value ]

CanvasRenderingContext2D/lineWidth

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
styles . lineWidth [ = value ]

Returns the current line width.

Can be set, to change the line width. Values that are not finite values greater than zero are ignored.

context . lineCap [ = value ]

CanvasRenderingContext2D/lineCap

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
styles . lineCap [ = value ]

Returns the current line cap style.

Can be set, to change the line cap style.

The possible line cap styles are "butt", "round", and "square". Other values are ignored.

context . lineJoin [ = value ]

CanvasRenderingContext2D/lineJoin

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
styles . lineJoin [ = value ]

Returns the current line join style.

Can be set, to change the line join style.

The possible line join styles are "bevel", "round", and "miter". Other values are ignored.

context . miterLimit [ = value ]

CanvasRenderingContext2D/miterLimit

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
styles . miterLimit [ = value ]

Returns the current miter limit ratio.

Can be set, to change the miter limit ratio. Values that are not finite values greater than zero are ignored.

context . setLineDash(segments)

CanvasRenderingContext2D/setLineDash

Support in all current engines.

Firefox27+Safari7+Chrome23+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android27+Safari iOS7+Chrome Android25+WebView Android37+Samsung Internet1.5+Opera Android14+
styles . setLineDash(segments)

Sets the current line dash pattern (as used when stroking). The argument is a list of distances for which to alternately have the line on and the line off.

segments = context . getLineDash()

CanvasRenderingContext2D/getLineDash

Support in all current engines.

Firefox27+Safari7+Chrome23+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android27+Safari iOS7+Chrome Android25+WebView Android37+Samsung Internet1.5+Opera Android14+
segments = styles . getLineDash()

Returns a copy of the current line dash pattern. The array returned will always have an even number of entries (i.e. the pattern is normalized).

context . lineDashOffset

CanvasRenderingContext2D/lineDashOffset

Support in all current engines.

Firefox27+Safari7+Chrome23+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android27+Safari iOS7+Chrome Android25+WebView Android37+Samsung Internet1.5+Opera Android14+
styles . lineDashOffset

Returns the phase offset (in the same units as the line dash pattern).

Can be set, to change the phase offset. Values that are not finite values are ignored.

Objects that implement the CanvasPathDrawingStyles interface have attributes and methods (defined in this section) that control how lines are treated by the object.

The lineWidth attribute gives the width of lines, in coordinate space units. On getting, it must return the current value. On setting, zero, negative, infinite, and NaN values must be ignored, leaving the value unchanged; other values must change the current value to the new value.

When the object implementing the CanvasPathDrawingStyles interface is created, the lineWidth attribute must initially have the value 1.0.


The lineCap attribute defines the type of endings that UAs will place on the end of lines. The three valid values are "butt", "round", and "square".

On getting, it must return the current value. On setting, the current value must be changed to the new value.

When the object implementing the CanvasPathDrawingStyles interface is created, the lineCap attribute must initially have the value "butt".


The lineJoin attribute defines the type of corners that UAs will place where two lines meet. The three valid values are "bevel", "round", and "miter".

On getting, it must return the current value. On setting, the current value must be changed to the new value.

When the object implementing the CanvasPathDrawingStyles interface is created, the lineJoin attribute must initially have the value "miter".


When the lineJoin attribute has the value "miter", strokes use the miter limit ratio to decide how to render joins. The miter limit ratio can be explicitly set using the miterLimit attribute. On getting, it must return the current value. On setting, zero, negative, infinite, and NaN values must be ignored, leaving the value unchanged; other values must change the current value to the new value.

When the object implementing the CanvasPathDrawingStyles interface is created, the miterLimit attribute must initially have the value 10.0.


Each CanvasPathDrawingStyles object has a dash list, which is either empty or consists of an even number of non-negative numbers. Initially, the dash list must be empty.

The setLineDash() method, when invoked, must run these steps:

  1. Let a be the argument.

  2. If any value in a is not finite (e.g. an Infinity or a NaN value), or if any value is negative (less than zero), then return (without throwing an exception; user agents could show a message on a developer console, though, as that would be helpful for debugging).

  3. If the number of elements in a is odd, then let a be the concatenation of two copies of a.

  4. Let the object's dash list be a.

When the getLineDash() method is invoked, it must return a sequence whose values are the values of the object's dash list, in the same order.

It is sometimes useful to change the "phase" of the dash pattern, e.g. to achieve a "marching ants" effect. The phase can be set using the lineDashOffset attribute. On getting, it must return the current value. On setting, infinite and NaN values must be ignored, leaving the value unchanged; other values must change the current value to the new value.

When the object implementing the CanvasPathDrawingStyles interface is created, the lineDashOffset attribute must initially have the value 0.0.


When a user agent is to trace a path, given an object style that implements the CanvasPathDrawingStyles interface, it must run the following algorithm. This algorithm returns a new path.

  1. Let path be a copy of the path being traced.

  2. Prune all zero-length line segments from path.

  3. Remove from path any subpaths containing no lines (i.e. subpaths with just one point).

  4. Replace each point in each subpath of path other than the first point and the last point of each subpath by a join that joins the line leading to that point to the line leading out of that point, such that the subpaths all consist of two points (a starting point with a line leading out of it, and an ending point with a line leading into it), one or more lines (connecting the points and the joins), and zero or more joins (each connecting one line to another), connected together such that each subpath is a series of one or more lines with a join between each one and a point on each end.

  5. Add a straight closing line to each closed subpath in path connecting the last point and the first point of that subpath; change the last point to a join (from the previously last line to the newly added closing line), and change the first point to a join (from the newly added closing line to the first line).

  6. If style's dash list is empty, then jump to the step labeled convert.

  7. Let pattern width be the concatenation of all the entries of style's dash list, in coordinate space units.

  8. For each subpath subpath in path, run the following substeps. These substeps mutate the subpaths in path in vivo.

    1. Let subpath width be the length of all the lines of subpath, in coordinate space units.

    2. Let offset be the value of style's lineDashOffset, in coordinate space units.

    3. While offset is greater than pattern width, decrement it by pattern width.

      While offset is less than zero, increment it by pattern width.

    4. Define L to be a linear coordinate line defined along all lines in subpath, such that the start of the first line in the subpath is defined as coordinate 0, and the end of the last line in the subpath is defined as coordinate subpath width.

    5. Let position be zero minus offset.

    6. Let index be 0.

    7. Let current state be off (the other states being on and zero-on).

    8. Dash on: Let segment length be the value of style's dash list's indexth entry.

    9. Increment position by segment length.

    10. If position is greater than subpath width, then end these substeps for this subpath and start them again for the next subpath; if there are no more subpaths, then jump to the step labeled convert instead.

    11. If segment length is nonzero, then let current state be on.

    12. Increment index by one.

    13. Dash off: Let segment length be the value of style's dash list's indexth entry.

    14. Let start be the offset position on L.

    15. Increment position by segment length.

    16. If position is less than zero, then jump to the step labeled post-cut.

    17. If start is less than zero, then let start be zero.

    18. If position is greater than subpath width, then let end be the offset subpath width on L. Otherwise, let end be the offset position on L.

    19. Jump to the first appropriate step:

      If segment length is zero and current state is off

      Do nothing, just continue to the next step.

      If current state is off

      Cut the line on which end finds itself short at end and place a point there, cutting in two the subpath that it was in; remove all line segments, joins, points, and subpaths that are between start and end; and finally place a single point at start with no lines connecting to it.

      The point has a directionality for the purposes of drawing line caps (see below). The directionality is the direction that the original line had at that point (i.e. when L was defined above).

      Otherwise

      Cut the line on which start finds itself into two at start and place a point there, cutting in two the subpath that it was in, and similarly cut the line on which end finds itself short at end and place a point there, cutting in two the subpath that it was in, and then remove all line segments, joins, points, and subpaths that are between start and end.

      If start and end are the same point, then this results in just the line being cut in two and two points being inserted there, with nothing being removed, unless a join also happens to be at that point, in which case the join must be removed.

    20. Post-cut: If position is greater than subpath width, then jump to the step labeled convert.

    21. If segment length is greater than zero, then let positioned-at-on-dash be false.

    22. Increment index by one. If it is equal to the number of entries in style's dash list, then let index be 0.

    23. Return to the step labeled dash on.

  9. Convert: This is the step that converts the path to a new path that represents its stroke.

    Create a new path that describes the edge of the areas that would be covered if a straight line of length equal to style's lineWidth was swept along each subpath in path while being kept at an angle such that the line is orthogonal to the path being swept, replacing each point with the end cap necessary to satisfy style's lineCap attribute as described previously and elaborated below, and replacing each join with the join necessary to satisfy style's lineJoin type, as defined below.

    Caps: Each point has a flat edge perpendicular to the direction of the line coming out of it. This is then augmented according to the value of style's lineCap. The "butt" value means that no additional line cap is added. The "round" value means that a semi-circle with the diameter equal to style's lineWidth width must additionally be placed on to the line coming out of each point. The "square" value means that a rectangle with the length of style's lineWidth width and the width of half style's lineWidth width, placed flat against the edge perpendicular to the direction of the line coming out of the point, must be added at each point.

    Points with no lines coming out of them must have two caps placed back-to-back as if it was really two points connected to each other by an infinitesimally short straight line in the direction of the point's directionality (as defined above).

    Joins: In addition to the point where a join occurs, two additional points are relevant to each join, one for each line: the two corners found half the line width away from the join point, one perpendicular to each line, each on the side furthest from the other line.

    A triangle connecting these two opposite corners with a straight line, with the third point of the triangle being the join point, must be added at all joins. The lineJoin attribute controls whether anything else is rendered. The three aforementioned values have the following meanings:

    The "bevel" value means that this is all that is rendered at joins.

    The "round" value means that an arc connecting the two aforementioned corners of the join, abutting (and not overlapping) the aforementioned triangle, with the diameter equal to the line width and the origin at the point of the join, must be added at joins.

    The "miter" value means that a second triangle must (if it can given the miter length) be added at the join, with one line being the line between the two aforementioned corners, abutting the first triangle, and the other two being continuations of the outside edges of the two joining lines, as long as required to intersect without going over the miter length.

    The miter length is the distance from the point where the join occurs to the intersection of the line edges on the outside of the join. The miter limit ratio is the maximum allowed ratio of the miter length to half the line width. If the miter length would cause the miter limit ratio (as set by style's miterLimit attribute) to be exceeded, then this second triangle must not be added.

    The subpaths in the newly created path must be oriented such that for any point, the number of times a half-infinite straight line drawn from that point crosses a subpath is even if and only if the number of times a half-infinite straight line drawn from that same point crosses a subpath going in one direction is equal to the number of times it crosses a subpath going in the other direction.

  10. Return the newly created path.

4.12.5.1.4 Text styles
context . font [ = value ]

CanvasRenderingContext2D/font

Support in all current engines.

Firefox3.5+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
styles . font [ = value ]

Returns the current font settings.

Can be set, to change the font. The syntax is the same as for the CSS 'font' property; values that cannot be parsed as CSS font values are ignored.

Relative keywords and lengths are computed relative to the font of the canvas element.

context . textAlign [ = value ]

CanvasRenderingContext2D/textAlign

Support in all current engines.

Firefox3.5+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
styles . textAlign [ = value ]

Returns the current text alignment settings.

Can be set, to change the alignment. The possible values are and their meanings are given below. Other values are ignored. The default is "start".

context . textBaseline [ = value ]

CanvasRenderingContext2D/textBaseline

Support in all current engines.

Firefox3.5+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
styles . textBaseline [ = value ]

Returns the current baseline alignment settings.

Can be set, to change the baseline alignment. The possible values and their meanings are given below. Other values are ignored. The default is "alphabetic".

context . direction [ = value ]

CanvasRenderingContext2D/direction

FirefoxNoSafari9+Chrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS9+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+
styles . direction [ = value ]

Returns the current directionality.

Can be set, to change the directionality. The possible values and their meanings are given below. Other values are ignored. The default is "inherit".

Objects that implement the CanvasTextDrawingStyles interface have attributes (defined in this section) that control how text is laid out (rasterized or outlined) by the object. Such objects can also have a font style source object. For CanvasRenderingContext2D objects, this is the canvas element given by the value of the context's canvas attribute. For OffscreenCanvasRenderingContext2D objects, this is the associated OffscreenCanvas object.

Font resolution for the font style source object requires a font source. This is determined for a given object implementing CanvasTextDrawingStyles by the following steps: [CSSFONTLOAD]

  1. If object's font style source object is a canvas element, return the element's node document.

  2. Otherwise, object's font style source object is an OffscreenCanvas object:

    1. Let global be object's relevant global object.

    2. If global is a Window object, then return global's associated Document.

    3. Assert: global implements WorkerGlobalScope.

    4. Return global.

This is an example of font resolution with a regular canvas element with ID c1.

const font = new FontFace("MyCanvasFont", "url(mycanvasfont.ttf)");
documents.fonts.add(font);

const context = document.getElementById("c1").getContext("2d");
document.fonts.ready.then(function() {
  context.font = "64px MyCanvasFont";
  context.fillText("hello", 0, 0);
});

In this example, the canvas will display text using mycanvasfont.ttf as its font.

This is an example of how font resolution can happen using OffscreenCanvas. Assuming a canvas element with ID c2 which is transferred to a worker like so:

const offscreenCanvas = document.getElementById("c2").transferControlToOffscreen();
worker.postMesage(offscreenCanvas, [offscreenCanvas]);

Then, in the worker:

self.onmessage = function(ev) {
  const transferredCanvas = ev.data;
  const context = transferredCanvas.getContext("2d");
  const font = new FontFace("MyFont", "url(myfont.ttf)");
  self.fonts.add(font);
  self.fonts.ready.then(function() {
    context.font = "64px MyFont";
    context.fillText("hello", 0, 0);
  });
};

In this example, the canvas will display a text using myfont.ttf. Notice that the font is only loaded inside the worker, and not in the document context.

The font IDL attribute, on setting, must be parsed as a CSS <'font'> value (but without supporting property-independent style sheet syntax like 'inherit'), and the resulting font must be assigned to the context, with the 'line-height' component forced to 'normal', with the 'font-size' component converted to CSS pixels, and with system fonts being computed to explicit values. If the new value is syntactically incorrect (including using property-independent style sheet syntax like 'inherit' or 'initial'), then it must be ignored, without assigning a new font value. [CSS]

Font family names must be interpreted in the context of the font style source object when the font is to be used; any fonts embedded using @font-face or loaded using FontFace objects that are visible to the font style source object must therefore be available once they are loaded. (Each font style source object has a font source, which determines what fonts are available.) If a font is used before it is fully loaded, or if the font style source object does not have that font in scope at the time the font is to be used, then it must be treated as if it was an unknown font, falling back to another as described by the relevant CSS specifications. [CSSFONTS] [CSSFONTLOAD]

On getting, the font attribute must return the serialized form of the current font of the context (with no 'line-height' component). [CSSOM]

For example, after the following statement:

context.font = 'italic 400 12px/2 Unknown Font, sans-serif';

...the expression context.font would evaluate to the string "italic 12px "Unknown Font", sans-serif". The "400" font-weight doesn't appear because that is the default value. The line-height doesn't appear because it is forced to "normal", the default value.

When the object implementing the CanvasTextDrawingStyles interface is created, the font of the context must be set to 10px sans-serif. When the 'font-size' component is set to lengths using percentages, 'em' or 'ex' units, or the 'larger' or 'smaller' keywords, these must be interpreted relative to the computed value of the 'font-size' property of the font style source object at the time that the attribute is set, if it is an element. When the 'font-weight' component is set to the relative values 'bolder' and 'lighter', these must be interpreted relative to the computed value of the 'font-weight' property of the font style source object at the time that the attribute is set, if it is an element. If the computed values are undefined for a particular case (e.g. because the font style source object is not an element or is not being rendered), then the relative keywords must be interpreted relative to the normal-weight 10px sans-serif default.

The textAlign IDL attribute, on getting, must return the current value. On setting, the current value must be changed to the new value. When the object implementing the CanvasTextDrawingStyles interface is created, the textAlign attribute must initially have the value start.

The textBaseline IDL attribute, on getting, must return the current value. On setting, the current value must be changed to the new value. When the object implementing the CanvasTextDrawingStyles interface is created, the textBaseline attribute must initially have the value alphabetic.

The direction IDL attribute, on getting, must return the current value. On setting, the current value must be changed to the new value. When the object implementing the CanvasTextDrawingStyles interface is created, the direction attribute must initially have the value "inherit".

The textAlign attribute's allowed keywords are as follows:

start

Align to the start edge of the text (left side in left-to-right text, right side in right-to-left text).

end

Align to the end edge of the text (right side in left-to-right text, left side in right-to-left text).

left

Align to the left.

right

Align to the right.

center

Align to the center.

The textBaseline attribute's allowed keywords correspond to alignment points in the font:

The top of the em square is roughly at the top of the glyphs in a font, the hanging baseline is where some glyphs like आ are anchored, the middle is half-way between the top of the em square and the bottom of the em square, the alphabetic baseline is where characters like Á, ÿ, f, and Ω are anchored, the ideographic-under baseline is where glyphs like 私 and 達 are anchored, and the bottom of the em square is roughly at the bottom of the glyphs in a font. The top and bottom of the bounding box can be far from these baselines, due to glyphs extending far outside the em square.

The keywords map to these alignment points as follows:

top
The top of the em square
hanging
The hanging baseline
middle
The middle of the em square
alphabetic
The alphabetic baseline
ideographic
The ideographic-under baseline
bottom
The bottom of the em square

The direction attribute's allowed keywords are as follows:

ltr

Treat input to the text preparation algorithm as left-to-right text.

rtl

Treat input to the text preparation algorithm as right-to-left text.

inherit

Default to the directionality of the canvas element or Document as appropriate.

The text preparation algorithm is as follows. It takes as input a string text , a CanvasTextDrawingStyles object target, and an optional length maxWidth. It returns an array of glyph shapes, each positioned on a common coordinate space, a physical alignment whose value is one of left, right, and center, and an inline box. (Most callers of this algorithm ignore the physical alignment and the inline box.)

  1. If maxWidth was provided but is less than or equal to zero or equal to NaN, then return an empty array.

  2. Replace all ASCII whitespace in text with U+0020 SPACE characters.

  3. Let font be the current font of target, as given by that object's font attribute.

  4. Apply the appropriate step from the following list to determine the value of direction:

    If the target object's direction attribute has the value "ltr"
    Let direction be 'ltr'.
    If the target object's direction attribute has the value "rtl"
    Let direction be 'rtl'.
    If the target object's font style source object is an element
    Let direction be the directionality of the target object's font style source object.
    If the target object's font style source object is a Document with a non-null document element
    Let direction be the directionality of the target object's font style source object's document element.
    Otherwise
    Let direction be 'ltr'.
  5. Form a hypothetical infinitely-wide CSS line box containing a single inline box containing the text text, with all the properties at their initial values except the 'font' property of the inline box set to font, the 'direction' property of the inline box set to direction, and the 'white-space' property set to 'pre'. [CSS]

  6. If maxWidth was provided and the hypothetical width of the inline box in the hypothetical line box is greater than maxWidth CSS pixels, then change font to have a more condensed font (if one is available or if a reasonably readable one can be synthesized by applying a horizontal scale factor to the font) or a smaller font, and return to the previous step.

  7. The anchor point is a point on the inline box, and the physical alignment is one of the values left, right, and center. These variables are determined by the textAlign and textBaseline values as follows:

    Horizontal position:

    If textAlign is left
    If textAlign is start and direction is 'ltr'
    If textAlign is end and direction is 'rtl'
    Let the anchor point's horizontal position be the left edge of the inline box, and let physical alignment be left.
    If textAlign is right
    If textAlign is end and direction is 'ltr'
    If textAlign is start and direction is 'rtl'
    Let the anchor point's horizontal position be the right edge of the inline box, and let physical alignment be right.
    If textAlign is center
    Let the anchor point's horizontal position be half way between the left and right edges of the inline box, and let physical alignment be center.

    Vertical position:

    If textBaseline is top
    Let the anchor point's vertical position be the top of the em box of the first available font of the inline box.
    If textBaseline is hanging
    Let the anchor point's vertical position be the hanging baseline of the first available font of the inline box.
    If textBaseline is middle
    Let the anchor point's vertical position be half way between the bottom and the top of the em box of the first available font of the inline box.
    If textBaseline is alphabetic
    Let the anchor point's vertical position be the alphabetic baseline of the first available font of the inline box.
    If textBaseline is ideographic
    Let the anchor point's vertical position be the ideographic-under baseline of the first available font of the inline box.
    If textBaseline is bottom
    Let the anchor point's vertical position be the bottom of the em box of the first available font of the inline box.
  8. Let result be an array constructed by iterating over each glyph in the inline box from left to right (if any), adding to the array, for each glyph, the shape of the glyph as it is in the inline box, positioned on a coordinate space using CSS pixels with its origin is at the anchor point.

  9. Return result, physical alignment, and the inline box.

4.12.5.1.5 Building paths

Objects that implement the CanvasPath interface have a path. A path has a list of zero or more subpaths. Each subpath consists of a list of one or more points, connected by straight or curved line segments, and a flag indicating whether the subpath is closed or not. A closed subpath is one where the last point of the subpath is connected to the first point of the subpath by a straight line. Subpaths with only one point are ignored when painting the path.

Paths have a need new subpath flag. When this flag is set, certain APIs create a new subpath rather than extending the previous one. When a path is created, its need new subpath flag must be set.

When an object implementing the CanvasPath interface is created, its path must be initialized to zero subpaths.

context . moveTo(x, y)

CanvasRenderingContext2D/moveTo

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . moveTo(x, y)

Creates a new subpath with the given point.

context . closePath()

CanvasRenderingContext2D/closePath

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . closePath()

Marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath.

context . lineTo(x, y)

CanvasRenderingContext2D/lineTo

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . lineTo(x, y)

Adds the given point to the current subpath, connected to the previous one by a straight line.

context . quadraticCurveTo(cpx, cpy, x, y)

CanvasRenderingContext2D/quadraticCurveTo

Support in all current engines.

Firefox1.5+Safari3+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . quadraticCurveTo(cpx, cpy, x, y)

Adds the given point to the current subpath, connected to the previous one by a quadratic Bézier curve with the given control point.

context . bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

CanvasRenderingContext2D/bezierCurveTo

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

Adds the given point to the current subpath, connected to the previous one by a cubic Bézier curve with the given control points.

context . arcTo(x1, y1, x2, y2, radius)

CanvasRenderingContext2D/arcTo

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . arcTo(x1, y1, x2, y2, radius)

Adds an arc with the given control points and radius to the current subpath, connected to the previous point by a straight line.

Throws an "IndexSizeError" DOMException if the given radius is negative.

context . arc(x, y, radius, startAngle, endAngle [, anticlockwise ] )

CanvasRenderingContext2D/arc

Support in all current engines.

Firefox1.5+Safari3+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . arc(x, y, radius, startAngle, endAngle [, anticlockwise ] )

Adds points to the subpath such that the arc described by the circumference of the circle described by the arguments, starting at the given start angle and ending at the given end angle, going in the given direction (defaulting to clockwise), is added to the path, connected to the previous point by a straight line.

Throws an "IndexSizeError" DOMException if the given radius is negative.

context . ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle [, anticlockwise] )

CanvasRenderingContext2D/ellipse

Support in all current engines.

Firefox48+Safari9+Chrome31+
Opera18+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android48+Safari iOS9+Chrome Android31+WebView Android4.4.3+Samsung Internet2.0+Opera Android18+
path . ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle [, anticlockwise] )

Adds points to the subpath such that the arc described by the circumference of the ellipse described by the arguments, starting at the given start angle and ending at the given end angle, going in the given direction (defaulting to clockwise), is added to the path, connected to the previous point by a straight line.

Throws an "IndexSizeError" DOMException if the given radius is negative.

context . rect(x, y, w, h)

CanvasRenderingContext2D/rect

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
path . rect(x, y, w, h)

Adds a new closed subpath to the path, representing the given rectangle.

The following methods allow authors to manipulate the paths of objects implementing the CanvasPath interface.

For objects implementing the CanvasDrawPath and CanvasTransform interfaces, the points passed to the methods, and the resulting lines added to current default path by these methods, must be transformed according to the current transformation matrix before being added to the path.

The moveTo(x, y) method, when invoked, must run these steps:

  1. If either of the arguments are infinite or NaN, then return.

  2. Create a new subpath with the specified point as its first (and only) point.

When the user agent is to ensure there is a subpath for a coordinate (x, y) on a path, the user agent must check to see if the path has its need new subpath flag set. If it does, then the user agent must create a new subpath with the point (x, y) as its first (and only) point, as if the moveTo() method had been called, and must then unset the path's need new subpath flag.

The closePath() method, when invoked, must do nothing if the object's path has no subpaths. Otherwise, it must mark the last subpath as closed, create a new subpath whose first point is the same as the previous subpath's first point, and finally add this new subpath to the path.

If the last subpath had more than one point in its list of points, then this is equivalent to adding a straight line connecting the last point back to the first point of the last subpath, thus "closing" the subpath.


New points and the lines connecting them are added to subpaths using the methods described below. In all cases, the methods only modify the last subpath in the object's path.

The lineTo(x, y) method, when invoked, must run these steps:

  1. If either of the arguments are infinite or NaN, then return.

  2. If the object's path has no subpaths, then ensure there is a subpath for (x, y).

  3. Otherwise, connect the last point in the subpath to the given point (x, y) using a straight line, and then add the given point (x, y) to the subpath.

The quadraticCurveTo(cpx, cpy, x, y) method, when invoked, must run these steps:

  1. If any of the arguments are infinite or NaN, then return.

  2. Ensure there is a subpath for (cpx, cpy)

  3. Connect the last point in the subpath to the given point (x, y) using a quadratic Bézier curve with control point (cpx, cpy). [BEZIER]

  4. Add the given point (x, y) to the subpath.

The bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) method, when invoked, must run these steps:

  1. If any of the arguments are infinite or NaN, then return.

  2. Ensure there is a subpath for (cp1x, cp1y).

  3. Connect the last point in the subpath to the given point (x, y) using a cubic Bézier curve with control points (cp1x, cp1y) and (cp2x, cp2y). [BEZIER]

  4. Add the point (x, y) to the subpath.


The arcTo(x1, y1, x2, y2, radius) method, when invoked, must run these steps:

  1. If any of the arguments are infinite or NaN, then return.

  2. Ensure there is a subpath for (x1, y1).

  3. If radius is negative, then throw an "IndexSizeError" DOMException.

  4. Let the point (x0, y0) be the last point in the subpath, transformed by the inverse of the current transformation matrix (so that it is in the same coordinate system as the points passed to the method).

  5. If the point (x0, y0) is equal to the point (x1, y1), or if the point (x1, y1) is equal to the point (x2, y2), or if radius is zero, then add the point (x1, y1) to the subpath, and connect that point to the previous point (x0, y0) by a straight line.

  6. Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2) all lie on a single straight line, then add the point (x1, y1) to the subpath, and connect that point to the previous point (x0, y0) by a straight line.

  7. Otherwise, let The Arc be the shortest arc given by circumference of the circle that has radius radius, and that has one point tangent to the half-infinite line that crosses the point (x0, y0) and ends at the point (x1, y1), and that has a different point tangent to the half-infinite line that ends at the point (x1, y1) and crosses the point (x2, y2). The points at which this circle touches these two lines are called the start and end tangent points respectively. Connect the point (x0, y0) to the start tangent point by a straight line, adding the start tangent point to the subpath, and then connect the start tangent point to the end tangent point by The Arc, adding the end tangent point to the subpath.


The arc(x, y, radius, startAngle, endAngle, anticlockwise) method, when invoked, must run the ellipse method steps with this, x, y, radius, radius, 0, startAngle, endAngle, and anticlockwise.

This makes it equivalent to ellipse() except that both radii are equal and rotation is 0.

The ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) method, when invoked, must run the ellipse method steps with this, x, y, radiusX, radiusY, rotation, startAngle, endAngle, and anticlockwise.

The ellipse method steps, given canvasPath, x, y, radiusX, radiusY, rotation, startAngle, endAngle, and anticlockwise, are:

  1. If any of the arguments are infinite or NaN, then return.

  2. If either radiusX or radiusY are negative, then throw an "IndexSizeError" DOMException.

  3. If canvasPath's path has any subpaths, then add a straight line from the last point in the subpath to the start point of the arc.

  4. Add the start and end points of the arc to the subpath, and connect them with an arc. The arc and its start and end points are defined as follows:

    Consider an ellipse that has its origin at (x, y), that has a major-axis radius radiusX and a minor-axis radius radiusY, and that is rotated about its origin such that its semi-major axis is inclined rotation radians clockwise from the x-axis.

    If anticlockwise is false and endAngle-startAngle is equal to or greater than , or, if anticlockwise is true and startAngle-endAngle is equal to or greater than , then the arc is the whole circumference of this ellipse, and the point at startAngle along this circle's circumference, measured in radians clockwise from the ellipse's semi-major axis, acts as both the start point and the end point.

    Otherwise, the points at startAngle and endAngle along this circle's circumference, measured in radians clockwise from the ellipse's semi-major axis, are the start and end points respectively, and the arc is the path along the circumference of this ellipse from the start point to the end point, going anti-clockwise if anticlockwise is true, and clockwise otherwise. Since the points are on the ellipse, as opposed to being simply angles from zero, the arc can never cover an angle greater than radians.

    Even if the arc covers the entire circumference of the ellipse and there are no other points in the subpath, the path is not closed unless the closePath() method is appropriately invoked.


The rect(x, y, w, h) method, when invoked, must run these steps:

  1. If any of the arguments are infinite or NaN, then return.

  2. Create a new subpath containing just the four points (x, y), (x+w, y), (x+w, y+h), (x, y+h), in that order, with those four points connected by straight lines.

  3. Mark the subpath as closed.

  4. Create a new subpath with the point (x, y) as the only point in the subpath.

4.12.5.1.6 Path2D objects

Path2D

Support in all current engines.

Firefox31+Safari8+Chrome36+
Opera23+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android31+Safari iOS8+Chrome Android36+WebView Android37+Samsung Internet3.0+Opera Android24+

Path2D objects can be used to declare paths that are then later used on objects implementing the CanvasDrawPath interface. In addition to many of the APIs described in earlier sections, Path2D objects have methods to combine paths, and to add text to paths.

path = new Path2D()

Path2D/Path2D

Support in all current engines.

Firefox31+Safari8+Chrome36+
Opera23+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android31+Safari iOS8+Chrome Android36+WebView Android37+Samsung Internet3.0+Opera Android24+

Creates a new empty Path2D object.

path = new Path2D(path)

When path is a Path2D object, returns a copy.

When path is a string, creates the path described by the argument, interpreted as SVG path data. [SVG]

path . addPath(path [, transform ] )

Path2D/addPath

Support in all current engines.

Firefox34+Safari9+Chrome68+
Opera55+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android34+Safari iOS9+Chrome Android68+WebView Android68+Samsung Internet10.0+Opera Android48+

Adds to the path the path given by the argument.

The Path2D(path) constructor, when invoked, must run these steps:

  1. Let output be a new Path2D object.

  2. If path is not given, then return output.

  3. If path is a Path2D object, then add all subpaths of path to output and return output. (In other words, it returns a copy of the argument.)

  4. Let svgPath be the result of parsing and interpreting path according to SVG 2's rules for path data. [SVG]

    The resulting path could be empty. SVG defines error handling rules for parsing and applying path data.

  5. Let (x, y) be the last point in svgPath.

  6. Add all the subpaths, if any, from svgPath to output.

  7. Create a new subpath in output with (x, y) as the only point in the subpath.

  8. Return output.


The addPath(b, transform) method, when invoked on a Path2D object a, must run these steps:

  1. If the Path2D object b has no subpaths, then return.

  2. Let matrix be the result of creating a DOMMatrix from the 2D dictionary transform.

  3. If one or more of matrix's m11 element, m12 element, m21 element, m22 element, m41 element, or m42 element are infinite or NaN, then return.

  4. Create a copy of all the subpaths in b. Let this copy be known as c.

  5. Transform all the coordinates and lines in c by the transform matrix matrix.

  6. Let (x, y) be the last point in the last subpath of c.

  7. Add all the subpaths in c to a.

  8. Create a new subpath in a with (x, y) as the only point in the subpath.

4.12.5.1.7 Transformations

Objects that implement the CanvasTransform interface have a current transformation matrix, as well as methods (described in this section) to manipulate it. When an object implementing the CanvasTransform interface is created, its transformation matrix must be initialized to the identity matrix.

The current transformation matrix is applied to coordinates when creating the current default path, and when painting text, shapes, and Path2D objects, on objects implementing the CanvasTransform interface.

The transformations must be performed in reverse order.

For instance, if a scale transformation that doubles the width is applied to the canvas, followed by a rotation transformation that rotates drawing operations by a quarter turn, and a rectangle twice as wide as it is tall is then drawn on the canvas, the actual result will be a square.

context . scale(x, y)

CanvasRenderingContext2D/scale

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Changes the current transformation matrix to apply a scaling transformation with the given characteristics.

context . rotate(angle)

CanvasRenderingContext2D/rotate

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Changes the current transformation matrix to apply a rotation transformation with the given characteristics. The angle is in radians.

context . translate(x, y)

CanvasRenderingContext2D/translate

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Changes the current transformation matrix to apply a translation transformation with the given characteristics.

context . transform(a, b, c, d, e, f)

CanvasRenderingContext2D/transform

Support in all current engines.

Firefox3+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Changes the current transformation matrix to apply the matrix given by the arguments as described below.

matrix = context . getTransform()

CanvasRenderingContext2D/getTransform

Support in all current engines.

Firefox70+Safari11+Chrome68+
Opera55+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS11+Chrome Android68+WebView Android68+Samsung Internet10.0+Opera Android48+

Returns a copy of the current transformation matrix, as a newly created DOMMatrix object.

context . setTransform(a, b, c, d, e, f)

CanvasRenderingContext2D/setTransform

Support in all current engines.

Firefox3+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Changes the current transformation matrix to the matrix given by the arguments as described below.

context . setTransform(transform)

Changes the current transformation matrix to the matrix represented by the passed DOMMatrix2DInit dictionary.

context . resetTransform()

CanvasRenderingContext2D/resetTransform

Support in all current engines.

Firefox36+Safari10.1+Chrome31+
Opera18+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android36+Safari iOS10.3+Chrome Android31+WebView Android4.4+Samsung Internet2.0+Opera Android18+

Changes the current transformation matrix to the identity matrix.

The scale(x, y) method, when invoked, must run these steps:

  1. If either of the arguments are infinite or NaN, then return.

  2. Add the scaling transformation described by the arguments to the current transformation matrix. The x argument represents the scale factor in the horizontal direction and the y argument represents the scale factor in the vertical direction. The factors are multiples.

The rotate(angle) method, when invoked, must run these steps:

  1. If angle is infinite or NaN, then return.

  2. Add the rotation transformation described by the argument to the current transformation matrix. The angle argument represents a clockwise rotation angle expressed in radians.

The translate(x, y) method, when invoked, must run these steps:

  1. If either of the arguments are infinite or NaN, then return.

  2. Add the translation transformation described by the arguments to the current transformation matrix. The x argument represents the translation distance in the horizontal direction and the y argument represents the translation distance in the vertical direction. The arguments are in coordinate space units.

The transform(a, b, c, d, e, f) method, when invoked, must run these steps:

  1. If any of the arguments are infinite or NaN, then return.

  2. Replace the current transformation matrix with the result of multiplying the current transformation matrix with the matrix described by:

ace
bdf
001

The arguments a, b, c, d, e, and f are sometimes called m11, m12, m21, m22, dx, and dy or m11, m21, m12, m22, dx, and dy. Care ought to be taken in particular with the order of the second and third arguments (b and c) as their order varies from API to API and APIs sometimes use the notation m12/m21 and sometimes m21/m12 for those positions.

The getTransform() method, when invoked, must return a newly created DOMMatrix representing a copy of the current transformation matrix matrix of the context.

This returned object is not live, so updating it will not affect the current transformation matrix, and updating the current transformation matrix will not affect an already returned DOMMatrix.

The setTransform(a, b, c, d, e, f) method, when invoked, must run these steps:

  1. If any of the arguments are infinite or NaN, then return.

  2. Reset the current transformation matrix to the identity matrix.

  3. Invoke the transform(a, b, c, d, e, f) method with the same arguments.

The setTransform(transform) method, when invoked, must run these steps:

  1. Let matrix be the result of creating a DOMMatrix from the 2D dictionary transform.

  2. If one or more of matrix's m11 element, m12 element, m21 element, m22 element, m41 element, or m42 element are infinite or NaN, then return.

  3. Reset the current transformation matrix to matrix.

The resetTransform() method, when invoked, must reset the current transformation matrix to the identity matrix.

Given a matrix of the form created by the transform() and setTransform() methods, i.e.,

ace
bdf
001

the resulting transformed coordinates after transform matrix multiplication will be

xnew = a x + c y + e
ynew = b x + d y + f

4.12.5.1.8 Image sources for 2D rendering contexts

Some methods on the CanvasDrawImage and CanvasFillStrokeStyles interfaces take the union type CanvasImageSource as an argument.

This union type allows objects implementing any of the following interfaces to be used as image sources:

Although not formally specified as such, SVG image elements are expected to be implemented nearly identical to img elements. That is, SVG image elements share the fundamental concepts and features of img elements.

The ImageBitmap interface can be created from a number of other image-representing types, including ImageData.

To check the usability of the image argument, where image is a CanvasImageSource object, run these steps:

  1. Switch on image:

    HTMLOrSVGImageElement

    If image's current request's state is broken, then throw an "InvalidStateError" DOMException.

    If image is not fully decodable, then return bad.

    If image has an intrinsic width or intrinsic height (or both) equal to zero, then return bad.

    HTMLVideoElement

    If image's readyState attribute is either HAVE_NOTHING or HAVE_METADATA, then return bad.

    HTMLCanvasElement
    OffscreenCanvas

    If image has either a horizontal dimension or a vertical dimension equal to zero, then throw an "InvalidStateError" DOMException.

    ImageBitmap

    If image's [[Detached]] internal slot value is set to true, then throw an "InvalidStateError" DOMException.

  2. Return good.

When a CanvasImageSource object represents an HTMLOrSVGImageElement, the element's image must be used as the source image.

Specifically, when a CanvasImageSource object represents an animated image in an HTMLOrSVGImageElement, the user agent must use the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation, when rendering the image for CanvasRenderingContext2D APIs.

When a CanvasImageSource object represents an HTMLVideoElement, then the frame at the current playback position when the method with the argument is invoked must be used as the source image when rendering the image for CanvasRenderingContext2D APIs, and the source image's dimensions must be the intrinsic width and intrinsic height of the media resource (i.e. after any aspect-ratio correction has been applied).

When a CanvasImageSource object represents an HTMLCanvasElement, the element's bitmap must be used as the source image.

When a CanvasImageSource object represents an element that is being rendered and that element has been resized, the original image data of the source image must be used, not the image as it is rendered (e.g. width and height attributes on the source element have no effect on how the object is interpreted when rendering the image for CanvasRenderingContext2D APIs).

When a CanvasImageSource object represents an ImageBitmap, the object's bitmap image data must be used as the source image.

An object image is not origin-clean if, switching on image:

HTMLOrSVGImageElement
HTMLVideoElement

image's origin is not same origin with entry settings object's origin.

HTMLCanvasElement
ImageBitMap

image's bitmap's origin-clean flag is false.

4.12.5.1.9 Fill and stroke styles
context . fillStyle [ = value ]

CanvasRenderingContext2D/fillStyle

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the current style used for filling shapes.

Can be set, to change the fill style.

The style can be either a string containing a CSS color, or a CanvasGradient or CanvasPattern object. Invalid values are ignored.

context . strokeStyle [ = value ]

CanvasRenderingContext2D/strokeStyle

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the current style used for stroking shapes.

Can be set, to change the stroke style.

The style can be either a string containing a CSS color, or a CanvasGradient or CanvasPattern object. Invalid values are ignored.

Objects that implement the CanvasFillStrokeStyles interface have attributes and methods (defined in this section) that control how shapes are treated by the object.

The fillStyle attribute represents the color or style to use inside shapes, and the strokeStyle attribute represents the color or style to use for the lines around the shapes.

Both attributes can be either strings, CanvasGradients, or CanvasPatterns. On setting, strings must be parsed with this canvas element and the color assigned, and CanvasGradient and CanvasPattern objects must be assigned themselves. If parsing the value results in failure, then it must be ignored, and the attribute must retain its previous value. If the new value is a CanvasPattern object that is marked as not origin-clean, then the CanvasRenderingContext2D's origin-clean flag must be set to false.

When set to a CanvasPattern or CanvasGradient object, the assignment is live, meaning that changes made to the object after the assignment do affect subsequent stroking or filling of shapes.

On getting, if the value is a color, then the serialization of the color must be returned. Otherwise, if it is not a color but a CanvasGradient or CanvasPattern, then the respective object must be returned. (Such objects are opaque and therefore only useful for assigning to other attributes or for comparison to other gradients or patterns.)

The serialization of a color for a color value is a string, computed as follows: if it has alpha equal to 1.0, then the string is a lowercase six-digit hex value, prefixed with a "#" character (U+0023 NUMBER SIGN), with the first two digits representing the red component, the next two digits representing the green component, and the last two digits representing the blue component, the digits being ASCII lower hex digits. Otherwise, the color value has alpha less than 1.0, and the string is the color value in the CSS rgba() functional-notation format: the literal string "rgba" (U+0072 U+0067 U+0062 U+0061) followed by a U+0028 LEFT PARENTHESIS, a base-ten integer in the range 0-255 representing the red component (using ASCII digits in the shortest form possible), a literal U+002C COMMA and U+0020 SPACE, an integer for the green component, a comma and a space, an integer for the blue component, another comma and space, a U+0030 DIGIT ZERO, if the alpha value is greater than zero then a U+002E FULL STOP (representing the decimal point), if the alpha value is greater than zero then one or more ASCII digits representing the fractional part of the alpha, and finally a U+0029 RIGHT PARENTHESIS. User agents must express the fractional part of the alpha value, if any, with the level of precision necessary for the alpha value, when reparsed, to be interpreted as the same alpha value.

When the context is created, the fillStyle and strokeStyle attributes must initially have the string value #000000.

When the value is a color, it must not be affected by the transformation matrix when used to draw on bitmaps.


There are two types of gradients, linear gradients and radial gradients, both represented by objects implementing the opaque CanvasGradient interface.

Once a gradient has been created (see below), stops are placed along it to define how the colors are distributed along the gradient. The color of the gradient at each stop is the color specified for that stop. Between each such stop, the colors and the alpha component must be linearly interpolated over the RGBA space without premultiplying the alpha value to find the color to use at that offset. Before the first stop, the color must be the color of the first stop. After the last stop, the color must be the color of the last stop. When there are no stops, the gradient is transparent black.

gradient . addColorStop(offset, color)

CanvasGradient/addColorStop

Support in all current engines.

Firefox1.5+Safari5.1+Chrome6+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS6+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android10.1+

Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end.

Throws an "IndexSizeError" DOMException if the offset is out of range. Throws a "SyntaxError" DOMException if the color cannot be parsed.

gradient = context . createLinearGradient(x0, y0, x1, y1)

CanvasRenderingContext2D/createLinearGradient

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns a CanvasGradient object that represents a linear gradient that paints along the line given by the coordinates represented by the arguments.

gradient = context . createRadialGradient(x0, y0, r0, x1, y1, r1)

CanvasRenderingContext2D/createRadialGradient

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns a CanvasGradient object that represents a radial gradient that paints along the cone given by the circles represented by the arguments.

If either of the radii are negative, throws an "IndexSizeError" DOMException exception.

The addColorStop(offset, color) method on the CanvasGradient, when invoked, must run these steps:

  1. If the offset is less than 0 or greater than 1, then throw an "IndexSizeError" DOMException.

  2. Let parsed color be the result of parsing color.

    No element is passed to the parser because CanvasGradient objects are canvas-neutral — a CanvasGradient object created by one canvas can be used by another, and there is therefore no way to know which is the "element in question" at the time that the color is specified.

  3. If parsed color is failure, throw a "SyntaxError" DOMException.

  4. Place a new stop on the gradient, at offset offset relative to the whole gradient, and with the color parsed color.

    If multiple stops are added at the same offset on a gradient, then they must be placed in the order added, with the first one closest to the start of the gradient, and each subsequent one infinitesimally further along towards the end point (in effect causing all but the first and last stop added at each point to be ignored).

The createLinearGradient(x0, y0, x1, y1) method takes four arguments that represent the start point (x0, y0) and end point (x1, y1) of the gradient. The method, when invoked, must return a linear CanvasGradient initialized with the specified line.

Linear gradients must be rendered such that all points on a line perpendicular to the line that crosses the start and end points have the color at the point where those two lines cross (with the colors coming from the interpolation and extrapolation described above). The points in the linear gradient must be transformed as described by the current transformation matrix when rendering.

If x0 = x1 and y0 = y1, then the linear gradient must paint nothing.

The createRadialGradient(x0, y0, r0, x1, y1, r1) method takes six arguments, the first three representing the start circle with origin (x0, y0) and radius r0, and the last three representing the end circle with origin (x1, y1) and radius r1. The values are in coordinate space units. If either of r0 or r1 are negative, then an "IndexSizeError" DOMException must be thrown. Otherwise, the method, when invoked, must return a radial CanvasGradient initialized with the two specified circles.

Radial gradients must be rendered by following these steps:

  1. If x0 = x1 and y0 = y1 and r0 = r1, then the radial gradient must paint nothing. Return.

  2. Let x(ω) = (x1-x0)ω + x0

    Let y(ω) = (y1-y0)ω + y0

    Let r(ω) = (r1-r0)ω + r0

    Let the color at ω be the color at that position on the gradient (with the colors coming from the interpolation and extrapolation described above).

  3. For all values of ω where r(ω) > 0, starting with the value of ω nearest to positive infinity and ending with the value of ω nearest to negative infinity, draw the circumference of the circle with radius r(ω) at position (x(ω), y(ω)), with the color at ω, but only painting on the parts of the bitmap that have not yet been painted on by earlier circles in this step for this rendering of the gradient.

This effectively creates a cone, touched by the two circles defined in the creation of the gradient, with the part of the cone before the start circle (0.0) using the color of the first offset, the part of the cone after the end circle (1.0) using the color of the last offset, and areas outside the cone untouched by the gradient (transparent black).

The resulting radial gradient must then be transformed as described by the current transformation matrix when rendering.

Gradients must be painted only where the relevant stroking or filling effects requires that they be drawn.


Patterns are represented by objects implementing the opaque CanvasPattern interface.

pattern = context . createPattern(image, repetition)

CanvasRenderingContext2D/createPattern

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns a CanvasPattern object that uses the given image and repeats in the direction(s) given by the repetition argument.

The allowed values for repetition are repeat (both directions), repeat-x (horizontal only), repeat-y (vertical only), and no-repeat (neither). If the repetition argument is empty, the value repeat is used.

If the image isn't yet fully decoded, then nothing is drawn. If the image is a canvas with no data, throws an "InvalidStateError" DOMException.

pattern . setTransform(transform)

CanvasPattern/setTransform

Support in all current engines.

Firefox33+Safari11.1+Chrome68+
Opera55+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android33+Safari iOS11.3+Chrome Android68+WebView Android68+Samsung Internet10.0+Opera Android48+

Sets the transformation matrix that will be used when rendering the pattern during a fill or stroke painting operation.

The createPattern(image, repetition) method, when invoked, must run these steps:

  1. Let usability be the result of checking the usability of image.

  2. If result is bad, then return null.

  3. Assert: result is good.

  4. If repetition is the empty string, then set it to "repeat".

  5. If repetition is not identical to one of "repeat", "repeat-x", "repeat-y", or "no-repeat", then throw a "SyntaxError" DOMException.

  6. Let pattern be a new CanvasPattern object with the image image and the repetition behavior given by repetition.

  7. If image is not origin-clean, then mark pattern as not origin-clean.

  8. Return pattern.

Modifying the image used when creating a CanvasPattern object after calling the createPattern() method must not affect the pattern(s) rendered by the CanvasPattern object.

Patterns have a transformation matrix, which controls how the pattern is used when it is painted. Initially, a pattern's transformation matrix must be the identity matrix.

The setTransform(transform) method, when invoked, must run these steps:

  1. Let matrix be the result of creating a DOMMatrix from the 2D dictionary transform.

  2. If one or more of matrix's m11 element, m12 element, m21 element, m22 element, m41 element, or m42 element are infinite or NaN, then return.

  3. Reset the pattern's transformation matrix to matrix.

When a pattern is to be rendered within an area, the user agent must run the following steps to determine what is rendered:

  1. Create an infinite transparent black bitmap.

  2. Place a copy of the image on the bitmap, anchored such that its top left corner is at the origin of the coordinate space, with one coordinate space unit per CSS pixel of the image, then place repeated copies of this image horizontally to the left and right, if the repetition behavior is "repeat-x", or vertically up and down, if the repetition behavior is "repeat-y", or in all four directions all over the bitmap, if the repetition behavior is "repeat".

    If the original image data is a bitmap image, then the value painted at a point in the area of the repetitions is computed by filtering the original image data. When scaling up, if the imageSmoothingEnabled attribute is set to false, then the image must be rendered using nearest-neighbor interpolation. Otherwise, the user agent may use any filtering algorithm (for example bilinear interpolation or nearest-neighbor). User agents which support multiple filtering algorithms may use the value of the imageSmoothingQuality attribute to guide the choice of filtering algorithm. When such a filtering algorithm requires a pixel value from outside the original image data, it must instead use the value from wrapping the pixel's coordinates to the original image's dimensions. (That is, the filter uses 'repeat' behavior, regardless of the value of the pattern's repetition behavior.)

  3. Transform the resulting bitmap according to the pattern's transformation matrix.

  4. Transform the resulting bitmap again, this time according to the current transformation matrix.

  5. Replace any part of the image outside the area in which the pattern is to be rendered with transparent black.

  6. The resulting bitmap is what is to be rendered, with the same origin and same scale.


If a radial gradient or repeated pattern is used when the transformation matrix is singular, then the resulting style must be transparent black (otherwise the gradient or pattern would be collapsed to a point or line, leaving the other pixels undefined). Linear gradients and solid colors always define all points even with singular transformation matrices.

4.12.5.1.10 Drawing rectangles to the bitmap

Objects that implement the CanvasRect interface provide the following methods for immediately drawing rectangles to the bitmap. The methods each take four arguments; the first two give the x and y coordinates of the top left of the rectangle, and the second two give the width w and height h of the rectangle, respectively.

The current transformation matrix must be applied to the following four coordinates, which form the path that must then be closed to get the specified rectangle: (x, y), (x+w, y), (x+w, y+h), (x, y+h).

Shapes are painted without affecting the current default path, and are subject to the clipping region, and, with the exception of clearRect(), also shadow effects, global alpha, and global composition operators.

context . clearRect(x, y, w, h)

CanvasRenderingContext2D/clearRect

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Clears all pixels on the bitmap in the given rectangle to transparent black.

context . fillRect(x, y, w, h)

CanvasRenderingContext2D/fillRect

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Paints the given rectangle onto the bitmap, using the current fill style.

context . strokeRect(x, y, w, h)

CanvasRenderingContext2D/strokeRect

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Paints the box that outlines the given rectangle onto the bitmap, using the current stroke style.

The clearRect(x, y, w, h) method, when invoked, must run these steps:

  1. If any of the arguments are infinite or NaN, then return.

  2. Let pixels be the set of pixels in the specified rectangle that also intersect the current clipping region.

  3. Clear the pixels in pixels to a transparent black, erasing any previous image.

If either height or width are zero, this method has no effect, since the set of pixels would be empty.

The fillRect(x, y, w, h) method, when invoked, must must run these steps:

  1. If any of the arguments are infinite or NaN, then return.

  2. If either w or h are zero, then return.

  3. Paint the specified rectangular area using the fillStyle.

The strokeRect(x, y, w, h) method, when invoked, must run these steps:

  1. If any of the arguments are infinite or NaN, then return.

  2. Take the result of tracing the path described below, using the CanvasPathDrawingStyles interface's line styles, and fill it with the strokeStyle.

If both w and h are zero, the path has a single subpath with just one point (x, y), and no lines, and this method thus has no effect (the trace a path algorithm returns an empty path in that case).

If just one of either w or h is zero, then the path has a single subpath consisting of two points, with coordinates (x, y) and (x+w, y+h), in that order, connected by a single straight line.

Otherwise, the path has a single subpath consisting of four points, with coordinates (x, y), (x+w, y), (x+w, y+h), and (x, y+h), connected to each other in that order by straight lines.

4.12.5.1.11 Drawing text to the bitmap

CanvasRenderingContext2D

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
context . fillText(text, x, y [, maxWidth ] )

CanvasRenderingContext2D/fillText

Support in all current engines.

Firefox3.5+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
context . strokeText(text, x, y [, maxWidth ] )

CanvasRenderingContext2D/strokeText

Support in all current engines.

Firefox3.5+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Fills or strokes (respectively) the given text at the given position. If a maximum width is provided, the text will be scaled to fit that width if necessary.

metrics = context . measureText(text)

CanvasRenderingContext2D/measureText

Support in all current engines.

Firefox2+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns a TextMetrics object with the metrics of the given text in the current font.

metrics . width

TextMetrics/width

Support in all current engines.

Firefox1.5+Safari4+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android31+Safari iOS3.2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
metrics . actualBoundingBoxLeft

TextMetrics/actualBoundingBoxLeft

Support in all current engines.

Firefox74+Safari11.1+Chrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS11.3+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+
metrics . actualBoundingBoxRight

TextMetrics/actualBoundingBoxRight

Support in all current engines.

Firefox74+Safari11.1+Chrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS11.3+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+
metrics . fontBoundingBoxAscent

TextMetrics/fontBoundingBoxAscent

Support in all current engines.

Firefox🔰 74+Safari11.1+Chrome87+
Opera73+Edge87+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS11.3+Chrome Android87+WebView Android87+Samsung Internet14.0+Opera Android62+
metrics . fontBoundingBoxDescent

TextMetrics/fontBoundingBoxDescent

Support in all current engines.

Firefox🔰 74+Safari11.1+Chrome87+
Opera73+Edge87+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS11.3+Chrome Android87+WebView Android87+Samsung Internet14.0+Opera Android62+
metrics . actualBoundingBoxAscent

TextMetrics/actualBoundingBoxAscent

Support in all current engines.

Firefox74+Safari11.1+Chrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS11.3+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+
metrics . actualBoundingBoxDescent

TextMetrics/actualBoundingBoxDescent

Support in all current engines.

Firefox74+Safari11.1+Chrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS11.3+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+
metrics . emHeightAscent

TextMetrics/emHeightAscent

Support in all current engines.

Firefox🔰 74+Safari11.1+Chrome🔰 35+
OperaNoEdge🔰 79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS11.3+Chrome Android🔰 35+WebView AndroidNoSamsung InternetNoOpera AndroidNo
metrics . emHeightDescent

TextMetrics/emHeightDescent

Support in all current engines.

Firefox🔰 74+Safari11.1+Chrome🔰 35+
OperaNoEdge🔰 79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS11.3+Chrome Android🔰 35+WebView AndroidNoSamsung InternetNoOpera AndroidNo
metrics . hangingBaseline

TextMetrics/hangingBaseline

Firefox🔰 74+Safari11.1+Chrome35–70
OperaNoEdgeNo
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS11.3+Chrome Android35–70WebView AndroidNoSamsung InternetNoOpera AndroidNo
metrics . alphabeticBaseline

TextMetrics/alphabeticBaseline

Firefox🔰 74+Safari11.1+Chrome35–70
OperaNoEdgeNo
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS11.3+Chrome Android35–70WebView AndroidNoSamsung InternetNoOpera AndroidNo
metrics . ideographicBaseline

TextMetrics/ideographicBaseline

Firefox🔰 74+Safari11.1+Chrome35–70
OperaNoEdgeNo
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS11.3+Chrome Android35–70WebView AndroidNoSamsung InternetNoOpera AndroidNo

Returns the measurement described below.

Objects that implement the CanvasText interface provide the following methods for rendering text.

The fillText() and strokeText() methods take three or four arguments, text, x, y, and optionally maxWidth, and render the given text at the given (x, y) coordinates ensuring that the text isn't wider than maxWidth if specified, using the current font, textAlign, and textBaseline values. Specifically, when the methods are invoked, the user agent must run these steps:

  1. If any of the arguments are infinite or NaN, then return.

  2. Run the text preparation algorithm, passing it text, the object implementing the CanvasText interface, and, if the maxWidth argument was provided, that argument. Let glyphs be the result.

  3. Move all the shapes in glyphs to the right by x CSS pixels and down by y CSS pixels.

  4. Paint the shapes given in glyphs, as transformed by the current transformation matrix, with each CSS pixel in the coordinate space of glyphs mapped to one coordinate space unit.

    For fillText(), fillStyle must be applied to the shapes and strokeStyle must be ignored. For strokeText(), the reverse holds: strokeStyle must be applied to the result of tracing the shapes using the object implementing the CanvasText interface for the line styles, and fillStyle must be ignored.

    These shapes are painted without affecting the current path, and are subject to shadow effects, global alpha, the clipping region, and global composition operators.

(This is a tracking vector.) The measureText() method takes one argument, text. When the method is invoked, the user agent must run the text preparation algorithm, passing it text and the object implementing the CanvasText interface, and then using the returned inline box must return a new TextMetrics object with members behaving as described in the following list: [CSS]

width attribute

The width of that inline box, in CSS pixels. (The text's advance width.)

actualBoundingBoxLeft attribute

The distance parallel to the baseline from the alignment point given by the textAlign attribute to the left side of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going left from the given alignment point.

The sum of this value and the next (actualBoundingBoxRight) can be wider than the width of the inline box (width), in particular with slanted fonts where characters overhang their advance width.

actualBoundingBoxRight attribute

The distance parallel to the baseline from the alignment point given by the textAlign attribute to the right side of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going right from the given alignment point.

fontBoundingBoxAscent attribute

The distance from the horizontal line indicated by the textBaseline attribute to the ascent metric of the first available font, in CSS pixels; positive numbers indicating a distance going up from the given baseline.

This value and the next are useful when rendering a background that have to have a consistent height even if the exact text being rendered changes. The actualBoundingBoxAscent attribute (and its corresponding attribute for the descent) are useful when drawing a bounding box around specific text.

fontBoundingBoxDescent attribute

The distance from the horizontal line indicated by the textBaseline attribute to the descent metric of the first available font, in CSS pixels; positive numbers indicating a distance going down from the given baseline.

actualBoundingBoxAscent attribute

The distance from the horizontal line indicated by the textBaseline attribute to the top of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going up from the given baseline.

This number can vary greatly based on the input text, even if the first font specified covers all the characters in the input. For example, the actualBoundingBoxAscent of a lowercase "o" from an alphabetic baseline would be less than that of an uppercase "F". The value can easily be negative; for example, the distance from the top of the em box (textBaseline value "top") to the top of the bounding rectangle when the given text is just a single comma "," would likely (unless the font is quite unusual) be negative.

actualBoundingBoxDescent attribute

The distance from the horizontal line indicated by the textBaseline attribute to the bottom of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going down from the given baseline.

emHeightAscent attribute

The distance from the horizontal line indicated by the textBaseline attribute to the highest top of the em squares in the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the top of that em square (so this value will usually be positive). Zero if the given baseline is the top of that em square; half the font size if the given baseline is the middle of that em square.

emHeightDescent attribute

The distance from the horizontal line indicated by the textBaseline attribute to the lowest bottom of the em squares in the inline box, in CSS pixels; positive numbers indicating that the given baseline is above the bottom of that em square. (Zero if the given baseline is the bottom of that em square.)

hangingBaseline attribute

The distance from the horizontal line indicated by the textBaseline attribute to the hanging baseline of the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the hanging baseline. (Zero if the given baseline is the hanging baseline.)

alphabeticBaseline attribute

The distance from the horizontal line indicated by the textBaseline attribute to the alphabetic baseline of the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the alphabetic baseline. (Zero if the given baseline is the alphabetic baseline.)

ideographicBaseline attribute

The distance from the horizontal line indicated by the textBaseline attribute to the ideographic-under baseline of the inline box, in CSS pixels; positive numbers indicating that the given baseline is below the ideographic-under baseline. (Zero if the given baseline is the ideographic-under baseline.)

Glyphs rendered using fillText() and strokeText() can spill out of the box given by the font size (the em square size) and the width returned by measureText() (the text width). Authors are encouraged to use the bounding box values described above if this is an issue.

A future version of the 2D context API might provide a way to render fragments of documents, rendered using CSS, straight to the canvas. This would be provided in preference to a dedicated way of doing multiline layout.

4.12.5.1.12 Drawing paths to the canvas

Objects that implement the CanvasDrawPath interface have a current default path. There is only one current default path, it is not part of the drawing state. The current default path is a path, as described above.

context . beginPath()

CanvasRenderingContext2D/beginPath

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Resets the current default path.

context . fill( [ fillRule ] )

CanvasRenderingContext2D/fill

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
context . fill(path [, fillRule ] )

Fills the subpaths of the current default path or the given path with the current fill style, obeying the given fill rule.

context . stroke()

CanvasRenderingContext2D/stroke

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
context . stroke(path)

Strokes the subpaths of the current default path or the given path with the current stroke style.

context . clip( [ fillRule ] )

CanvasRenderingContext2D/clip

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
context . clip(path [, fillRule ] )

Further constrains the clipping region to the current default path or the given path, using the given fill rule to determine what points are in the path.

context . isPointInPath(x, y [, fillRule ] )

CanvasRenderingContext2D/isPointInPath

Support in all current engines.

Firefox2+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
context . isPointInPath(path, x, y [, fillRule ] )

Returns true if the given point is in the current default path or the given path, using the given fill rule to determine what points are in the path.

context . isPointInStroke(x, y)

CanvasRenderingContext2D/isPointInStroke

Support in all current engines.

Firefox19+Safari7+Chrome26+
Opera15+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android19+Safari iOS7+Chrome Android26+WebView Android37+Samsung Internet1.5+Opera Android14+
context . isPointInStroke(path, x, y)

Returns true if the given point would be in the region covered by the stroke of the current default path or the given path, given the current stroke style.

The beginPath() method, when invoked, must empty the list of subpaths in the context's current default path so that it once again has zero subpaths.

Where the following method definitions use the term intended path, it means the Path2D argument, if one was provided, or the current default path otherwise.

When the intended path is a Path2D object, the coordinates and lines of its subpaths must be transformed according to the current transformation matrix on the object implementing the CanvasTransform interface when used by these methods (without affecting the Path2D object itself). When the intended path is the current default path, it is not affected by the transform. (This is because transformations already affect the current default path when it is constructed, so applying it when it is painted as well would result in a double transformation.)

The fill() method, when invoked, must fill all the subpaths of the intended path, using fillStyle, and using the fill rule indicated by the fillRule argument. Open subpaths must be implicitly closed when being filled (without affecting the actual subpaths).

The stroke() method, when invoked, must trace the intended path, using this CanvasPathDrawingStyles object for the line styles, and then fill the resulting path using the strokeStyle attribute, using the nonzero winding rule.

As a result of how the algorithm to trace a path is defined, overlapping parts of the paths in one stroke operation are treated as if their union was what was painted.

The stroke style is affected by the transformation during painting, even if the intended path is the current default path.

Paths, when filled or stroked, must be painted without affecting the current default path or any Path2D objects, and must be subject to shadow effects, global alpha, the clipping region, and global composition operators. (The effect of transformations is described above and varies based on which path is being used.)


The clip() method, when invoked, must create a new clipping region by calculating the intersection of the current clipping region and the area described by the intended path, using the fill rule indicated by the fillRule argument. Open subpaths must be implicitly closed when computing the clipping region, without affecting the actual subpaths. The new clipping region replaces the current clipping region.

When the context is initialized, the clipping region must be set to the largest infinite surface (i.e. by default, no clipping occurs).


The isPointInPath() method, when invoked, must return true if the point given by the x and y coordinates passed to the method, when treated as coordinates in the canvas coordinate space unaffected by the current transformation, is inside the intended path as determined by the fill rule indicated by the fillRule argument; and must return false otherwise. Open subpaths must be implicitly closed when computing the area inside the path, without affecting the actual subpaths. Points on the path itself must be considered to be inside the path. If either of the arguments are infinite or NaN, then the method must return false.


The isPointInStroke() method, when invoked, must return true if the point given by the x and y coordinates passed to the method, when treated as coordinates in the canvas coordinate space unaffected by the current transformation, is inside the path that results from tracing the intended path, using the nonzero winding rule, and using the CanvasPathDrawingStyles interface for the line styles; and must return false otherwise. Points on the resulting path must be considered to be inside the path. If either of the arguments are infinite or NaN, then the method must return false.


This canvas element has a couple of checkboxes. The path-related commands are highlighted:

<canvas height=400 width=750>
 <label><input type=checkbox id=showA> Show As</label>
 <label><input type=checkbox id=showB> Show Bs</label>
 <!-- ... -->
</canvas>
<script>
 function drawCheckbox(context, element, x, y, paint) {
   context.save();
   context.font = '10px sans-serif';
   context.textAlign = 'left';
   context.textBaseline = 'middle';
   var metrics = context.measureText(element.labels[0].textContent);
   if (paint) {
     context.beginPath();
     context.strokeStyle = 'black';
     context.rect(x-5, y-5, 10, 10);
     context.stroke();
     if (element.checked) {
       context.fillStyle = 'black';
       context.fill();
     }
     context.fillText(element.labels[0].textContent, x+5, y);
   }
   context.beginPath();
   context.rect(x-7, y-7, 12 + metrics.width+2, 14);

   context.drawFocusIfNeeded(element);
   context.restore();
 }
 function drawBase() { /* ... */ }
 function drawAs() { /* ... */ }
 function drawBs() { /* ... */ }
 function redraw() {
   var canvas = document.getElementsByTagName('canvas')[0];
   var context = canvas.getContext('2d');
   context.clearRect(0, 0, canvas.width, canvas.height);
   drawCheckbox(context, document.getElementById('showA'), 20, 40, true);
   drawCheckbox(context, document.getElementById('showB'), 20, 60, true);
   drawBase();
   if (document.getElementById('showA').checked)
     drawAs();
   if (document.getElementById('showB').checked)
     drawBs();
 }
 function processClick(event) {
   var canvas = document.getElementsByTagName('canvas')[0];
   var context = canvas.getContext('2d');
   var x = event.clientX;
   var y = event.clientY;
   var node = event.target;
   while (node) {
     x -= node.offsetLeft - node.scrollLeft;
     y -= node.offsetTop - node.scrollTop;
     node = node.offsetParent;
   }
   drawCheckbox(context, document.getElementById('showA'), 20, 40, false);
   if (context.isPointInPath(x, y))
     document.getElementById('showA').checked = !(document.getElementById('showA').checked);
   drawCheckbox(context, document.getElementById('showB'), 20, 60, false);
   if (context.isPointInPath(x, y))
     document.getElementById('showB').checked = !(document.getElementById('showB').checked);
   redraw();
 }
 document.getElementsByTagName('canvas')[0].addEventListener('focus', redraw, true);
 document.getElementsByTagName('canvas')[0].addEventListener('blur', redraw, true);
 document.getElementsByTagName('canvas')[0].addEventListener('change', redraw, true);
 document.getElementsByTagName('canvas')[0].addEventListener('click', processClick, false);
 redraw();
</script>
4.12.5.1.13 Drawing focus rings and scrolling paths into view
context . drawFocusIfNeeded(element)

CanvasRenderingContext2D/drawFocusIfNeeded

Support in all current engines.

Firefox32+Safari8+Chrome37+
Opera24+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android32+Safari iOS8+Chrome Android37+WebView Android37+Samsung Internet3.0+Opera Android24+
context . drawFocusIfNeeded(path, element)

If the given element is focused, draws a focus ring around the current default path or the given path, following the platform conventions for focus rings.

context . scrollPathIntoView()

CanvasRenderingContext2D/scrollPathIntoView

Support in one engine only.

FirefoxNoSafariNoChrome🔰 36+
Opera🔰 23+Edge🔰 79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome Android🔰 36+WebView AndroidNoSamsung InternetNoOpera AndroidNo
context . scrollPathIntoView(path)

Scrolls the current default path or the given path into view. This is especially useful on devices with small screens, where the whole canvas might not be visible at once.

Objects that implement the CanvasUserInterface interface provide the following methods to control drawing focus rings and scrolling paths into view.

The drawFocusIfNeeded(element) method, when invoked, must run these steps:

  1. If element is not focused or is not a descendant of the element with whose context the method is associated, then return.

  2. Draw a focus ring of the appropriate style along the intended path, following platform conventions.

    Some platforms only draw focus rings around elements that have been focused from the keyboard, and not those focused from the mouse. Other platforms simply don't draw focus rings around some elements at all unless relevant accessibility features are enabled. This API is intended to follow these conventions. User agents that implement distinctions based on the manner in which the element was focused are encouraged to classify focus driven by the focus() method based on the kind of user interaction event from which the call was triggered (if any).

    The focus ring should not be subject to the shadow effects, the global alpha, the global composition operators, or any of the members in the CanvasFillStrokeStyles, CanvasPathDrawingStyles, CanvasTextDrawingStyles interfaces, but should be subject to the clipping region. (The effect of transformations is described above and varies based on which path is being used.)

  3. Inform the user that the focus is at the location given by the intended path. User agents may wait until the next time the event loop reaches its update the rendering step to optionally inform the user.

User agents should not implicitly close open subpaths in the intended path when drawing the focus ring.

This might be a moot point, however. For example, if the focus ring is drawn as an axis-aligned bounding rectangle around the points in the intended path, then whether the subpaths are closed or not has no effect. This specification intentionally does not specify precisely how focus rings are to be drawn: user agents are expected to honor their platform's native conventions.


The scrollPathIntoView() method, when invoked, must run these steps:

  1. Let specifiedRectangle be the rectangle of the bounding box of the intended path.

  2. Let notionalChild be a hypothetical element that is a rendered child of the canvas element whose dimensions are those of specifiedRectangle.

  3. Scroll notionalChild into view with behavior set to "auto", block set to "start", and inline set to "nearest".

  4. Optionally, inform the user that the caret or selection (or both) cover specifiedRectangle of the canvas. The user agent may wait until the next time the event loop reaches its update the rendering step to optionally inform the user.

"Inform the user", as used in this section, does not imply any persistent state change. It could mean, for instance, calling a system accessibility API to notify assistive technologies such as magnification tools so that the user's magnifier moves to the given area of the canvas. However, it does not associate the path with the element, or provide a region for tactile feedback, etc.

4.12.5.1.14 Drawing images

Objects that implement the CanvasDrawImage interface have the drawImage method to draw images.

This method can be invoked with three different sets of arguments:

context . drawImage(image, dx, dy)

CanvasRenderingContext2D/drawImage

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
context . drawImage(image, dx, dy, dw, dh)
context . drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)

Draws the given image onto the canvas. The arguments are interpreted as follows:

The sx and sy parameters give the x and y coordinates of the source rectangle; the sw and sh arguments give the width and height of the source rectangle; the dx and dy give the x and y coordinates of the destination rectangle; and the dw and dh arguments give the width and height of the destination rectangle.

If the image isn't yet fully decoded, then nothing is drawn. If the image is a canvas with no data, throws an "InvalidStateError" DOMException.

When the drawImage() method is invoked, the user agent must run these steps:

  1. If any of the arguments are infinite or NaN, then return.

  2. Let usability be the result of checking the usability of image.

  3. If usability is bad, then return (without drawing anything).

  4. Establish the source and destination rectangles as follows:

    If not specified, the dw and dh arguments must default to the values of sw and sh, interpreted such that one CSS pixel in the image is treated as one unit in the output bitmap's coordinate space. If the sx, sy, sw, and sh arguments are omitted, then they must default to 0, 0, the image's intrinsic width in image pixels, and the image's intrinsic height in image pixels, respectively. If the image has no intrinsic dimensions, then the concrete object size must be used instead, as determined using the CSS "Concrete Object Size Resolution" algorithm, with the specified size having neither a definite width nor height, nor any additional constraints, the object's intrinsic properties being those of the image argument, and the default object size being the size of the output bitmap. [CSSIMAGES]

    The source rectangle is the rectangle whose corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh).

    The destination rectangle is the rectangle whose corners are the four points (dx, dy), (dx+dw, dy), (dx+dw, dy+dh), (dx, dy+dh).

    When the source rectangle is outside the source image, the source rectangle must be clipped to the source image and the destination rectangle must be clipped in the same proportion.

    When the destination rectangle is outside the destination image (the output bitmap), the pixels that land outside the output bitmap are discarded, as if the destination was an infinite canvas whose rendering was clipped to the dimensions of the output bitmap.

  5. If one of the sw or sh arguments is zero, then return. Nothing is painted.

  6. Paint the region of the image argument specified by the source rectangle on the region of the rendering context's output bitmap specified by the destination rectangle, after applying the current transformation matrix to the destination rectangle.

    The image data must be processed in the original direction, even if the dimensions given are negative.

    When scaling up, if the imageSmoothingEnabled attribute is set to true, the user agent should attempt to apply a smoothing algorithm to the image data when it is scaled. User agents which support multiple filtering algorithms may use the value of the imageSmoothingQuality attribute to guide the choice of filtering algorithm when the imageSmoothingEnabled attribute is set to true. Otherwise, the image must be rendered using nearest-neighbor interpolation.

    This specification does not define the precise algorithm to use when scaling an image down, or when scaling an image up when the imageSmoothingEnabled attribute is set to true.

    When a canvas element is drawn onto itself, the drawing model requires the source to be copied before the image is drawn, so it is possible to copy parts of a canvas element onto overlapping parts of itself.

    If the original image data is a bitmap image, then the value painted at a point in the destination rectangle is computed by filtering the original image data. The user agent may use any filtering algorithm (for example bilinear interpolation or nearest-neighbor). When the filtering algorithm requires a pixel value from outside the original image data, it must instead use the value from the nearest edge pixel. (That is, the filter uses 'clamp-to-edge' behavior.) When the filtering algorithm requires a pixel value from outside the source rectangle but inside the original image data, then the value from the original image data must be used.

    Thus, scaling an image in parts or in whole will have the same effect. This does mean that when sprites coming from a single sprite sheet are to be scaled, adjacent images in the sprite sheet can interfere. This can be avoided by ensuring each sprite in the sheet is surrounded by a border of transparent black, or by copying sprites to be scaled into temporary canvas elements and drawing the scaled sprites from there.

    Images are painted without affecting the current path, and are subject to shadow effects, global alpha, the clipping region, and global composition operators.

  7. If image is not origin-clean, then set the CanvasRenderingContext2D's origin-clean flag to false.

4.12.5.1.15 Pixel manipulation
imagedata = new ImageData(sw, sh)

ImageData/ImageData

Support in all current engines.

Firefox29+Safari7+Chrome36+
Opera23+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android29+Safari iOS7+Chrome Android36+WebView Android37+Samsung Internet3.0+Opera Android24+
imagedata = context . createImageData(sw, sh)

CanvasRenderingContext2D/createImageData

Support in all current engines.

Firefox3.5+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns an ImageData object with the given dimensions. All the pixels in the returned object are transparent black.

Throws an "IndexSizeError" DOMException if either of the width or height arguments are zero.

imagedata = context . createImageData(imagedata)

Returns an ImageData object with the same dimensions as the argument. All the pixels in the returned object are transparent black.

imagedata = new ImageData(data, sw [, sh ] )

Returns an ImageData object using the data provided in the Uint8ClampedArray argument, interpreted using the given dimensions.

As each pixel in the data is represented by four numbers, the length of the data needs to be a multiple of four times the given width. If the height is provided as well, then the length needs to be exactly the width times the height times 4.

Throws an "IndexSizeError" DOMException if the given data and dimensions can't be interpreted consistently, or if either dimension is zero.

imagedata = context . getImageData(sx, sy, sw, sh)

CanvasRenderingContext2D/getImageData

Support in all current engines.

Firefox2+Safari4+Chrome1+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

Returns an ImageData object containing the image data for the given rectangle of the bitmap.

Throws an "IndexSizeError" DOMException if the either of the width or height arguments are zero.

imagedata . width

ImageData/width

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+
imagedata . height

ImageData/height

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

Returns the actual dimensions of the data in the ImageData object, in pixels.

imagedata . data

ImageData/data

Support in all current engines.

Firefox3.5+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

Returns the one-dimensional array containing the data in RGBA order, as integers in the range 0 to 255.

context . putImageData(imagedata, dx, dy [, dirtyX, dirtyY, dirtyWidth, dirtyHeight ] )

CanvasRenderingContext2D/putImageData

Support in all current engines.

Firefox2+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Paints the data from the given ImageData object onto the bitmap. If a dirty rectangle is provided, only the pixels from that rectangle are painted.

The globalAlpha and globalCompositeOperation attributes, as well as the shadow attributes, are ignored for the purposes of this method call; pixels in the canvas are replaced wholesale, with no composition, alpha blending, no shadows, etc.

Throws an "InvalidStateError" DOMException if the imagedata object's data attribute value's [[ViewedArrayBuffer]] internal slot is detached.

Objects that implement the CanvasImageData interface provide the following methods for reading and writing pixel data to the bitmap.

The ImageData() constructors and the createImageData() methods are used to instantiate new ImageData objects.

When the ImageData() constructor is invoked with two numeric arguments sw and sh, it must run these steps:

  1. If one or both of sw and sh are zero, then throw an "IndexSizeError" DOMException.

  2. Create an ImageData object with parameter pixelsPerRow set to sw, and rows set to sh.

  3. Initialize the image data of the newly created ImageData object to transparent black.

  4. Return the newly created ImageData object.

When the ImageData() constructor is invoked with its first argument being an Uint8ClampedArray source and its second and optional third arguments being numeric arguments sw and sh, it must run these steps:

  1. Let length be the number of bytes in source.

  2. If length is not a nonzero integral multiple of four, then throw an "InvalidStateError" DOMException.

  3. Let length be length divided by four.

  4. If length is not an integral multiple of sw, then throw an "IndexSizeError" DOMException.

    At this step, the length is guaranteed to be greater than zero (otherwise the second step above would have aborted the steps), so if sw is zero, this step will throw the exception and return.

  5. Let height be length divided by sw.

  6. If the sh argument was not omitted, and its value is not equal to height, then throw an "IndexSizeError" DOMException.

  7. Create an ImageData object, with parameter pixelsPerRow set to sw, rows set to sh, and using source. Return the newly created ImageData object.

    The resulting object's data is not a copy of source, it's the actual Uint8ClampedArray object passed as the first argument to the constructor.

When the createImageData() method is invoked with two numeric arguments sw and sh, it must create an ImageData object, with parameter pixelsPerRow set to the absolute magnitude of sw, and parameter rows set to the absolute magnitude of sh. Initialize the image data of the new ImageData object to transparent black. If both sw and sh are nonzero, then return the new ImageData object. If one or both of sw and sh are zero, then throw an "IndexSizeError" DOMException instead.

When the createImageData() method is invoked with a single imagedata argument, it must create an ImageData object, with parameter pixelsPerRow set to the value of the width attribute of the ImageData object passed as the argument, and the rows parameter set to the value of the height attribute. Initialize the image data of the new ImageData object to transparent black. Return the newly created ImageData object.

The getImageData(sx, sy, sw, sh) method, when invoked, must, if either the sw or sh arguments are zero, throw an "IndexSizeError" DOMException; otherwise, if the CanvasRenderingContext2D's origin-clean flag is set to false, it must throw a "SecurityError" DOMException; otherwise, it must create an ImageData object, with parameter pixelsPerRow set to sw, and parameter rows set to sh. Set the pixel values of the image data of the newly created ImageData object to represent the output bitmap for the area of that bitmap denoted by the rectangle whose corners are the four points (sx, sy), (sx+sw, sy), (sx+sw, sy+sh), (sx, sy+sh), in the bitmap's coordinate space units. Pixels outside the output bitmap must be set to transparent black. Pixel values must not be premultiplied by alpha.

When the user agent is required to create an ImageData object, given a positive integer number of rows rows, a positive integer number of pixels per row pixelsPerRow, and an optional Uint8ClampedArray source, it must run these steps:

  1. Let imageData be a new uninitialized ImageData object.

  2. If source is specified, then assign the data attribute of imageData to source.

  3. If source is not specified, then initialize the data attribute of imageData to a new Uint8ClampedArray object. The Uint8ClampedArray object must use a new Canvas Pixel ArrayBuffer for its storage, and must have a zero start offset and a length equal to the length of its storage, in bytes. The Canvas Pixel ArrayBuffer must have the correct size to store rows × pixelsPerRow pixels.

    If the Canvas Pixel ArrayBuffer cannot be allocated, then rethrow the RangeError thrown by JavaScript, and return.

  4. Initialize the width attribute of imageData to pixelsPerRow.

  5. Initialize the height attribute of imageData to rows.

  6. Return imageData.

ImageData objects are serializable objects. Their serialization steps, given value and serialized, are:

  1. Set serialized.[[Data]] to the sub-serialization of the value of value's data attribute.

  2. Set serialized.[[Width]] to the value of value's width attribute.

  3. Set serialized.[[Height]] to the value of value's height attribute.

Their deserialization steps, given serialized and value, are:

  1. Initialize value's data attribute to the sub-deserialization of serialized.[[Data]].

  2. Initialize value's width attribute to serialized.[[Width]].

  3. Initialize value's height attribute to serialized.[[Height]].

A Canvas Pixel ArrayBuffer is an ArrayBuffer whose data is represented in left-to-right order, row by row top to bottom, starting with the top left, with each pixel's red, green, blue, and alpha components being given in that order for each pixel. Each component of each pixel represented in this array must be in the range 0..255, representing the 8 bit value for that component. The components must be assigned consecutive indices starting with 0 for the top left pixel's red component.

The putImageData() method writes data from ImageData structures back to the rendering context's output bitmap. Its arguments are: imagedata, dx, dy, dirtyX, dirtyY, dirtyWidth, and dirtyHeight.

When the last four arguments to this method are omitted, they must be assumed to have the values 0, 0, the width member of the imagedata structure, and the height member of the imagedata structure, respectively.

The method, when invoked, must act as follows:

  1. Let buffer be imagedata's data attribute value's [[ViewedArrayBuffer]] internal slot.

  2. If IsDetachedBuffer(buffer) is true, then throw an "InvalidStateError" DOMException.

  3. If dirtyWidth is negative, then let dirtyX be dirtyX+dirtyWidth, and let dirtyWidth be equal to the absolute magnitude of dirtyWidth.

    If dirtyHeight is negative, then let dirtyY be dirtyY+dirtyHeight, and let dirtyHeight be equal to the absolute magnitude of dirtyHeight.

  4. If dirtyX is negative, then let dirtyWidth be dirtyWidth+dirtyX, and let dirtyX be zero.

    If dirtyY is negative, then let dirtyHeight be dirtyHeight+dirtyY, and let dirtyY be zero.

  5. If dirtyX+dirtyWidth is greater than the width attribute of the imagedata argument, then let dirtyWidth be the value of that width attribute, minus the value of dirtyX.

    If dirtyY+dirtyHeight is greater than the height attribute of the imagedata argument, then let dirtyHeight be the value of that height attribute, minus the value of dirtyY.

  6. If, after those changes, either dirtyWidth or dirtyHeight are negative or zero, then return without affecting any bitmaps.

  7. For all integer values of x and y where dirtyX ≤ x < dirtyX+dirtyWidth and dirtyY ≤ y < dirtyY+dirtyHeight, copy the four channels of the pixel with coordinate (x, y) in the imagedata data structure's Canvas Pixel ArrayBuffer to the pixel with coordinate (dx+x, dy+y) in the rendering context's output bitmap.

Due to the lossy nature of converting to and from premultiplied alpha color values, pixels that have just been set using putImageData() might be returned to an equivalent getImageData() as different values.

The current path, transformation matrix, shadow attributes, global alpha, the clipping region, and global composition operator must not affect the methods described in this section.

In the following example, the script generates an ImageData object so that it can draw onto it.

// canvas is a reference to a <canvas> element
var context = canvas.getContext('2d');

// create a blank slate
var data = context.createImageData(canvas.width, canvas.height);

// create some plasma
FillPlasma(data, 'green'); // green plasma

// add a cloud to the plasma
AddCloud(data, data.width/2, data.height/2); // put a cloud in the middle

// paint the plasma+cloud on the canvas
context.putImageData(data, 0, 0);

// support methods
function FillPlasma(data, color) { ... }
function AddCloud(data, x, y) { ... }

Here is an example of using getImageData() and putImageData() to implement an edge detection filter.

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Edge detection demo</title>
  <script>
   var image = new Image();
   function init() {
     image.onload = demo;
     image.src = "image.jpeg";
   }
   function demo() {
     var canvas = document.getElementsByTagName('canvas')[0];
     var context = canvas.getContext('2d');

     // draw the image onto the canvas
     context.drawImage(image, 0, 0);

     // get the image data to manipulate
     var input = context.getImageData(0, 0, canvas.width, canvas.height);

     // get an empty slate to put the data into
     var output = context.createImageData(canvas.width, canvas.height);

     // alias some variables for convenience
     // In this case input.width and input.height
     // match canvas.width and canvas.height
     // but we'll use the former to keep the code generic.
     var w = input.width, h = input.height;
     var inputData = input.data;
     var outputData = output.data;

     // edge detection
     for (var y = 1; y < h-1; y += 1) {
       for (var x = 1; x < w-1; x += 1) {
         for (var c = 0; c < 3; c += 1) {
           var i = (y*w + x)*4 + c;
           outputData[i] = 127 + -inputData[i - w*4 - 4] -   inputData[i - w*4] - inputData[i - w*4 + 4] +
                                 -inputData[i - 4]       + 8*inputData[i]       - inputData[i + 4] +
                                 -inputData[i + w*4 - 4] -   inputData[i + w*4] - inputData[i + w*4 + 4];
         }
         outputData[(y*w + x)*4 + 3] = 255; // alpha
       }
     }

     // put the image data back after manipulation
     context.putImageData(output, 0, 0);
   }
  </script>
 </head>
 <body onload="init()">
  <canvas></canvas>
 </body>
</html>
4.12.5.1.16 合成
context . globalAlpha [ = value ]

CanvasRenderingContext2D/globalAlpha

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

返回当前应用于渲染操作的 alpha 值。

可以设置来改变 alpha 值。在 0.0 .. 1.0 之外的值会被忽略。

context . globalCompositeOperation [ = value ]

CanvasRenderingContext2D/globalCompositeOperation

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

返回当前合成操作,来自 Compositing 和 Blending 规范定义的值。[COMPOSITE].

可以设置来改变合成操作。未知值会被忽略。

在实现了 CanvasCompositing 接口的对象上的所有绘图操作都会被全局合成属性影响: globalAlphaglobalCompositeOperation

globalAlpha 属性给出了应用于形状和图像在合成到 输出位图 上之前的 alpha 值。这个值必须在 0.0 (完全透明) 到 1.0 (不透明)之间。 如果尝试把这个值设置到范围外,包括 Infinity 和 Not-a-Number (NaN) 值,该属性必须保持之前的值。 当创建上下文时,必须把 globalAlpha 属性设置初始值 1.0。

globalCompositeOperation 属性 设置了 当前合成操作, 它控制着给定 globalAlpha 和当前转换矩阵,形状和图像如何绘制到 输出位图。 可能的值定义在 Compositing 和 Blending 规范,也包括 source-overcopy 值。 [COMPOSITE]

这些值是大小写敏感的 — 它们必须完全按照定义的方式使用。用户代理不得识别非 大小写敏感匹配的 Compositing 和 Blending 规范给出的值。[COMPOSITE]

在设置时,如果用户代理不识别指定的值,就必须忽略它,让 globalCompositeOperation 的值不受影响。 否则,必须把该属性的值设置为给定的新值。

当创建上下文时,必须把 globalCompositeOperation 属性设为初始值 source-over

4.12.5.1.17 Image smoothing
context . imageSmoothingEnabled [ = value ]

CanvasRenderingContext2D/imageSmoothingEnabled

Support in all current engines.

Firefox51+Safari9.1+Chrome30+
Opera17+Edge79+
Edge (Legacy)15+Internet Explorer🔰 11
Firefox Android51+Safari iOS9.3+Chrome Android30+WebView Android4.4+Samsung Internet2.0+Opera Android18+

Returns whether pattern fills and the drawImage() method will attempt to smooth images if their pixels don't line up exactly with the display, when scaling images up.

Can be set, to change whether images are smoothed (true) or not (false).

context . imageSmoothingQuality [ = value ]

CanvasRenderingContext2D/imageSmoothingQuality

FirefoxNoSafari9.1+Chrome54+
Opera41+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS9.3+Chrome Android54+WebView Android54+Samsung Internet6.0+Opera Android41+

Returns the current image-smoothing-quality preference.

Can be set, to change the preferred quality of image smoothing. The possible values are "low", "medium" and "high". Unknown values are ignored.

Objects that implement the CanvasImageSmoothing interface have attributes that control how image smoothing is performed.

The imageSmoothingEnabled attribute, on getting, must return the last value it was set to. On setting, it must be set to the new value. When the object implementing the CanvasImageSmoothing interface is created, the attribute must be set to true.

The imageSmoothingQuality attribute, on getting, must return the last value it was set to. On setting, it must be set to the new value. When the object implementing the CanvasImageSmoothing interface is created, the attribute must be set to "low".

4.12.5.1.18 Shadows

All drawing operations on an object which implements the CanvasShadowStyles interface are affected by the four global shadow attributes.

context . shadowColor [ = value ]

CanvasRenderingContext2D/shadowColor

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the current shadow color.

Can be set, to change the shadow color. Values that cannot be parsed as CSS colors are ignored.

context . shadowOffsetX [ = value ]

CanvasRenderingContext2D/shadowOffsetX

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
context . shadowOffsetY [ = value ]

CanvasRenderingContext2D/shadowOffsetY

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the current shadow offset.

Can be set, to change the shadow offset. Values that are not finite numbers are ignored.

context . shadowBlur [ = value ]

CanvasRenderingContext2D/shadowBlur

Support in all current engines.

Firefox1.5+Safari2+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the current level of blur applied to shadows.

Can be set, to change the blur level. Values that are not finite numbers greater than or equal to zero are ignored.

The shadowColor attribute sets the color of the shadow.

When the context is created, the shadowColor attribute initially must be transparent black.

On getting, the serialization of the color must be returned.

On setting, the new value must be parsed with this canvas element and the color assigned. If parsing the value results in failure then it must be ignored, and the attribute must retain its previous value. [CSSCOLOR]

The shadowOffsetX and shadowOffsetY attributes specify the distance that the shadow will be offset in the positive horizontal and positive vertical distance respectively. Their values are in coordinate space units. They are not affected by the current transformation matrix.

When the context is created, the shadow offset attributes must initially have the value 0.

On getting, they must return their current value. On setting, the attribute being set must be set to the new value, except if the value is infinite or NaN, in which case the new value must be ignored.

The shadowBlur attribute specifies the level of the blurring effect. (The units do not map to coordinate space units, and are not affected by the current transformation matrix.)

When the context is created, the shadowBlur attribute must initially have the value 0.

On getting, the attribute must return its current value. On setting the attribute must be set to the new value, except if the value is negative, infinite or NaN, in which case the new value must be ignored.

Shadows are only drawn if the opacity component of the alpha component of the color of shadowColor is nonzero and either the shadowBlur is nonzero, or the shadowOffsetX is nonzero, or the shadowOffsetY is nonzero.

When shadows are drawn, they must be rendered as follows:

  1. Let A be an infinite transparent black bitmap on which the source image for which a shadow is being created has been rendered.

  2. Let B be an infinite transparent black bitmap, with a coordinate space and an origin identical to A.

  3. Copy the alpha channel of A to B, offset by shadowOffsetX in the positive x direction, and shadowOffsetY in the positive y direction.

  4. If shadowBlur is greater than 0:

    1. Let σ be half the value of shadowBlur.

    2. Perform a 2D Gaussian Blur on B, using σ as the standard deviation.

    User agents may limit values of σ to an implementation-specific maximum value to avoid exceeding hardware limitations during the Gaussian blur operation.

  5. Set the red, green, and blue components of every pixel in B to the red, green, and blue components (respectively) of the color of shadowColor.

  6. Multiply the alpha component of every pixel in B by the alpha component of the color of shadowColor.

  7. The shadow is in the bitmap B, and is rendered as part of the drawing model described below.

If the current composition operation is copy, then shadows effectively won't render (since the shape will overwrite the shadow).

4.12.5.1.19 滤镜

对实现了 CanvasFilters 接口的对象的所有绘图操作 都会被全局 滤镜 属性影响。

context . filter [ = value ]

CanvasRenderingContext2D/filter

Firefox49+SafariNoChrome52+
Opera39+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android49+Safari iOSNoChrome Android52+WebView Android52+Samsung Internet6.0+Opera Android41+

返回当前滤镜。

可以设置它来改变滤镜。不能解析为 <filter-function-list> 的值会被忽略。

在读取 filter 属性时, 必须返回上一个成功设置的值。不得重新序列化它的值。 在设置时,如果新的值是 'none' (不是空字符串、 null 或 undefined), 那么必须禁用这个上下文的滤镜。 否则,必须把这个值解析为 <filter-function-list> 值。 如果该值不能解析为一个 <filter-function-list> 值, 其中独立于属性的样式表语法如 'inherit' 或 'initial' 被认为是非法值并被忽略, 而且该属性的值必须保持之前的值。当创建实现了 CanvasFilters 接口的对象时, 必须把该属性的值设为 'none'。

<filter-function-list> 值包括一个或更多滤镜函数或 SVG 滤镜的引用组成的序列。 滤镜的输入被用作该列表中第一个滤镜的输入。后续项取前一项的输出作为输入。 [FILTERS]

解释 filter 属性的值使用的坐标时, 一像素相当于一个 SVG 用户空间单位,一个 canvas 坐标空间单位。 滤镜坐标不会受 当前转换矩阵 影响。 当前转换矩阵只影响滤镜的输入。滤镜作用于 输出位图 的坐标空间。

如果 filter 属性的值使用 百分比或 'em''ex' 单位定义了长度,那么必须相对于设置该属性时 字体样式源对象'font-size' 属性的 计算后的值 来解释该长度。 如果 计算后的值 是 undefined (比如由于 字体样式源对象 不是元素或没有 被渲染), 那么必须相对于 font 属性的默认值来解释相对关键字。 不支持 'larger' 和 'smaller' 关键字。

如果 filter 属性的值是同一文档中 SVG 滤镜的引用,而且该 SVG 滤镜发生了改变,那么改变后的滤镜将会用作下一次绘图操作。

如果 filter 属性的值是外部资源文档中的 SVG 滤镜的引用,而且在调用绘图操作时该外部文档还没加载完成,那么执行该绘制操作时不得使用滤镜。

4.12.5.1.20 使用外部定义的 SVG 滤镜

This section is non-normative.

因为在外部定义的滤镜完成载入之前,绘制使用的滤镜值都是 'none', 因此作者可能希望在进行绘图操作前确定滤镜是否已经载入。 一种实现方式是在同一个页面的其他地方加一个元素来载入外部定义的滤镜, (比如 SVG use 元素), 然后等待 load 事件的派发。

4.12.5.1.21 Drawing model

When a shape or image is painted, user agents must follow these steps, in the order given (or act as if they do):

  1. Render the shape or image onto an infinite transparent black bitmap, creating image A, as described in the previous sections. For shapes, the current fill, stroke, and line styles must be honored, and the stroke must itself also be subjected to the current transformation matrix.

  2. When the filter attribute is set to a value other than 'none' and all the externally-defined filters it references, if any, are in documents that are currently loaded, then use image A as the input to the filter, creating image B. Otherwise, let B be an alias for A.

  3. When shadows are drawn, render the shadow from image B, using the current shadow styles, creating image C.

  4. When shadows are drawn, multiply the alpha component of every pixel in C by globalAlpha.

  5. When shadows are drawn, composite C within the clipping region over the current output bitmap using the current composition operator.

  6. Multiply the alpha component of every pixel in B by globalAlpha.

  7. Composite B within the clipping region over the current output bitmap using the current composition operator.

When compositing onto the output bitmap, pixels that would fall outside of the output bitmap must be discarded.

4.12.5.1.22 最佳实践

如果画布可交互,作者应该对画布的每个可聚焦部分,都在该元素的 fallback 内容中包含一个可聚焦元素, 像 上述例子 中那样。

当渲染焦点环时,为了确保焦点环的外观和原生焦点环相同,作者应该使用 drawFocusIfNeeded() 方法, 把需要绘制焦点环的元素传给它。该方法只在元素 获得焦点 时才绘制焦点环。这样就可以在每次绘制元素时简单地调用它,而不需要先检查元素是否已经获得焦点。

除了绘制焦点环以外,作者还应该在画布中的元素获得焦点时调用 scrollPathIntoView() 方法, 以确保它在屏幕上可见(如果可以的话)。

作者应该避免使用 canvas 元素 实现文本编辑控件,这样做有很多缺点:

这是巨大的工作量,而且强烈建议作者避免做任何这些事情,不如直接使用 input 元素, textarea 元素,或者 contenteditable 属性。

4.12.5.1.23 示例

This section is non-normative.

这是一个使用 canvas 绘图 漂亮的发光线 的脚本示例。

<canvas width="800" height="450"></canvas>
<script>

 var context = document.getElementsByTagName('canvas')[0].getContext('2d');

 var lastX = context.canvas.width * Math.random();
 var lastY = context.canvas.height * Math.random();
 var hue = 0;
 function line() {
   context.save();
   context.translate(context.canvas.width/2, context.canvas.height/2);
   context.scale(0.9, 0.9);
   context.translate(-context.canvas.width/2, -context.canvas.height/2);
   context.beginPath();
   context.lineWidth = 5 + Math.random() * 10;
   context.moveTo(lastX, lastY);
   lastX = context.canvas.width * Math.random();
   lastY = context.canvas.height * Math.random();
   context.bezierCurveTo(context.canvas.width * Math.random(),
                         context.canvas.height * Math.random(),
                         context.canvas.width * Math.random(),
                         context.canvas.height * Math.random(),
                         lastX, lastY);

   hue = hue + 10 * Math.random();
   context.strokeStyle = 'hsl(' + hue + ', 50%, 50%)';
   context.shadowColor = 'white';
   context.shadowBlur = 10;
   context.stroke();
   context.restore();
 }
 setInterval(line, 50);

 function blank() {
   context.fillStyle = 'rgba(0,0,0,0.1)';
   context.fillRect(0, 0, context.canvas.width, context.canvas.height);
 }
 setInterval(blank, 40);

</script>

基于雪碧图的游戏经常使用 canvas 的 2D 渲染上下文。下面的例子可以作为演示:

这是该例子的源码:

<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">
<title>Blue Robot Demo</title>
<style>
  html { overflow: hidden; min-height: 200px; min-width: 380px; }
  body { height: 200px; position: relative; margin: 8px; }
  .buttons { position: absolute; bottom: 0px; left: 0px; margin: 4px; }
</style>
<canvas width="380" height="200"></canvas>
<script>
 var Landscape = function (context, width, height) {
   this.offset = 0;
   this.width = width;
   this.advance = function (dx) {
     this.offset += dx;
   };
   this.horizon = height * 0.7;
   // This creates the sky gradient (from a darker blue to white at the bottom)
   this.sky = context.createLinearGradient(0, 0, 0, this.horizon);
   this.sky.addColorStop(0.0, 'rgb(55,121,179)');
   this.sky.addColorStop(0.7, 'rgb(121,194,245)');
   this.sky.addColorStop(1.0, 'rgb(164,200,214)');
   // this creates the grass gradient (from a darker green to a lighter green)
   this.earth = context.createLinearGradient(0, this.horizon, 0, height);
   this.earth.addColorStop(0.0, 'rgb(81,140,20)');
   this.earth.addColorStop(1.0, 'rgb(123,177,57)');
   this.paintBackground = function (context, width, height) {
     // first, paint the sky and grass rectangles
     context.fillStyle = this.sky;
     context.fillRect(0, 0, width, this.horizon);
     context.fillStyle = this.earth;
     context.fillRect(0, this.horizon, width, height-this.horizon);
     // then, draw the cloudy banner
     // we make it cloudy by having the draw text off the top of the
     // canvas, and just having the blurred shadow shown on the canvas
     context.save();
     context.translate(width-((this.offset+(this.width*3.2)) % (this.width*4.0))+0, 0);
     context.shadowColor = 'white';
     context.shadowOffsetY = 30+this.horizon/3; // offset down on canvas
     context.shadowBlur = '5';
     context.fillStyle = 'white';
     context.textAlign = 'left';
     context.textBaseline = 'top';
     context.font = '20px sans-serif';
     context.fillText('WHATWG ROCKS', 10, -30); // text up above canvas
     context.restore();
     // then, draw the background tree
     context.save();
     context.translate(width-((this.offset+(this.width*0.2)) % (this.width*1.5))+30, 0);
     context.beginPath();
     context.fillStyle = 'rgb(143,89,2)';
     context.lineStyle = 'rgb(10,10,10)';
     context.lineWidth = 2;
     context.rect(0, this.horizon+5, 10, -50); // trunk
     context.fill();
     context.stroke();
     context.beginPath();
     context.fillStyle = 'rgb(78,154,6)';
     context.arc(5, this.horizon-60, 30, 0, Math.PI*2); // leaves
     context.fill();
     context.stroke();
     context.restore();
   };
   this.paintForeground = function (context, width, height) {
     // draw the box that goes in front
     context.save();
     context.translate(width-((this.offset+(this.width*0.7)) % (this.width*1.1))+0, 0);
     context.beginPath();
     context.rect(0, this.horizon - 5, 25, 25);
     context.fillStyle = 'rgb(220,154,94)';
     context.lineStyle = 'rgb(10,10,10)';
     context.lineWidth = 2;
     context.fill();
     context.stroke();
     context.restore();
   };
 };
</script>
<script>
 var BlueRobot = function () {
   this.sprites = new Image();
   this.sprites.src = 'blue-robot.png'; // this sprite sheet has 8 cells
   this.targetMode = 'idle';
   this.walk = function () {
     this.targetMode = 'walk';
   };
   this.stop = function () {
     this.targetMode = 'idle';
   };
   this.frameIndex = {
     'idle': [0], // first cell is the idle frame
     'walk': [1,2,3,4,5,6], // the walking animation is cells 1-6
     'stop': [7], // last cell is the stopping animation
   };
   this.mode = 'idle';
   this.frame = 0; // index into frameIndex
   this.tick = function () {
     // this advances the frame and the robot
     // the return value is how many pixels the robot has moved
     this.frame += 1;
     if (this.frame >= this.frameIndex[this.mode].length) {
       // we've reached the end of this animation cycle
       this.frame = 0;
       if (this.mode != this.targetMode) {
         // switch to next cycle
         if (this.mode == 'walk') {
           // we need to stop walking before we decide what to do next
           this.mode = 'stop';
         } else if (this.mode == 'stop') {
           if (this.targetMode == 'walk')
             this.mode = 'walk';
           else
             this.mode = 'idle';
         } else if (this.mode == 'idle') {
           if (this.targetMode == 'walk')
             this.mode = 'walk';
         }
       }
     }
     if (this.mode == 'walk')
       return 8;
     return 0;
   },
   this.paint = function (context, x, y) {
     if (!this.sprites.complete) return;
     // draw the right frame out of the sprite sheet onto the canvas
     // we assume each frame is as high as the sprite sheet
     // the x,y coordinates give the position of the bottom center of the sprite
     context.drawImage(this.sprites,
                       this.frameIndex[this.mode][this.frame] * this.sprites.height, 0, this.sprites.height, this.sprites.height,
                       x-this.sprites.height/2, y-this.sprites.height, this.sprites.height, this.sprites.height);
   };
 };
</script>
<script>
 var canvas = document.getElementsByTagName('canvas')[0];
 var context = canvas.getContext('2d');
 var landscape = new Landscape(context, canvas.width, canvas.height);
 var blueRobot = new BlueRobot();
 // paint when the browser wants us to, using requestAnimationFrame()
 function paint() {
   context.clearRect(0, 0, canvas.width, canvas.height);
   landscape.paintBackground(context, canvas.width, canvas.height);
   blueRobot.paint(context, canvas.width/2, landscape.horizon*1.1);
   landscape.paintForeground(context, canvas.width, canvas.height);
   requestAnimationFrame(paint);
 }
 paint();
 // but tick every 100ms, so that we don't slow down when we don't paint
 setInterval(function () {
   var dx = blueRobot.tick();
   landscape.advance(dx);
 }, 100);
</script>
<p class="buttons">
 <input type=button value="Walk" onclick="blueRobot.walk()">
 <input type=button value="Stop" onclick="blueRobot.stop()">
<footer>
 <small> Blue Robot Player Sprite by <a href="https://johncolburn.deviantart.com/">JohnColburn</a>.
 Licensed under the terms of the Creative Commons Attribution Share-Alike 3.0 Unported license.</small>
 <small> This work is itself licensed under a <a rel="license" href="https://creativecommons.org/licenses/by-sa/3.0/">Creative
 Commons Attribution-ShareAlike 3.0 Unported License</a>.</small>
</footer>
4.12.5.2 ImageBitmap 渲染上下文
4.12.5.2.1 Introduction

ImageBitmapRenderingContext is a performance-oriented interface that provides a low overhead method for displaying the contents of ImageBitmap objects. It uses transfer semantics to reduce overall memory consumption. It also streamlines performance by avoiding intermediate compositing, unlike the drawImage() method of CanvasRenderingContext2D.

Using an img element as an intermediate for getting an image resource into a canvas, for example, would result in two copies of the decoded image existing in memory at the same time: the img element's copy, and the one in the canvas's backing store. This memory cost can be prohibitive when dealing with extremely large images. This can be avoided by using ImageBitmapRenderingContext.

Using ImageBitmapRenderingContext, here is how to transcode an image to the JPEG format in a memory- and CPU-efficient way:

createImageBitmap(inputImageBlob).then(image => {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('bitmaprenderer');
  context.transferFromImageBitmap(image);

  canvas.toBlob(outputJPEGBlob => {
    // Do something with outputJPEGBlob.
  }, 'image/jpeg');
});
4.12.5.2.2 The ImageBitmapRenderingContext interface

ImageBitmapRenderingContext

Support in all current engines.

Firefox46+Safari15+Chrome56+
Opera43+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android46+Safari iOS15+Chrome Android56+WebView Android56+Samsung Internet6.0+Opera Android43+
[Exposed=(Window,Worker)]
interface ImageBitmapRenderingContext {
  readonly attribute (HTMLCanvasElement or OffscreenCanvas) canvas;
  undefined transferFromImageBitmap(ImageBitmap? bitmap);
};

dictionary ImageBitmapRenderingContextSettings {
  boolean alpha = true;
};
context = canvas . getContext('bitmaprenderer' [, { [ alpha: false ] } ] )

Returns an ImageBitmapRenderingContext object that is permanently bound to a particular canvas element.

If the alpha setting is provided and set to false, then the canvas is forced to always be opaque.

context . canvas

Returns the canvas element that the context is bound to.

context . transferFromImageBitmap(imageBitmap)

ImageBitmapRenderingContext/transferFromImageBitmap

Support in all current engines.

Firefox52+Safari15+Chrome56+
Opera43+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android52+Safari iOS15+Chrome Android56+WebView Android56+Samsung Internet6.0+Opera Android43+

Transfers the underlying bitmap data from imageBitmap to context, and the bitmap becomes the contents of the canvas element to which context is bound.

context . transferFromImageBitmap(null)

Replaces contents of the canvas element to which context is bound with a transparent black bitmap whose size corresponds to the width and height content attributes of the canvas element.

The canvas attribute must return the value it was initialized to when the object was created.

An ImageBitmapRenderingContext object has an output bitmap, which is a reference to bitmap data.

An ImageBitmapRenderingContext object has a bitmap mode, which can be set to valid or blank. A value of valid indicates that the context's output bitmap refers to bitmap data that was acquired via transferFromImageBitmap(). A value blank indicates that the context's output bitmap is a default transparent bitmap.

An ImageBitmapRenderingContext object also has an alpha flag, which can be set to true or false. When an ImageBitmapRenderingContext object has its alpha flag set to false, the contents of the canvas element to which the context is bound are obtained by compositing the context's output bitmap onto an opaque black bitmap of the same size using the source-over composite operation. If the alpha flag is set to true, then the output bitmap is used as the contents of the canvas element to which the context is bound. [COMPOSITE]

The step of compositing over an opaque black bitmap ought to be elided whenever equivalent results can be obtained more efficiently by other means.


When a user agent is required to set an ImageBitmapRenderingContext's output bitmap, with a context argument that is an ImageBitmapRenderingContext object and an optional argument bitmap that refers to bitmap data, it must run these steps:

  1. If a bitmap argument was not provided, then:

    1. Set context's bitmap mode to blank.

    2. Let canvas be the canvas element to which context is bound.

    3. Set context's output bitmap to be transparent black with an intrinsic width equal to the numeric value of canvas's width attribute and an intrinsic height equal to the numeric value of canvas's height attribute, those values being interpreted in CSS pixels.

    4. Set the output bitmap's origin-clean flag to true.

  2. If a bitmap argument was provided, then:

    1. Set context's bitmap mode to valid.

    2. Set context's output bitmap to refer to the same underlying bitmap data as bitmap, without making a copy.

      The origin-clean flag of bitmap is included in the bitmap data to be referenced by context's output bitmap.


The ImageBitmapRenderingContext creation algorithm, which is passed a target and options, consists of running these steps:

  1. Let settings be the result of converting options to the dictionary type ImageBitmapRenderingContextSettings. (This can throw an exception.)

  2. Let context be a new ImageBitmapRenderingContext object.

  3. Initialize context's canvas attribute to point to target.

  4. Set context's output bitmap to the same bitmap as target's bitmap (so that they are shared).

  5. Run the steps to set an ImageBitmapRenderingContext's output bitmap with context.

  6. Initialize context's alpha flag to true.

  7. Process each of the members of settings as follows:

    alpha
    If false, then set context's alpha flag to false.
  8. Return context.


The transferFromImageBitmap(imageBitmap) method, when invoked, must run these steps:

  1. Let bitmapContext be the ImageBitmapRenderingContext object on which the transferFromImageBitmap() method was called.

  2. If imageBitmap is null, then run the steps to set an ImageBitmapRenderingContext's output bitmap, with bitmapContext as the context argument and no bitmap argument, then return.

  3. If the value of imageBitmap's [[Detached]] internal slot is set to true, then throw an "InvalidStateError" DOMException.

  4. Run the steps to set an ImageBitmapRenderingContext's output bitmap, with the context argument equal to bitmapContext, and the bitmap argument referring to imageBitmap's underlying bitmap data.

  5. Set the value of imageBitmap's [[Detached]] internal slot to true.

  6. Unset imageBitmap's bitmap data.

4.12.5.3 The OffscreenCanvas interface

OffscreenCanvas

Support in one engine only.

Firefox🔰 44+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome Android69+WebView Android69+Samsung Internet10.0+Opera Android48+
typedef (OffscreenCanvasRenderingContext2D or ImageBitmapRenderingContext or WebGLRenderingContext or WebGL2RenderingContext) OffscreenRenderingContext;

dictionary ImageEncodeOptions {
  DOMString type = "image/png";
  unrestricted double quality;
};

enum OffscreenRenderingContextId { "2d", "bitmaprenderer", "webgl", "webgl2" };

[Exposed=(Window,Worker), Transferable]
interface OffscreenCanvas : EventTarget {
  constructor([EnforceRange] unsigned long long width, [EnforceRange] unsigned long long height);

  attribute [EnforceRange] unsigned long long width;
  attribute [EnforceRange] unsigned long long height;

  OffscreenRenderingContext? getContext(OffscreenRenderingContextId contextId, optional any options = null);
  ImageBitmap transferToImageBitmap();
  Promise<Blob> convertToBlob(optional ImageEncodeOptions options = {});
};

OffscreenCanvas is an EventTarget so that WebGL can fire webglcontextlost and webglcontextrestored events at it. [WEBGL]

OffscreenCanvas objects are used to create rendering contexts, much like an HTMLCanvasElement, but with no connection to the DOM. This makes it possible to use canvas rendering contexts in workers.

WebGLRenderingContext/commit

Support in one engine only.

Firefox🔰 44+SafariNoChromeNo
OperaNoEdgeNo
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo

An OffscreenCanvas object may hold a weak reference to a placeholder canvas element, which is typically in the DOM, whose embedded content is provided by the OffscreenCanvas object. The bitmap of the OffscreenCanvas object is pushed to the placeholder canvas element by calling the commit() method of the OffscreenCanvas object's rendering context. All rendering context types that can be created by an OffscreenCanvas object must implement a commit() method. The exact behavior of the commit method (e.g. whether it copies or transfers bitmaps) may vary, as defined by the rendering contexts' respective specifications. Only the 2D context for offscreen canvases is defined in this specification.

offscreenCanvas = new OffscreenCanvas(width, height)

OffscreenCanvas/OffscreenCanvas

Support in one engine only.

Firefox🔰 46+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome Android69+WebView Android69+Samsung Internet10.0+Opera Android48+

Returns a new OffscreenCanvas object that is not linked to a placeholder canvas element, and whose bitmap's size is determined by the width and height arguments.

context = offscreenCanvas . getContext(contextId [, options ] )

OffscreenCanvas/getContext

Support in one engine only.

Firefox🔰 44+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome Android69+WebView Android69+Samsung Internet10.0+Opera Android48+

Returns an object that exposes an API for drawing on the OffscreenCanvas object. contextId specifies the desired API: "2d", "bitmaprenderer", "webgl", or "webgl2". options is handled by that API.

This specification defines the "2d" context below, which is similar but distinct from the "2d" context that is created from a canvas element. The WebGL specifications define the "webgl" and "webgl2" contexts. [WEBGL]

Returns null if the canvas has already been initialized with another context type (e.g., trying to get a "2d" context after getting a "webgl" context).

An OffscreenCanvas object has an internal bitmap that is initialized when the object is created. The width and height of the bitmap are equal to the values of the width and height attributes of the OffscreenCanvas object. Initially, all the bitmap's pixels are transparent black.

An OffscreenCanvas object can have a rendering context bound to it. Initially, it does not have a bound rendering context. To keep track of whether it has a rendering context or not, and what kind of rendering context it is, an OffscreenCanvas object also has a context mode, which is initially none but can be changed to either 2d, bitmaprenderer, webgl, webgl2, or detached by algorithms defined in this specification.

The constructor OffscreenCanvas(width, height), when invoked, must create a new OffscreenCanvas object with its bitmap initialized to a rectangular array of transparent black pixels of the dimensions specified by width and height; and its width and height attributes initialized to width and height respectively.


OffscreenCanvas objects are transferable. Their transfer steps, given value and dataHolder, are as follows:

  1. If value's context mode is not equal to none, then throw an "InvalidStateError" DOMException.

  2. Set value's context mode to detached.

  3. Let width and height be the dimensions of value's bitmap.

  4. Unset value's bitmap.

  5. Set dataHolder.[[Width]] to width and dataHolder.[[Height]] to height.

  6. Set dataHolder.[[PlaceholderCanvas]] to be a weak reference to value's placeholder canvas element, if value has one, or null if it does not.

Their transfer-receiving steps, given dataHolder and value, are:

  1. Initialize value's bitmap to a rectangular array of transparent black pixels with width given by dataHolder.[[Width]] and height given by dataHolder.[[Height]].

  2. If dataHolder.[[PlaceholderCanvas]] is not null, set value's placeholder canvas element to dataHolder.[[PlaceholderCanvas]] (while maintaining the weak reference semantics).


The getContext(contextId, options) method of an OffscreenCanvas object, when invoked, must run these steps:

  1. If options is not an object, then set options to null.

  2. Set options to the result of converting options to a JavaScript value.

  3. Run the steps in the cell of the following table whose column header matches this OffscreenCanvas object's context mode and whose row header matches contextId:

    none 2d bitmaprenderer webgl or webgl2 detached
    "2d" Follow the offscreen 2D context creation algorithm defined in the section below, passing it this OffscreenCanvas object and options, to obtain an OffscreenCanvasRenderingContext2D object; if this does not throw an exception, then set this OffscreenCanvas object's context mode to 2d, and return the new OffscreenCanvasRenderingContext2D object. Return the same object as was returned the last time the method was invoked with this same first argument. Return null. Return null. Throw an "InvalidStateError" DOMException.
    "bitmaprenderer" Follow the ImageBitmapRenderingContext creation algorithm defined in the section above, passing it this OffscreenCanvas object and options, to obtain an ImageBitmapRenderingcontext object; if this does not throw an exception, then set this OffscreenCanvas object's context mode to bitmaprenderer, and return the new ImageBitmapRenderingcontext object. Return null. Return the same object as was returned the last time the method was invoked with this same first argument. Return null. Throw an "InvalidStateError" DOMException.
    "webgl" or "webgl2" Follow the instructions given in the WebGL specifications' Context Creation sections to obtain either a WebGLRenderingContext, WebGL2RenderingContext, or null; if the returned value is null, then return null; otherwise, set this OffscreenCanvas object's context mode to webgl or webgl2, and return the WebGLRenderingContext or WebGL2RenderingContext object. [WEBGL] Return null. Return null. Return the same value as was returned the last time the method was invoked with this same first argument. Throw an "InvalidStateError" DOMException.

offscreenCanvas . width [ = value ]

OffscreenCanvas/width

Support in one engine only.

Firefox🔰 44+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome Android69+WebView Android69+Samsung Internet10.0+Opera Android48+
offscreenCanvas . height [ = value ]

OffscreenCanvas/height

Support in one engine only.

Firefox🔰 44+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome Android69+WebView Android69+Samsung Internet10.0+Opera Android48+

These attributes return the dimensions of the OffscreenCanvas object's bitmap.

They can be set, to replace the bitmap with a new, transparent black bitmap of the specified dimensions (effectively resizing it).

If either the width or height attributes of an OffscreenCanvas object are set (to a new value or to the same value as before) and the OffscreenCanvas object's context mode is 2d, then replace the OffscreenCanvas object's bitmap with a new transparent black bitmap and reset the rendering context to its default state. The new bitmap's dimensions are equal to the new values of the width and height attributes.

The resizing behavior for "webgl" and "webgl2" contexts is defined in the WebGL specifications. [WEBGL]

If an OffscreenCanvas object whose dimensions were changed has a placeholder canvas element, then the placeholder canvas element's intrinsic size will only be updated via the commit() method of the OffscreenCanvas object's rendering context.

promise = offscreenCanvas . convertToBlob( [options] )

OffscreenCanvas/convertToBlob

Support in one engine only.

Firefox🔰 46+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome Android69+WebView Android69+Samsung Internet10.0+Opera Android48+

Returns a promise that will fulfill with a new Blob object representing a file containing the image in the OffscreenCanvas object.

The argument, if provided, is a dictionary that controls the encoding options of the image file to be created. The type field specifies the file format and has a default value of "image/png"; that type is also used if the requested type isn't supported. If the image format supports variable quality (such as "image/jpeg"), then the quality field is a number in the range 0.0 to 1.0 inclusive indicating the desired quality level for the resulting image.

canvas . transferToImageBitmap()

OffscreenCanvas/transferToImageBitmap

Support in one engine only.

Firefox🔰 46+SafariNoChrome69+
Opera56+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome Android69+WebView Android69+Samsung Internet10.0+Opera Android48+

Returns a newly created ImageBitmap object with the image in the OffscreenCanvas object. The image in the OffscreenCanvas object is replaced with a new blank image.

The convertToBlob(options) method, when invoked, must run the following steps:

  1. If the value of this OffscreenCanvas object's [[Detached]] internal slot is set to true, then return a promise rejected with an "InvalidStateError" DOMException.

  2. If this OffscreenCanvas object's context mode is 2d and the rendering context's bitmap's origin-clean flag is set to false, then return a promise rejected with a "SecurityError" DOMException.

  3. If this OffscreenCanvas object's bitmap has no pixels (i.e., either its horizontal dimension or its vertical dimension is zero) then return a promise rejected with an "IndexSizeError" DOMException.

  4. Let bitmap be a copy of this OffscreenCanvas object's bitmap.

  5. Let result be a new promise object.

  6. Run these steps in parallel:

    1. Let file be a serialization of bitmap as a file, with options's type and quality if present.

    2. Queue an element task on the canvas blob serialization task source given the canvas element to run these steps:

      1. If file is null, then reject result with an "EncodingError" DOMException.

      2. Otherwise, resolve result with a new Blob object, created in the relevant Realm of this OffscreenCanvas object, representing file. [FILEAPI]

  7. Return result.

The transferToImageBitmap() method, when invoked, must run the following steps:

  1. If the value of this OffscreenCanvas object's [[Detached]] internal slot is set to true, then throw an "InvalidStateError" DOMException.

  2. If this OffscreenCanvas object's context mode is set to none, then throw an "InvalidStateError" DOMException.

  3. Let image be a newly created ImageBitmap object that references the same underlying bitmap data as this OffscreenCanvas object's bitmap.

  4. Set this OffscreenCanvas object's bitmap to reference a newly created bitmap of the same dimensions as the previous bitmap, and with its pixels initialized to transparent black, or opaque black if the rendering context's alpha flag is set to false.

    This means that if the rendering context of this OffscreenCanvas is a WebGLRenderingContext, the value of preserveDrawingBuffer will have no effect. [WEBGL]

  5. Return image.

4.12.5.3.1 The offscreen 2D rendering context
[Exposed=(Window,Worker)]
interface OffscreenCanvasRenderingContext2D {
  undefined commit();
  readonly attribute OffscreenCanvas canvas;
};

OffscreenCanvasRenderingContext2D includes CanvasState;
OffscreenCanvasRenderingContext2D includes CanvasTransform;
OffscreenCanvasRenderingContext2D includes CanvasCompositing;
OffscreenCanvasRenderingContext2D includes CanvasImageSmoothing;
OffscreenCanvasRenderingContext2D includes CanvasFillStrokeStyles;
OffscreenCanvasRenderingContext2D includes CanvasShadowStyles;
OffscreenCanvasRenderingContext2D includes CanvasFilters;
OffscreenCanvasRenderingContext2D includes CanvasRect;
OffscreenCanvasRenderingContext2D includes CanvasDrawPath;
OffscreenCanvasRenderingContext2D includes CanvasText;
OffscreenCanvasRenderingContext2D includes CanvasDrawImage;
OffscreenCanvasRenderingContext2D includes CanvasImageData;
OffscreenCanvasRenderingContext2D includes CanvasPathDrawingStyles;
OffscreenCanvasRenderingContext2D includes CanvasTextDrawingStyles;
OffscreenCanvasRenderingContext2D includes CanvasPath;

The OffscreenCanvasRenderingContext2D object is a rendering context for drawing to the bitmap of an OffscreenCanvas object. It is similar to the CanvasRenderingContext2D object, with the following differences:

An OffscreenCanvasRenderingContext2D object has a bitmap that is initialized when the object is created.

The bitmap has an origin-clean flag, which can be set to true or false. Initially, when one of these bitmaps is created, its origin-clean flag must be set to true.

An OffscreenCanvasRenderingContext2D object also has an alpha flag, which can be set to true or false. Initially, when the context is created, its alpha flag must be set to true. When an OffscreenCanvasRenderingContext2D object has its alpha flag set to false, then its alpha channel must be fixed to 1.0 (fully opaque) for all pixels, and attempts to change the alpha component of any pixel must be silently ignored.

An OffscreenCanvasRenderingContext2D object has an associated OffscreenCanvas object, which is the OffscreenCanvas object from which the OffscreenCanvasRenderingContext2D object was created.

offscreenCanvasRenderingContext2D . commit()

Copies the rendering context's bitmap to the bitmap of the placeholder canvas element of the associated OffscreenCanvas object. The copy operation is synchronous. Calling this method is not needed for the transfer, since it happens automatically during the event loop execution.

offscreenCanvas = offscreenCanvasRenderingContext2D . canvas

Returns the associated OffscreenCanvas object.

The offscreen 2D context creation algorithm, which is passed a target (an OffscreenCanvas object) and optionally some arguments, consists of running the following steps:

  1. If the algorithm was passed some arguments, let arg be the first such argument. Otherwise, let arg be undefined.

  2. Let settings be the result of converting options to the dictionary type CanvasRenderingContext2DSettings. (This can throw an exception.).

  3. Let context be a new OffscreenCanvasRenderingContext2D object.

  4. Set context's associated OffscreenCanvas object to target.

  5. Process each of the members of settings as follows:

    alpha
    If false, set context's alpha flag to false.
  6. Set context's bitmap to a newly created bitmap with the dimensions specified by the width and height attributes of target, and set target's bitmap to the same bitmap (so that they are shared).

  7. If context's alpha flag is set to true, initialize all the pixels of context's bitmap to transparent black. Otherwise, initialize the pixels to opaque black.

  8. Return context.

The commit() method, when invoked, must run the following steps:

  1. If this OffscreenCanvasRenderingContext2D's associated OffscreenCanvas object does not have a placeholder canvas element, then return.

  2. Let image be a copy of this OffscreenCanvasRenderingContext2D's bitmap, including the value of its origin-clean flag.

  3. Queue an element task on the DOM manipulation task source given the placeholder canvas element to set the placeholder canvas element's output bitmap to be a reference to image.

    If image has different dimensions than the bitmap previously referenced as the placeholder canvas element's output bitmap, then this task will result in a change in the placeholder canvas element's intrinsic size, which can affect document layout.

Implementations are encouraged to short-circuit the graphics update steps of the window event loop for the purposes of updating the contents of a placeholder canvas element to the display. This could mean, for example, that the commit() method can copy the bitmap contents directly to a graphics buffer that is mapped to the physical display location of the placeholder canvas element. This or similar short-circuiting approaches can significantly reduce display latency, especially in cases where the commit() method is invoked from a worker event loop and the window event loop of the placeholder canvas element is busy. However, such shortcuts can not have any script-observable side-effects. This means that the committed bitmap still needs to be sent to the placeholder canvas element, in case the element is used as a CanvasImageSource, as an ImageBitmapSource, or in case toDataURL() or toBlob() are called on it.

The canvas attribute, on getting, must return this OffscreenCanvasRenderingContext2D's associated OffscreenCanvas object.

4.12.5.4 Color spaces and color correction

The canvas APIs must perform color correction at only two points: when rendering images with their own gamma correction and color space information onto a bitmap, to convert the image to the color space used by the bitmaps (e.g. using the 2D Context's drawImage() method with an HTMLOrSVGImageElement object), and when rendering the actual canvas bitmap to the output device.

Thus, in the 2D context, colors used to draw shapes onto the canvas will exactly match colors obtained through the getImageData() method.

The toDataURL() method, when invoked, must not include color space information in the resources they return. Where the output format allows it, the color of pixels in resources created by toDataURL() must match those returned by the getImageData() method.

In user agents that support CSS, the color space used by a canvas element must match the color space used for processing any colors for that element in CSS.

The gamma correction and color space information of images must be handled in such a way that an image rendered directly using an img element would use the same colors as one painted on a canvas element that is then itself rendered. Furthermore, the rendering of images that have no color correction information (such as those returned by the toDataURL() method) must be rendered with no color correction.

Thus, in the 2D context, calling the drawImage() method to render the output of the toDataURL() method to the canvas, given the appropriate dimensions, has no visible effect.

4.12.5.5 Serializing bitmaps to a file

When a user agent is to create a serialization of the bitmap as a file, given a type and an optional quality, it must create an image file in the format given by type. If an error occurs during the creation of the image file (e.g. an internal encoder error), then the result of the serialization is null. [PNG]

The image file's pixel data must be the bitmap's pixel data scaled to one image pixel per coordinate space unit, and if the file format used supports encoding resolution metadata, the resolution must be given as 96dpi (one image pixel per CSS pixel).

If type is supplied, then it must be interpreted as a MIME type giving the format to use. If the type has any parameters, then it must be treated as not supported.

For example, the value "image/png" would mean to generate a PNG image, the value "image/jpeg" would mean to generate a JPEG image, and the value "image/svg+xml" would mean to generate an SVG image (which would require that the user agent track how the bitmap was generated, an unlikely, though potentially awesome, feature).

User agents must support PNG ("image/png"). User agents may support other types. If the user agent does not support the requested type, then it must create the file using the PNG format. [PNG]

User agents must convert the provided type to ASCII lowercase before establishing if they support that type.

For image types that do not support an alpha channel, the serialized image must be the bitmap image composited onto an opaque black background using the source-over operator.

If type is an image format that supports variable quality (such as "image/jpeg"), quality is given, and type is not "image/png", then, if Type(quality) is Number, and quality is in the range 0.0 to 1.0 inclusive, the user agent must treat quality as the desired quality level. Otherwise, the user agent must use its default quality value, as if the quality argument had not been given.

The use of type-testing here, instead of simply declaring quality as a Web IDL double, is a historical artifact.

Different implementations can have slightly different interpretations of "quality". When the quality is not specified, an implementation-specific default is used that represents a reasonable compromise between compression ratio, image quality, and encoding time.

4.12.5.6 canvas 元素的安全问题

This section is non-normative.

如果一个 的脚本可以访问另一个(非 同域 的) 域的图片信息(例如读取像素)就可能发生 信息泄露

为了减轻这个问题, canvas 元素和 ImageBitmap 对象使用的位图定义有一个标志, 来表示它们是否 origin-clean。 所有位图开始时 origin-clean 都设为 true。 使用到跨域图片时该标志被设为 false。

toDataURL(), toBlob(), 和 getImageData() 方法会检查这个标志, 并且会抛出一个 "SecurityError" DOMException, 以保证不泄漏跨域数据。

origin-clean 标志的值会通过 createImageBitmap() 从一个 源 canvas 元素的位图传播到新的 ImageBitmap 对象。 反过来,如果源 ImageBitmap 对象的位图的 origin-clean 标志为 false, 目标 canvas 元素的位图在 drawImage 时会把它的 origin-clean 标志设为 false。

在某些情况下这个标志会被重置;例如绑定有 CanvasRenderingContext2Dcanvas 元素的 widthheight 内容属性的值改变时,该位图会被清空且它的 origin-clean 标志会被重置。

ImageBitmapRenderingContext 中, 当 ImageBitmap 对象通过 transferFromImageBitmap() 转移到 canvas 时,它的 origin-clean 标志会被传播。

4.13 Custom elements

Using_custom_elements

Support in all current engines.

Firefox63+Safari10.1+Chrome54+
Opera41+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10.3+Chrome Android54+WebView Android54+Samsung Internet6.0+Opera Android41+

4.13.1 概述

This section is non-normative.

Custom elements 为作者提供了一种构建他们自己的完整特性的 DOM 元素的方式。即使作者们总是可以在他们的文档中使用非标准元素, 在生效之后使用类似脚本的方式给它们增加应用相关的行为, 但是这些元素由于历史原因表现并不一致,也不是很好用。 通过 定义 custom element, 作者可以告知解析器如何适当地构造一个元素,以及这类元素如何响应变化。

Custom elements 是 "解释 Web 平台" 努力中的一部分, 在这一工作中,我们通过将低层的可扩展点(比如定义 Custom Element)暴露给作者, 来解释既有的平台特性(比如 HTML 的元素)。 即使现在 Custom Element 在功能和语义上都有很多能力的局限, 尚不能完整地解释现存 HTML 元素的行为,我们希望随着时间的推移逐渐缩小这个差异。

4.13.1.1 创建自主的 Custom Element

This section is non-normative.

为了说明如何创建 autonomous custom element, 我们定义 Custom Element 来封装一个显示国旗的小图标。 我们的目标是可以像这样使用它:

<flag-icon country="nl"></flag-icon>

为了实现这一效果,我们首先为该 Custom Element 声明一个类,扩展 HTMLElement

class FlagIcon extends HTMLElement {
  constructor() {
    super();
    this._countryCode = null;
  }

  static get observedAttributes() { return ["country"]; }

  attributeChangedCallback(name, oldValue, newValue) {
    // name will always be "country" due to observedAttributes
    this._countryCode = newValue;
    this._updateRendering();
  }
  connectedCallback() {
    this._updateRendering();
  }

  get country() {
    return this._countryCode;
  }
  set country(v) {
    this.setAttribute("country", v);
  }

  _updateRendering() {
    // Left as an exercise for the reader. But, you'll probably want to
    // check this.ownerDocument.defaultView to see if we've been
    // inserted into a document with a browsing context, and avoid
    // doing any work if not.
  }
}

我们现在需要使用这个类来定义这个元素:

customElements.define("flag-icon", FlagIcon);

此时,上述代码生效了!解析器一旦看到 flag-icon 标签, 就会为我们的 FlagIcon 类构造一个新的实例,并把新的 country 属性告诉我们的代码, 接着我们用它来设置内部状态并更新渲染(在适当的时候)。

你也可以使用 DOM API 创建 flag-icon 元素:

const flagIcon = document.createElement("flag-icon")
flagIcon.country = "jp"
document.body.appendChild(flagIcon)

最后,我们还可以直接使用 custom element 构造器。 这就是说上述代码等效于:

const flagIcon = new FlagIcon()
flagIcon.country = "jp"
document.body.appendChild(flagIcon)
4.13.1.2 Creating a form-associated custom element

This section is non-normative.

Adding a static formAssociated property, with a true value, makes an autonomous custom element a form-associated custom element. The ElementInternals interface helps you to implement functions and properties common to form control elements.

class MyCheckbox extends HTMLElement {
  static get formAssociated() { return true; }
  static get observedAttributes() { return ['checked']; }

  constructor() {
    super();
    this._internals = this.attachInternals();
    this.addEventListener('click', this._onClick.bind(this));
  }

  get form() { return this._internals.form; }
  get name() { return this.getAttribute('name'); }
  get type() { return this.localName; }

  get checked() { return this.getAttribute('checked'); }
  set checked(flag) { this.toggleAttribute('checked', Boolean(flag)); }

  attributeChangedCallback(name, oldValue, newValue) {
    // name will always be "checked" due to observedAttributes
    this._internals.setFormValue(this.checked ? 'on' : null);
  }

  _onClick(event) {
    this.checked = !this.checked;
  }
}
customElements.define('my-checkbox', MyCheckbox);

You can use the custom element my-checkbox like a built-in form-associated element. For example, putting it in form or label associates the my-checkbox element with them, and submitting the form will send data provided by my-checkbox implementation.

<form action="..." method="...">
  <label><my-checkbox name="agreed"></my-checkbox> I read the agreement.</label>
  <input type="submit">
</form>
4.13.1.3 Creating a custom element with default accessible roles, states, and properties

This section is non-normative.

By using the appropriate properties of ElementInternals, your custom element can have default accessibility semantics. The following code expands our form-associated checkbox from the previous section to properly set its default role and checkedness, as viewed by accessibility technology:

class MyCheckbox extends HTMLElement {
  static get formAssociated() { return true; }
  static get observedAttributes() { return ['checked']; }

  constructor() {
    super();
    this._internals = this.attachInternals();
    this.addEventListener('click', this._onClick.bind(this));

    this._internals.role = 'checkbox';
    this._internals.ariaChecked = false;
  }

  get form() { return this._internals.form; }
  get name() { return this.getAttribute('name'); }
  get type() { return this.localName; }

  get checked() { return this.getAttribute('checked'); }
  set checked(flag) { this.toggleAttribute('checked', Boolean(flag)); }

  attributeChangedCallback(name, oldValue, newValue) {
    // name will always be "checked" due to observedAttributes
    this._internals.setFormValue(this.checked ? 'on' : null);
    this._internals.ariaChecked = this.checked;
  }

  _onClick(event) {
    this.checked = !this.checked;
  }
}
customElements.define('my-checkbox', MyCheckbox);

Note that, like for built-in elements, these are only defaults, and can be overridden by the page author using the role and aria-* attributes:

<!-- This markup is non-conforming -->
<input type="checkbox" checked role="button" aria-checked="false">
<!-- This markup is probably not what the custom element author intended -->
<my-checkbox role="button" checked aria-checked="false">

Custom element authors are encouraged to state what aspects of their accessibility semantics are strong native semantics, i.e., should not be overriden by users of the custom element. In our example, the author of the my-checkbox element would state that its role and aria-checked values are strong native semantics, thus discouraging code such as the above.

4.13.1.4 创建定制的内建元素

This section is non-normative.

定制的内建元素 是一种独特的 custom element,它的定义稍有不同,但使用方式与 自主的 custom elements 很不一样。 它们的存在是为了允许通过扩展新的定制功能来复用现存 HTML 元素的行为。 因为如果只使用 自主的 custom elements 很多 HTML 元素的现存行为可能需要重复实现, 但使用 定制的内建元素 允许给既有的元素 安装自定义的构造行为、生命周期钩子、以及原型链。 本质上就是在已经有的元素上 "混入" 这些定制的功能。

定制的内建元素 要求一种与 自主的 custom elements 不同的语法,因为用户代理和其他软件会提取元素的 局部名 来识别元素的语义和行为。 就是说建立在既有行为基础上的 定制的内建元素 的概念 严重依赖于被扩展的元素保持他们原有的 局部名。

在这个例子中,我们将会创建一个名为 plastic-button定制的内建元素。它像一个普通按钮一样,但是当点击时有漂亮的动画效果。 就像以前一样,我们从定义一个类开始,虽然这次我们扩展的是 HTMLButtonElement 而不是 HTMLElement

class PlasticButton extends HTMLButtonElement {
  constructor() {
    super();

    this.addEventListener("click", () => {
      // Draw some fancy animation effects!
    });
  }
}

在定义我们的 custom element 时,我们必须同时声明 extends 选项:

customElements.define("plastic-button", PlasticButton, { extends: "button" });

通常被扩展元素的名字不能简单地通过看它扩展了什么元素接口来确定, 因为很多元素共用同样的接口(比如 qblockquote 共用 HTMLQuoteElement)。

为了使用我们的 定制内建元素, 我们使用 button 元素上的 is 属性:

<button is="plastic-button">Click Me!</button>

尝试将 定制的内建元素 当做 自主 custom element 使用 不会 奏效; 也就是说 <plastic-button>Click me?</plastic-button> 只会创建一个没有特殊行为的 HTMLElement

如果你需要编程方式创建一个类型扩展的元素,可以使用下面的形式 createElement()

const plasticButton = document.createElement("button", { is: "plastic-button" });
plasticButton.textContent = "Click me!";

像以前一样,构造器也好使:

const plasticButton2 = new PlasticButton();
console.log(plasticButton2.localName);          // 将会输出 "button"
console.log(plasticButton2.getAttribute("is")); // 将会输出 "plastic-button"

值得一提的是,所有 button 的特殊行为也适用于该 "plastic buttons": 获得焦点行为、参与 表单提交 的能力、 disabled 属性,等等。

定制的内建元素 设计为允许扩展既有 HTML 元素,尤其是那些用户代理提供了 有用行为或者 API 的元素。它们只能扩展在本标准中定义的现存 HTML 元素,不可继承遗留元素, 比如 bgsoundblinkisindexkeygenmulticolnextid, 或者 使用 HTMLUnknownElement 作为它们的 元素接口 来定义的 spacer

这一要求的一个原因是向后兼容性:如果定义了一个 定制内建元素,扩展了 一个目前未知的元素,比如 combobox,这将会阻止本标准在将来定义一个 combobox 元素,因为派生过 定制内建元素 的客户可能依赖于它们的基元素 没有那些有趣的用户代理提供的行为。

此外, applet 元素不可被扩展,因为它们正在被 Web 平台移除的过程中。

4.13.1.5 自主 custom element 的缺点

This section is non-normative.

正如下文规定,以及上文提到的,简单地定义和使用一个称为 taco-button 不意味着这个元素代表 represent 按钮。也就是说像 Web 浏览器、搜索引擎、 或可访问性技术这些工具将不会自动仅仅基于它定义的名字,就把它当做一个按钮。

为了向不同的用户表达期望的按钮语义,在使用 自主 custom element 的时候, 就有必要应用下面这些技术了:

考虑到这些点,一个全特性的 taco-button 想要负责表达按钮的语义 (包括被禁用的能力),看起来可能是这样的:

class TacoButton extends HTMLElement {
  static get observedAttributes() { return ["disabled"]; }

  constructor() {
    super();

    this.addEventListener("keydown", e => {
      if (e.keyCode === 32 || e.keyCode === 13) {
        this.dispatchEvent(new MouseEvent("click", {
          bubbles: true,
          cancelable: true
        }));
      }
    });

    this.addEventListener("click", e => {
      if (this.disabled) {
        e.preventDefault();
        e.stopPropagation();
      }
    });

    this._observer = new MutationObserver(() => {
      this.setAttribute("aria-label", this.textContent);
    });
  }

  connectedCallback() {
    this.setAttribute("role", "button");
    this.setAttribute("tabindex", "0");

    this._observer.observe(this, {
      childList: true,
      characterData: true,
      subtree: true
    });
  }

  disconnectedCallback() {
    this._observer.disconnect();
  }

  get disabled() {
    return this.hasAttribute("disabled");
  }

  set disabled(v) {
    if (v) {
      this.setAttribute("disabled", "");
    } else {
      this.removeAttribute("disabled");
    }
  }

  attributeChangedCallback() {
    // only is called for the disabled attribute due to observedAttributes
    if (this.disabled) {
      this.removeAttribute("tabindex");
      this.setAttribute("aria-disabled", "true");
    } else {
      this.setAttribute("tabindex", "0");
      this.setAttribute("aria-disabled", "false");
    }
  }
}

即使有这样复杂的元素定义,该元素对用户来讲并不好用:它不断地根据自己的意愿添加 tabindexaria-* 属性。 这是因为现在还没有办法设置 Custom Element 的默认的可访问性语义或者获得焦点行为。 只能强制使用这些属性来完成这一工作(即使它们通常是保留的,只供用户来重写默认行为)。

相比而言,一个简单的 定制内建元素, 如上一节所述,将会自动继承 button 的语义和行为,不需手动实现这些行为。 通常对于任何有着建立在既有 HTML 元素之上的明显语义和行为的元素, 定制内建元素 更容易开发、维护,以及使用。

4.13.1.6 在创建之后升级元素

This section is non-normative.

因为 元素定义 任何时候都可以发生, 可能会先 创建 一个非 custom element, 在适当的 定义 注册之后, 才变成一个 custom element。 我们称这一过程为 "升级" 元素:从一个普通元素编程一个 Custom Element。

升级 使得 custom element 定义 可以在 相关元素初(比如被解析器)始创建之后再行注册。这允许渐进增强 Custom Element 的内容。 例如在下列 HTML 文档中,img-viewer 的元素定义是异步载入的:

<!DOCTYPE html>
<html lang="en">
<title>Image viewer example</title>

<img-viewer filter="Kelvin">
  <img src="images/tree.jpg" alt="A beautiful tree towering over an empty savannah">
</img-viewer>

<script src="js/elements/img-viewer.js" async></script>

img-viewer 元素的定义是被一个标记了 async 属性的 script 元素加载的。 在标记代码中该脚本放置在 <img-viewer> 标签之后。 当脚本正在载入时,img-viewer 元素将会被当做未定义元素, 类似 span。一旦脚本载入,它将会定义 img-viewer 元素, 并且页面中既有的 img-viewer 元素将会被升级, 应用 Custom Element 的定义(大概包括根据 "Kelvin" 字符串应用图像光栅,增强图像的视觉效果)。


注意 升级 只会应用于文档树中的元素。 (形式化地说是 已连接的 元素)。没有插入到文档中的元素将会保持未升级的状态。下面的例子说明了这一点:

<!DOCTYPE html>
<html lang="en">
<title>Upgrade edge-cases example</title>

<example-element></example-element>

<script>
  "use strict";

  const inDocument = document.querySelector("example-element");
  const outOfDocument = document.createElement("example-element");

  // Before the element definition, both are HTMLElement:
  console.assert(inDocument instanceof HTMLElement);
  console.assert(outOfDocument instanceof HTMLElement);

  class ExampleElement extends HTMLElement {}
  customElements.define("example-element", ExampleElement);

  // After element definition, the in-document element was upgraded:
  console.assert(inDocument instanceof ExampleElement);
  console.assert(!(outOfDocument instanceof ExampleElement));

  document.body.appendChild(outOfDocument);

  // Now that we've moved the element into the document, it too was upgraded:
  console.assert(outOfDocument instanceof ExampleElement);
</script>

4.13.2 Requirements for custom element constructors and reactions

When authoring custom element constructors, authors are bound by the following conformance requirements:

Several of these requirements are checked during element creation, either directly or indirectly, and failing to follow them will result in a custom element that cannot be instantiated by the parser or DOM APIs. This is true even if the work is done inside a constructor-initiated microtask, as a microtask checkpoint can occur immediately after construction.

When authoring custom element reactions, authors should avoid manipulating the node tree as this can lead to unexpected results.

An element's connectedCallback can be queued before the element is disconnected, but as the callback queue is still processed, it results in a connectedCallback for an element that is no longer connected:

class CParent extends HTMLElement {
  connectedCallback() {
    this.firstChild.remove();
  }
}
customElements.define("c-parent", CParent);

class CChild extends HTMLElement {
  connectedCallback() {
    console.log("CChild connectedCallback: isConnected =", this.isConnected);
  }
}
customElements.define("c-child", CChild);

const parent = new CParent(),
      child = new CChild();
parent.append(child);
document.body.append(parent);

// Logs:
// CChild connectedCallback: isConnected = false

4.13.3 核心概念

custom element自定义的 元素。 非形式化地,这意味着它的构造器和原型链由作者而不是用户代理定义。 作者提供的构造函数称为 custom element 构造器

可以定义两种不同的 custom elements

Global_attributes/is

Firefox63+SafariNoChrome67+
Opera54+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOSNoChrome Android67+WebView Android67+Samsung Internet9.0+Opera Android48+
  1. 自主的 custom element 定义时不包含 extends 选项。这类 custom elements 的 局部名 等于它们 定义的名称

  2. 定制内建元素 定义时包含 extends 选项。这类 custom elements 的 局部名 等于它们 在 extends 选项中传入的值,它们的 定义的名称 被用于 is 属性的值,因此它必须是一个 合法的 custom element 名

custom element创建 后, 更改 is 属性的值不会更改该元素的行为,因为它只是 保存为该元素的 is 的值

自主的 custom elements 有下列的元素定义:

类别
流式内容
短语内容
可感知内容
表单相关的 custom element在列表中的, 可加标签的, 可提交的可重置的 表单相关元素
该元素可使用的上下文
应该出现 短语内容 的地方。
内容模型
透明的
内容属性
is 之外的 全局属性
表单相关元素form — Associates the element with a form element
表单相关元素disabled — Whether the form control is disabled
表单相关元素readonly — Affects willValidate, plus any behavior added by the custom element author
表单相关元素name — Name of the element to use for form submission and in the form.elements API
任何其他没有命名空间的属性。
可访问性相关
表单相关的 custom element使用方版本实现方版本
其他的:使用方版本实现方版本
DOM 接口
由元素作者提供(继承自 HTMLElement

自主的 custom element 没有任何特殊含义:它 表示 它的子节点。 定制内建元素 继承了它扩展的元素的语义。

任何没有命名空间的并与元素功能相关的属性,都可以按照元素作者的决定添加到 自主的 custom element 上, 只要该属性名是 XML 兼容的 其不含 ASCII 大写字母is 属性较为特殊, 它不能声明在 自主的 custom element 上(如果设置的话不会有任何效果)。

定制内建元素 遵循普通的属性名要求 (基于它们扩展的元素)。新增自定义的基于属性的行为,可使用 data-* 属性。


一个 自主的 custom element,如果与一个 form-associated 字段为 true 的 Custom Element 定义 相关联, 就称为 表单相关的 custom element

name 属性表示 表单相关的 custom element 的名字。 disabled 属性用来让 表单相关的 custom element 不可交互并阻止它的 提交数据 被提交。 form 属性用来明确地把 表单相关的 custom element 和它的 表单 owner 相关联。

readonly 属性指定该元素 禁止约束验证。用户代理不会给这个属性提供任何其他行为, 但 custom element 作者应该利用它是否存在来以某种方式让控件变得不可编辑,类似内置控件的 readonly 属性那样。

强校验:如果 表单相关的 custom element 的指定了 readonly 属性,该元素就 禁止了约束验证

表单相关的 custom element重置算法 是用这个元素 入队一个 Custom Element 反应,回调名为 "formResetCallback",参数列表为空。


合法的 custom element 名 是满足以下要求的一串字符 name

上述要求保证了 合法 custom element 名 的这些目标:

除这些限制之外,允许了大量的名字来给像 <math-α><emotion-😍> 这样的用例最大的自由。

Custom Element 定义 描述了一个 custom element 的组成:

name
一个 合法的 Custom Element 名称
局部名
一个 局部名
constructor
一个Web IDL Function 回调函数类型的值,包装了 custom element 构造器
被观察的属性列表
一个 sequence<DOMString>
生命周期回调列表
一个映射,其键是字符串 "connectedCallback", "disconnectedCallback", "adoptedCallback", "attributeChangedCallback", "formAssociatedCallback", "formDisabledCallback", "formResetCallback" 和 "formStateRestoreCallback"。 相应的值是 Web IDL Function 回调函数类型的值,或者 null。默认每一项的值都是null。
一个construction stack
一个初始为空的列表,由 元素升级 算法和 和 HTML 元素构造器 操作。列表中每一项都将是一个元素或者一个 已经构造的 标记
表单相关 布尔
如果为真,用户代理会把和这个 custom element 定义 关联的元素当作 表单相关的 custom elements 处理。
disable 内部 布尔
控制 attachInternals()
禁用 shadow 布尔
控制 attachShadow()

给定一个 documentnamespacelocalName,以及 is查找一个 custom element 的定义 应执行下列步骤( 返回一个 custom element 定义 或 null):

  1. 如果 namespace 不是 HTML 命名空间,返回 null。

  2. 如果 document浏览环境 是 null,返回 null。

  3. registrydocument相关全局对象CustomElementRegistry 对象。

  4. 如果在 registry 中有一个 custom element 定义name局部名 都等于 localName,返回该 custom element 定义

  5. 如果在 registry 中有一个 custom element 定义name 等于 is局部名 等于 localName,返回该 custom element 定义

  6. 返回 null。

4.13.4 CustomElementRegistry 接口

CustomElementRegistry

Support in all current engines.

Firefox63+Safari10.1+Chrome54+
Opera41+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10.3+Chrome Android54+WebView Android54+Samsung Internet6.0+Opera Android41+

每个 Window 对象都关联是一个唯一的 CustomElementRegistry 对象实例,当 Window 对象创建时分配。

Custom element registries 与 Window 对象而不是 Document 对象关联,因为每个 custom element 构造函数 继承自 HTMLElement 接口,而每个 Window 对象只有一个 HTMLElement 接口。

Window/customElements

Support in all current engines.

Firefox63+Safari10.1+Chrome54+
Opera41+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10.3+Chrome Android54+WebView Android54+Samsung Internet6.0+Opera Android41+

Window 接口的 customElements 属性必须返回该 Window 对象的 CustomElementRegistry 对象。

interface CustomElementRegistry {
  [CEReactions] undefined define(DOMString name, CustomElementConstructor constructor, optional ElementDefinitionOptions options = {});
  (CustomElementConstructor or undefined) get(DOMString name);
  Promise<CustomElementConstructor> whenDefined(DOMString name);
  [CEReactions] undefined upgrade(Node root);
};

callback CustomElementConstructor = HTMLElement ();

dictionary ElementDefinitionOptions {
  DOMString extends;
};

每个 CustomElementRegistry 有一个 custom element 定义 的集合,初始为空。通常本标准中的算法在 registry 中通过 name局部名, 或 constructor 中的任意一个进行查找。

每个 CustomElementRegistry 还有一个 element 定义正在运行 标记, 用来防止 元素定义 被再次调用。 初始未设置。

每个 CustomElementRegistry 还有一个 when-defined Promise 映射, 将 合法的 custom element 名 映射为 Promise。 用来实现 whenDefined() 方法。

window . customElements . define(nameconstructor)

CustomElementRegistry/define

Support in all current engines.

Firefox63+Safari10.1+Chrome67+
Opera54+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10.3+Chrome Android67+WebView Android67+Samsung Internet9.0+Opera Android48+
定义一个新的 custom element,作为 自主的 custom element,并将指定的名称映射到指定的构造函数。
window . customElements . define(nameconstructor, { extends: baseLocalName })
定义一个新的 custom element,作为 定制内建元素,其 元素类型baseLocalName 标识的。 同时将给定的 name 映射到给定的 constructor。当尝试扩展 custom element 或未知元素时, 将会抛出 "NotSupportedError" DOMException
window . customElements . get(name)

CustomElementRegistry/get

Support in all current engines.

Firefox63+Safari10.1+Chrome67+
Opera54+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10.3+Chrome Android67+WebView Android67+Samsung Internet9.0+Opera Android48+
获取定义为 namecustom element 构造函数 。如果没有 custom element 定义 拥有给定的 name 则返回 undefined。
window . customElements . whenDefined(name)

CustomElementRegistry/whenDefined

Support in all current engines.

Firefox63+Safari10.1+Chrome67+
Opera54+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10.3+Chrome Android67+WebView Android67+Samsung Internet9.0+Opera Android48+
返回一个 promise,定义给定 name 的 custom element 时完成,值为 custom element 的构造函数。 (如果这样的 custom element 已经定义,返回的 promise 将会立即完成。) 如果没有给定 合法的 Custom Element 名称 则返回一个已经以 "SyntaxError" DOMException 拒绝的 Promise。

元素定义 是向 CustomElementRegistry 新增一个 custom element 定义 的过程。 由 define() 方法完成。 define(nameconstructoroptions) 方法被调用时必须运行下列步骤:

  1. 如果 IsConstructor(constructor) 为 false,抛出一个 TypeError 并中止这些步骤。

  2. 如果 name 不是一个 合法的 custom element 名,则抛出一个 "SyntaxError" DOMException 并中止这些步骤。

  3. 如果该 CustomElementRegistry 包含 name 值为 name 的项目, 则抛出一个 "NotSupportedError" DOMException 并中止这些步骤。

  4. 如果该 CustomElementRegistry 包含 constructor 值为 constructor 的项目, 则抛出一个 "NotSupportedError" DOMException 并中止这些步骤。

  5. localNamename

  6. extendsoptionsextends 成员(没有该成员则为 null)。

  7. 如果 extends 不为 null,则:

    1. 如果 extends 是一个 合法的 custom element 名,则抛出 "NotSupportedError" DOMException

    2. 如果 extends元素接口HTML 命名空间HTMLUnknownElement (例如,如果 extends 表示的元素定义不在本标准中),则抛出 "NotSupportedError" DOMException

    3. 设置 localNameextends

  8. 如果该 CustomElementRegistry元素定义正在运行 标记被设置,则抛出一个 "NotSupportedError" DOMException 并中止这些步骤。

  9. 设置该 CustomElementRegistry元素定义正在运行 标记。

  10. formAssociated 为 false。

  11. disableInternals 为 false。

  12. disableShadow 为 false。

  13. observedAttributes 为空 sequence<DOMString>

  14. 运行下列子步骤并捕获所有异常:

    1. prototypeGet(constructor, "prototype")。重新抛出任何异常。

    2. 如果 Type(prototype) 不是 Object,则抛出 TypeError 异常。

    3. lifecycleCallbacks 为生命周期回调映射,并拥有键 "connectedCallback", "disconnectedCallback", "adoptedCallback", 和 "attributeChangedCallback", 每一项对应的值均为 null。

    4. lifecycleCallbacks 键中的每一项 callbackName,按照上一步列出的顺序:

      1. callbackValueGet(prototypecallbackName)。重新抛出任何异常。

      2. 如果 callbackValue 不是 undefined,则设置 lifecycleCallbacks 中键为 callbackName 的项目的值为 callbackValue 转换 为 Web IDL Function 回调类型的结果。重新抛出任何转换过程中的异常。

    5. 如果 lifecycleCallbacks 中键为 "attributeChangedCallback" 的项目的值不是 null,则:

      1. observedAttributesIterableGet(constructor, "observedAttributes")。 重新抛出任何异常。

      2. 如果 observedAttributesIterable 不是 undefined,则设置 observedAttributesobservedAttributesIterable 转换sequence<DOMString> 的结果。重新抛出任何转换过程中的异常。

    6. disabledFeatures 为空 sequence<DOMString>

    7. disabledFeaturesIterableGet(constructor, "disabledFeatures")。 重新抛出任何异常。

    8. 如果 disabledFeaturesIterable 不是 undefined,设置 disabledFeaturesdisabledFeaturesIterable 转换为 sequence<DOMString> 的结果。 重新抛出转换中的任何异常。

    9. 如果 disabledFeatures 包含 "internals", 设置 disableInternals 为 true。

    10. 如果 disabledFeatures 包含 "shadow", 设置 disableShadow 为 true。

    11. formAssociatedValueGet( constructor, "formAssociated")。重新抛出任何异常。

    12. 设置 formAssociatedformAssociatedValue 转换为 boolean 的结果。 重新抛出转换中的任何异常。

    13. 如果 formAssociated 为 true,对每个 "formAssociatedCallback", "formResetCallback", "formDisabledCallback" 和 "formStateRestoreCallback" callbackName

      1. callbackValueGet(prototype, callbackName)。重新抛出任何异常。

      2. 如果 callbackValue 不是 undefined,设置 lifecycleCallbacks 中键 callbackName 对应的值为 callbackValue 转换 为 Web IDL Function 回调类型的结果。重新抛出转换中的任何异常。

    然后执行下列的子步骤,不论上述步骤是否抛出异常:

    1. 重置 CustomElementRegistry元素定义正在运行 标记。

    最终,如果第一批子步骤抛出了异常,则重新抛出该异常并终止算法。否则继续。

  15. definition 为一个新的 custom element 定义, 其 namename, 其 局部名localName, 其 constructorconstructor, 其 observed attributesobservedAttributes, 其 lifecycle callbackslifecycleCallbacks, 其 form-associatedformAssociated, 其 disable internalsdisableInternals, 其 disable shadowdisableShadow

  16. 添加 definition 到该该 CustomElementRegistry

  17. document 为该 CustomElementRegistry相关全局对象关联的 Document

  18. upgrade candidatesdocument 的所有 shadow-including 后代 中, 命名空间为 HTML 命名空间 且 局部名 为 localName 的元素, 以 shadow-including 树序。 此外如果 extends 不是 null,则只包括 is 的值 等于 name 的元素。

  19. upgrade candidates 中的每一个元素 element将一个 Custom Element 升级响应加入队列,并指定 elementdefinition

  20. 如果该 CustomElementRegistrywhen-defined Promise 映射 包含键为 name 的项目:

    1. promise 为该项目的值。

    2. constructor 完成 promise

    3. 从该 CustomElementRegistrywhen-defined promise 映射 中删除键为 name 的项目。

get(name) 方法被调用时必须执行这些步骤:

  1. 如果该 CustomElementRegistry 包含 namename 条目,则返回该条目的 构造函数

  2. 否则返回 undefined。

whenDefined(name) 方法被调用时必须执行这些步骤:

  1. 如果 name 不是一个 合法的 custom element 名称,则返回一个新的 promise,以 "SyntaxError" DOMException 拒绝它并中止这些步骤。

  2. 如果该 CustomElementRegistry 包含一个 namename 的条目,则返回一个 Promise,其值为 那个条目的 构造函数

  3. map 为该 CustomElementRegistrywhen-defined promise 映射

  4. 如果 map 不包含键为 name 的条目,在 map 中创建一个条目, 其键为 name,值为一个新的 promise。

  5. promisemap 中键为 name 的条目的值。

  6. 返回 promise

whenDefined() 方法可以用来避免 在合适的 custom elements 被定义 之前执行操作。 这个例子中我们将它与 :defined 伪类结合, 来隐藏一个动态载入的文章内容,直到我们确定它使用的所有 自主 Custom Element 已经定义。

articleContainer.hidden = true;

fetch(articleURL)
  .then(response => response.text())
  .then(text => {
    articleContainer.innerHTML = text;

    return Promise.all(
      [...articleContainer.querySelectorAll(":not(:defined)")]
        .map(el => customElements.whenDefined(el.localName))
    );
  })
  .then(() => {
    articleContainer.hidden = false;
  });

调用 upgrade(root) 方法时必须执行以下步骤:

  1. candidatesroot包括 shadow 的后代 所有元素的 列表, 按照 包括 shadow 的树排序

  2. 对每一个 candidates 中的 candidate尝试升级 candidate

upgrade() 方法允许按需升级元素。 正常情况下,元素会在 连接到 DOM 时自动升级, 但也可以在已经准备好连接到 DOM 时调用这个方法。

const el = document.createElement("spider-man");

class SpiderMan extends HTMLElement {}
customElements.define("spider-man", SpiderMan);

console.assert(!(el instanceof SpiderMan)); // not yet upgraded

customElements.upgrade(el);
console.assert(el instanceof SpiderMan);    // upgraded!

4.13.5 升级

给定输入 custom element 定义 definition 和一个元素 element升级元素 应运行以下步骤:

  1. 如果 element自定义的,中止这些步骤。

    这一情况在再次进入该算法时就会发生,比如下面的例子:

    <!DOCTYPE html>
    <x-foo id="a"></x-foo>
    <x-foo id="b"></x-foo>
    
    <script>
    // Defining enqueues upgrade reactions for both "a" and "b"
    customElements.define("x-foo", class extends HTMLElement {
      constructor() {
        super();
    
        const b = document.querySelector("#b");
        b.remove();
    
        // While this constructor is running for "a", "b" is still
        // undefined, and so inserting it into the document will enqueue a
        // second upgrade reaction for "b" in addition to the one enqueued
        // by defining x-foo.
        document.body.appendChild(b);
      }
    })
    </script>

    这一步会使得第二次以 "b" 为参数调用 升级元素 算法时直接早退出。

  2. 如果 elementcustom element 状态failed",则中止这些步骤。

  3. element属性列表 中每一个 attribute, 按顺序 入队一个 Custom Element 反应 (元素为 element,回调名为 "attributeChangedCallback"), 参数列表为 attribute 的 局部名,null,attribute的值,以及 attribute 的命名空间。

  4. 如果 element 已连接入队一个 Custom Element 反应 (元素为 element,回调名为 "attributeChangedCallback"),参数列表为空。

  5. element 添加到 definition构造栈 尾部。

  6. Cdefinition构造器

  7. 运行以下子步骤的同时捕获任何异常:

    1. constructResult 为无参数 构造 C 的结果。

      如果 C 不合规范地 使用了以 [CEReactions] 扩展属性修饰的 API, 那么就在这一步中,在 C 结束前执行本算法开始时入队的回调,此后将控制返回给本算法。 否则,在 C 和其他升级过程结束后再执行它们。

    2. 如果 SameValue(constructResultelement) 为 false, 那么抛出一个 "InvalidStateError" DOMException

      如果 C 在调用 super() 之前构造了同一个 Custom Element 的另一个实例, 或者 C 使用了 JavaScript 的 return重写特性并在构造函数中返回一个任意的对象时, 就会发生这种情况。

    然后执行下列子步骤,无论上述步骤是否抛出了异常:

    1. definition构造栈 尾部移除最后一个入口。

      假设 C 调用了 super() (如果它 符合规范 就会这样做),并且该调用是成功的,此时 this 就是 已构造 标记,替换了本算法最开始推入的 element。 (就是 HTML 元素构造器 执行了这个替换。)

      如果 C 没有调用 super() (即它不 符合规范),或者在 HTML 元素构造 中的任何一步抛出了异常,那么这个入口仍然是 element

    最后,如果上述步骤抛出了异常:

    1. 设置 elementcustom element 状态 为 "failed"。

    2. 清空 elementcustom element 反应队列

    3. 重新抛出该异常,终止本算法。

  8. 设置 elementcustom element 状态 为 "custom"。

  9. 设置 elementcustom element 定义definition

给定输入元素 element尝试升级元素, 应执行下列步骤:

  1. definition 为给定 element节点文档element的命名空间, element的 局部名,以及 elementis查找 custom element 定义 的结果。

  2. 如果 definition 不是 null,那么 入队一个 Custom Element 升级反应, 其元素为 element,定义为 definition

4.13.6 Custom element reactions

A custom element possesses the ability to respond to certain occurrences by running author code:

We call these reactions collectively custom element reactions.

The way in which custom element reactions are invoked is done with special care, to avoid running author code during the middle of delicate operations. Effectively, they are delayed until "just before returning to user script". This means that for most purposes they appear to execute synchronously, but in the case of complicated composite operations (like cloning, or range manipulation), they will instead be delayed until after all the relevant user agent processing steps have completed, and then run together as a batch.

Additionally, the precise ordering of these reactions is managed via a somewhat-complicated stack-of-queues system, described below. The intention behind this system is to guarantee that custom element reactions always are invoked in the same order as their triggering actions, at least within the local context of a single custom element. (Because custom element reaction code can perform its own mutations, it is not possible to give a global ordering guarantee across multiple elements.)


Each similar-origin window agent has a custom element reactions stack, which is initially empty. A similar-origin window agent's current element queue is the element queue at the top of its custom element reactions stack. Each item in the stack is an element queue, which is initially empty as well. Each item in an element queue is an element. (The elements are not necessarily custom yet, since this queue is used for upgrades as well.)

Each custom element reactions stack has an associated backup element queue, which an initially-empty element queue. Elements are pushed onto the backup element queue during operations that affect the DOM without going through an API decorated with [CEReactions], or through the parser's create an element for the token algorithm. An example of this is a user-initiated editing operation which modifies the descendants or attributes of an editable element. To prevent reentrancy when processing the backup element queue, each custom element reactions stack also has a processing the backup element queue flag, initially unset.

All elements have an associated custom element reaction queue, initially empty. Each item in the custom element reaction queue is of one of two types:

This is all summarized in the following schematic diagram:

A custom element reactions stack consists of a stack of element queues. Zooming in on a particular queue, we see that it contains a number of elements (in our example, <x-a>, then <x-b>, then <x-c>). Any particular element in the queue then has a custom element reaction queue. Zooming in on the custom element reaction queue, we see that it contains a variety of queued-up reactions (in our example, upgrade, then attribute changed, then another attribute changed, then connected).

To enqueue an element on the appropriate element queue, given an element element, run the following steps:

  1. Let reactionsStack be element's relevant agent's custom element reactions stack.

  2. If reactionsStack is empty, then:

    1. Add element to reactionsStack's backup element queue.

    2. If reactionsStack's processing the backup element queue flag is set, then return.

    3. Set reactionsStack's processing the backup element queue flag.

    4. Queue a microtask to perform the following steps:

      1. Invoke custom element reactions in reactionsStack's backup element queue.

      2. Unset reactionsStack's processing the backup element queue flag.

  3. Otherwise, add element to element's relevant agent's current element queue.

To enqueue a custom element callback reaction, given a custom element element, a callback name callbackName, and a list of arguments args, run the following steps:

  1. Let definition be element's custom element definition.

  2. Let callback be the value of the entry in definition's lifecycle callbacks with key callbackName.

  3. If callback is null, then return

  4. If callbackName is "attributeChangedCallback", then:

    1. Let attributeName be the first element of args.

    2. If definition's observed attributes does not contain attributeName, then return.

  5. Add a new callback reaction to element's custom element reaction queue, with callback function callback and arguments args.

  6. Enqueue an element on the appropriate element queue given element.

To enqueue a custom element upgrade reaction, given an element element and custom element definition definition, run the following steps:

  1. Add a new upgrade reaction to element's custom element reaction queue, with custom element definition definition.

  2. Enqueue an element on the appropriate element queue given element.

To invoke custom element reactions in an element queue queue, run the following steps:

  1. For each custom element element in queue:

    1. Let reactions be element's custom element reaction queue.

    2. Repeat until reactions is empty:

      1. Remove the first element of reactions, and let reaction be that element. Switch on reaction's type:

        upgrade reaction
        Upgrade element using reaction's custom element definition.
        callback reaction
        Invoke reaction's callback function with reaction's arguments, and with element as the callback this value.

        If this throws an exception, catch it, and report the exception.


To ensure custom element reactions are triggered appropriately, we introduce the [CEReactions] IDL extended attribute. It indicates that the relevant algorithm is to be supplemented with additional steps in order to appropriately track and invoke custom element reactions.

The [CEReactions] extended attribute must take no arguments, and must not appear on anything other than an operation, attribute, setter, or deleter. Additionally, it must not appear on readonly attributes.

Operations, attributes, setters, or deleters annotated with the [CEReactions] extended attribute must run the following steps in place of the ones specified in their description:

  1. Push a new element queue onto this object's relevant agent's custom element reactions stack.

  2. Run the originally-specified steps for this construct, catching any exceptions. If the steps return a value, let value be the returned value. If they throw an exception, let exception be the thrown exception.

  3. Let queue be the result of popping from this object's relevant agent's custom element reactions stack.

  4. Invoke custom element reactions in queue.

  5. If an exception exception was thrown by the original steps, rethrow exception.

  6. If a value value was returned from the original steps, return value.

The intent behind this extended attribute is somewhat subtle. One way of accomplishing its goals would be to say that every operation, attribute, setter, and deleter on the platform must have these steps inserted, and to allow implementers to optimize away unnecessary cases (where no DOM mutation is possible that could cause custom element reactions to occur).

However, in practice this imprecision could lead to non-interoperable implementations of custom element reactions, as some implementations might forget to invoke these steps in some cases. Instead, we settled on the approach of explicitly annotating all relevant IDL constructs, as a way of ensuring interoperable behavior and helping implementations easily pinpoint all cases where these steps are necessary.

Any nonstandard APIs introduced by the user agent that could modify the DOM in such a way as to cause enqueuing a custom element callback reaction or enqueuing a custom element upgrade reaction, for example by modifying any attributes or child elements, must also be decorated with the [CEReactions] attribute.

As of the time of this writing, the following nonstandard or not-yet-standardized APIs are known to fall into this category:

4.13.7 Element internals

Certain capabilities are meant to be available to a custom element author, but not to a custom element consumer. These are provided by the element.attachInternals() method, which returns an instance of ElementInternals. The properties and methods of ElementInternals allow control over internal features which the user agent provides to all elements.

element . attachInternals()

Returns an ElementInternals object targeting the custom element element. Throws an exception if element is not a custom element, if the "internals" feature was disabled as part of the element definition, or if it is called twice on the same element.

Each HTMLElement has an attached internals boolean, initially false.

HTMLElement/attachInternals

Firefox93+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android93+Safari iOSNoChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

The attachInternals() method steps are:

  1. If this's is value is not null, then throw a "NotSupportedError" DOMException.

  2. Let definition be the result of looking up a custom element definition given this's node document, its namespace, its local name, and null as the is value.

  3. If definition is null, then throw an "NotSupportedError" DOMException.

  4. If definition's disable internals is true, then throw a "NotSupportedError" DOMException.

  5. If this's attached internals is true, then throw an "NotSupportedError" DOMException.

  6. If this's custom element state is not "precustomized" or "custom", then throw a "NotSupportedError" DOMException.

  7. Set this's attached internals to true.

  8. Return a new ElementInternals instance whose target element is this.

4.13.7.1 The ElementInternals interface

ElementInternals

Firefox93+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android93+Safari iOSNoChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

The IDL for the ElementInternals interface is as follows, with the various operations and attributes defined in the following sections:

[Exposed=Window]
interface ElementInternals {
  // Shadow root access
  readonly attribute ShadowRoot? shadowRoot;

  // Form-associated custom elements
  undefined setFormValue((File or USVString or FormData)? value,
                         optional (File or USVString or FormData)? state);

  readonly attribute HTMLFormElement? form;

  undefined setValidity(optional ValidityStateFlags flags = {},
                        optional DOMString message,
                        optional HTMLElement anchor);
  readonly attribute boolean willValidate;
  readonly attribute ValidityState validity;
  readonly attribute DOMString validationMessage;
  boolean checkValidity();
  boolean reportValidity();

  readonly attribute NodeList labels;
};

// Accessibility semantics
ElementInternals includes ARIAMixin;

dictionary ValidityStateFlags {
  boolean valueMissing = false;
  boolean typeMismatch = false;
  boolean patternMismatch = false;
  boolean tooLong = false;
  boolean tooShort = false;
  boolean rangeUnderflow = false;
  boolean rangeOverflow = false;
  boolean stepMismatch = false;
  boolean badInput = false;
  boolean customError = false;
};

Each ElementInternals has a target element, which is a custom element.

4.13.7.2 Shadow root access
internals . shadowRoot

Returns the ShadowRoot for internals's target element, if the target element is a shadow host, or null otherwise.

ElementInternals/shadowRoot

Firefox93+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android93+Safari iOSNoChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

The shadowRoot getter steps are:

  1. Let target be this's target element.

  2. If target is not a shadow host, then return null.

  3. Let shadow be target's shadow root.

  4. If shadow's available to element internals is false, then return null.

  5. Return shadow.

4.13.7.3 Form-associated custom elements
internals . setFormValue(value)

Sets both the state and submission value of internals's target element to value.

If value is null, the element won't participate in form submission.

internals . setFormValue(value, state)

Sets the submission value of internals's target element to value, and its state to state.

If value is null, the element won't participate in form submission.

internals . form

Returns the form owner of internals's target element.

internals . setValidity(flags, message [, anchor ])

Marks internals's target element as suffering from the constraints indicated by the flags argument, and sets the element's validation message to message. If anchor is specified, the user agent might use it to indicate problems with the constraints of internals's target element when the form owner is validated interactively or reportValidity() is called.

internals . setValidity({})

Marks internals's target element as satisfying its constraints.

internals . willValidate

Returns true if internals's target element will be validated when the form is submitted; false otherwise.

internals . validity

Returns the ValidityState object for internals's target element.

internals . validationMessage

Returns the error message that would be shown to the user if internals's target element was to be checked for validity.

valid = internals . checkValidity()

Returns true if internals's target element has no validity problems; false otherwise. Fires an invalid event at the element in the latter case.

valid = internals . reportValidity()

Returns true if internals's target element has no validity problems; otherwise, returns false, fires an invalid event at the element, and (if the event isn't canceled) reports the problem to the user.

internals . labels

Returns a NodeList of all the label elements that internals's target element is associated with.

Each form-associated custom element has submission value. It is used to provide one or more entries on form submission. The initial value of submission value is null, and submission value can be null, a string, a File, or a list of entries.

Each form-associated custom element has state. It is information with which the user agent can restore a user's input for the element. The initial value of state is null, and state can be null, a string, a File, or a list of entries.

The setFormValue() method is used by the custom element author to set the element's submission value and state, thus communicating these to the user agent.

When the user agent believes it is a good idea to restore a form-associated custom element's state, for example after navigation or restarting the user agent, they may enqueue a custom element callback reaction with that element, callback name "formStateRestoreCallback", and an argument list containing the state to be restored, and "restore".

If the user agent has a form-filling assist feature, then when the feature is invoked, it may enqueue a custom element callback reaction with a form-associated custom element, callback name "formStateRestoreCallback", and an argument list containing the state value determined by history of state value and some heuristics, and "autocomplete".

In general, the state is information specified by a user, and the submission value is a value after canonicalization or sanitization, suitable for submission to the server. The following examples makes this concrete:

Suppose that we have a form-associated custom element which asks a user to specify a date. The user specifies "3/15/2019", but the control wishes to submit "2019-03-15" to the server. "3/15/2019" would be a state of the element, and "2019-03-15" would be a submission value.

Suppose you develop a custom element emulating a the behavior of the existing checkbox input type. Its submission value would be the value of its value content attribute, or the string "on". Its state would be one of "checked", "unchecked", "checked/indeterminate", or "unchecked/indeterminate".

ElementInternals/setFormValue

Firefox98+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOSNoChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

The setFormValue(value, state) method steps are:

  1. Let element be this's target element.

  2. If element is not a form-associated custom element, then throw a "NotSupportedError" DOMException.

  3. Set target element's submission value to value if value is not a FormData object, or to a clone of the entry list associated with value otherwise.

  4. If the state argument of the function is omitted, set element's state to its submission value.

  5. Otherwise, if state is a FormData object, set element's state to clone of the entry list associated with state.

  6. Otherwise, set element's state to state.


Each form-associated custom element has validity flags named valueMissing, typeMismatch, patternMismatch, tooLong, tooShort, rangeUnderflow, rangeOverflow, stepMismatch, and customError. They are false initially.

Each form-associated custom element has a validation message string. It is the empty string initially.

Each form-associated custom element has a validation anchor element. It is null initially.

ElementInternals/setValidity

Firefox98+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOSNoChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

The setValidity(flags, message, anchor) method steps are:

  1. Let element be this's target element.

  2. If element is not a form-associated custom element, then throw a "NotSupportedError" DOMException.

  3. If flags contains one or more true values and message is not given or is the empty string, then throw a TypeError.

  4. For each entry flagvalue of flags, set element's validity flag with the name flag to value.

  5. Set element's validation message to the empty string if message is not given or all of element's validity flags are false, or to message otherwise.

  6. If element's customError validity flag is true, then set element's custom validity error message to element's validation message. Otherwise, set element's custom validity error message to the empty string.

  7. Set element's validation anchor to null if anchor is not given. Otherwise, if anchor is not a shadow-including descendant of element, then throw a "NotFoundError" DOMException. Otherwise, set element's validation anchor to anchor.

ElementInternals/validationMessage

Firefox98+SafariNoChrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOSNoChrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

The validationMessage getter steps are to return the validation message of this's target element.

The entry construction algorithm for a form-associated custom element, given an element element and a list entry list, consists of the following steps:

  1. If element's submission value is a list of entries, then append each item of element's submission value to entry list, and return.

    In this case, user agent does not refer to the name content attribute value. An implementation of form-associated custom element is responsible to decide names of entries. They can be the name content attribute value, they can be strings based on the name content attribute value, or they can be unrelated to the name content attribute.

  2. If the element does not have a name attribute specified, or its name attribute's value is the empty string, then return.

  3. If the element's submission value is not null, append an entry to entry list with the name attribute value and the submission value.

4.13.7.4 Accessibility semantics
internals . role [ = value ]

Sets or retrieves the default ARIA role for internals's target element, which will be used unless the page author overrides it using the role attribute.

internals . aria* [ = value ]

Sets or retrieves various default ARIA states or property values for internals's target element, which will be used unless the page author overrides them using the aria-* attributes.

Each custom element has a native accessibility semantics map, which is a map, initially empty. See the Requirements related to ARIA and to platform accessibility APIs section for information on how this impacts platform accessibility APIs.

ElementInternals includes the ARIAMixin mixin. The accessors provided by this mixin are used to manipulate the target element's native accessibility semantics map, as follows:

The ARIAMixin getter steps for ElementInternals, given internals, idlAttribute, and contentAttribute, are:

  1. Let map be internals's target element's native accessibility semantics map.

  2. If map[contentAttribute] exists, then return it.

  3. Return null.

The ARIAMixin setter steps for ElementInternals, given internals, idlAttribute, contentAttribute, and value, are:

  1. Let map be internals's target element's native accessibility semantics map.

  2. If value is null, then remove map[contentAttribute].

  3. Otherwise, set map[contentAttribute] to value.

4.14 Common idioms without dedicated elements

4.14.1 面包屑导航

本规范没有提供机器可读的方式来描述面包屑导航彩蛋。 鼓励作者只是在段落中使用一些超链接。可以使用 nav 元素来标记包含这些段落的部分形成导航块。

在下面的例子中,当前页面可以通过两种路径到达。

<nav>
 <p>
  <a href="/">Main</a> ▸
  <a href="/products/">Products</a> ▸
  <a href="/products/dishwashers/">Dishwashers</a> ▸
  <a>Second hand</a>
 </p>
 <p>
  <a href="/">Main</a> ▸
  <a href="/second-hand/">Second hand</a> ▸
  <a>Dishwashers</a>
 </p>
</nav>

4.14.2 标签云

本规范没有定义任何专门标记一组页面的关键字列表(也称为 tag clouds)的标记。 通常,鼓励作者使用 ul 元素来标记这些列表。 其中写好计数并隐藏,再用样式表或 SVG 把它的效果呈现出来。

这是一个只有三个标签的标签云:

<style>
.tag-cloud > li > span { display: none; }
.tag-cloud > li { display: inline; }
.tag-cloud-1 { font-size: 0.7em; }
.tag-cloud-2 { font-size: 0.9em; }
.tag-cloud-3 { font-size: 1.1em; }
.tag-cloud-4 { font-size: 1.3em; }
.tag-cloud-5 { font-size: 1.5em; }

@media speech {
  .tag-cloud > li > span { display:inline }
}
</style>
...
<ul class="tag-cloud">
 <li class="tag-cloud-4"><a title="28 instances" href="/t/apple">apple</a> <span>(popular)</span>
 <li class="tag-cloud-2"><a title="6 instances"  href="/t/kiwi">kiwi</a> <span>(rare)</span>
 <li class="tag-cloud-5"><a title="41 instances" href="/t/pear">pear</a> <span>(very popular)</span>
</ul>

每个标签实际的频率使用 title 属性给出。 提供了一个 CSS 样式表来把标记转化成一个不同大小的词的云, 但不支持 CSS 的或非视觉的用户代理中,包含类似 "(popular)" 或 "(rare)" 字样的标记也会把不同频率的标签分离开, 这样所有用户都可以得到这个信息。

使用 ul 元素(而不是 ol)是因为顺序并不重要: 虽然列表实际上是按字母顺序排列的,但如果按标签的长度排序,它将传达相同的信息。

tag rel 关键字 没有 用在这些 a 元素上, 因为它们表示的标签不适用于当前页面自己;它们只是列出标签本身的索引的一部分。

4.14.3 对话

本规范没有定义特定的元素来标记对话、会议记录、聊天记录、剧本中的对话、即时通信记录, 和其他有不同参与者轮流发言的场景。

但是鼓励作者使用 p 元素和标点来标记对话。 需要标记发言者来提供样式的情况,鼓励作者使用 spanb。 可以使用 i 元素包裹其内容的段落来标记对话的信息。

这个例子中,使用了 Abbot 和 Costello's 著名的喜剧 Who's on first 中的一个摘录:

<p> Costello: Look, you gotta first baseman?
<p> Abbott: Certainly.
<p> Costello: Who's playing first?
<p> Abbott: That's right.
<p> Costello becomes exasperated.
<p> Costello: When you pay off the first baseman every month, who gets the money?
<p> Abbott: Every dollar of it.

下面的摘录演示了如何标记 IM 对话日志, 使用 data 元素来为每行提供 Unix 时间戳。 注意 time 元素不支持这个时间戳的格式,所以才使用了 data 元素(即 Unix time_t 时间戳)。 如果作者希望使用 time 元素支持的日期或时间格式来标记数据, 就要使用那个元素来替代 data。 这样的好处是数据分析工具可以无歧义地检测到时间戳,而不需要与网页作者协调。

<p> <data value="1319898155">14:22</data> <b>egof</b> I'm not that nerdy, I've only seen 30% of the star trek episodes
<p> <data value="1319898192">14:23</data> <b>kaj</b> if you know what percentage of the star trek episodes you have seen, you are inarguably nerdy
<p> <data value="1319898200">14:23</data> <b>egof</b> it's unarguably
<p> <data value="1319898228">14:23</data> <i>* kaj blinks</i>
<p> <data value="1319898260">14:24</data> <b>kaj</b> you are not helping your case

HTML 没有一种好的方式来标记图形,因此游戏中交互式对话的描述很难标记出来。 这个例子展示了一个可能的惯例,使用 dl 元素来列出对话中每个点可能的回复。 可以考虑的另一个选择是以 DOT 文件的格式来描述对话,然后把结果输出为 SVG 图片放到文档中。[DOT]

<p> Next, you meet a fisher. You can say one of several greetings:
<dl>
 <dt> "Hello there!"
 <dd>
  <p> She responds with "Hello, how may I help you?"; you can respond with:
  <dl>
   <dt> "I would like to buy a fish."
   <dd> <p> She sells you a fish and the conversation finishes.
   <dt> "Can I borrow your boat?"
   <dd>
    <p> She is surprised and asks "What are you offering in return?".
    <dl>
     <dt> "Five gold." (if you have enough)
     <dt> "Ten gold." (if you have enough)
     <dt> "Fifteen gold." (if you have enough)
     <dd> <p> She lends you her boat. The conversation ends.
     <dt> "A fish." (if you have one)
     <dt> "A newspaper." (if you have one)
     <dt> "A pebble." (if you have one)
     <dd> <p> "No thanks", she replies. Your conversation options
     at this point are the same as they were after asking to borrow
     her boat, minus any options you've suggested before.
    </dl>
   </dd>
  </dl>
 </dd>
 <dt> "Vote for me in the next election!"
 <dd> <p> She turns away. The conversation finishes.
 <dt> "Madam, are you aware that your fish are running away?"
 <dd>
  <p> She looks at you skeptically and says "Fish cannot run, miss".
  <dl>
   <dt> "You got me!"
   <dd> <p> The fisher sighs and the conversation ends.
   <dt> "Only kidding."
   <dd> <p> "Good one!" she retorts. Your conversation options at this
   point are the same as those following "Hello there!" above.
   <dt> "Oh, then what are they doing?"
   <dd> <p> She looks at her fish, giving you an opportunity to steal
   her boat, which you do. The conversation ends.
  </dl>
 </dd>
</dl>

有些图中对话比较简单:每个角色只有一些确定的话要说。 这个例子中,一个游戏 FAQ/流程 列出了每个角色的一些已知的可能回应:

<section>
 <h1>Dialogue</h1>
 <p><small>Some characters repeat their lines in order each time you interact
 with them, others randomly pick from amongst their lines. Those who respond in
 order have numbered entries in the lists below.</small>
 <h2>The Shopkeeper</h2>
 <ul>
  <li>How may I help you?
  <li>Fresh apples!
  <li>A loaf of bread for madam?
 </ul>
 <h2>The pilot</h2>
 <p>Before the accident:
 <ul>
  <li>I'm about to fly out, sorry!
  <li>Sorry, I'm just waiting for flight clearance and then I'll be off!
 </ul>
 <p>After the accident:
 <ol>
  <li>I'm about to fly out, sorry!
  <li>Ok, I'm not leaving right now, my plane is being cleaned.
  <li>Ok, it's not being cleaned, it needs a minor repair first.
  <li>Ok, ok, stop bothering me! Truth is, I had a crash.
 </ol>
 <h2>Clan Leader</h2>
 <p>During the first clan meeting:
 <ul>
  <li>Hey, have you seen my daughter? I bet she's up to something nefarious again...
  <li>Nice weather we're having today, eh?
  <li>The name is Bailey, Jeff Bailey. How can I help you today?
  <li>A glass of water? Fresh from the well!
 </ul>
 <p>After the earthquake:
 <ol>
  <li>Everyone is safe in the shelter, we just have to put out the fire!
  <li>I'll go and tell the fire brigade, you keep hosing it down!
 </ol>
</section>

4.14.4 脚注

HTML 没有标记脚注的专门机制。以下是建议的替代方案。


对于较短的行内注释,可以使用 title 属性。。

在这个例子中,对话框中有两部分是通过 title 属性, 使用类似脚注的内容注释的。

<p> <b>Customer</b>: Hello! I wish to register a complaint. Hello. Miss?
<p> <b>Shopkeeper</b>: <span title="Colloquial pronunciation of 'What do you'"
>Watcha</span> mean, miss?
<p> <b>Customer</b>: Uh, I'm sorry, I have a cold. I wish to make a complaint.
<p> <b>Shopkeeper</b>: Sorry, <span title="This is, of course, a lie.">we're
closing for lunch</span>.

不幸的是,很多用户代理目前不鼓励依赖 title 属性, 它们没有按照本规范的要求把该属性以可访问的方式暴露出来。 (例如,需要类似鼠标的指点设备才能让提示显示出来,这就排除了纯键盘用户和触摸设备用户, 这里面包括任何一个使用现代手机和平板的用户)。

如果使用 title 属性,可以使用 CSS 来吸引读者注意 这个有 title 属性的元素。

例如,下面的 CSS 在有 title 属性的元素下面画了一条虚线。

[title] { border-bottom: thin dashed; }

对于更长的注释,应该使用 a 元素,指向文档后面的一个元素。 根据惯例,这个超链接的内容是一个方括号中的数字。

在这个例子中,对话框中的脚注链接到了对话框下面的一个段落。 然后这个段落又链接回对话框,让用户可以返回脚注的位置。

<p> Announcer: Number 16: The <i>hand</i>.
<p> Interviewer: Good evening. I have with me in the studio tonight
Mr Norman St John Polevaulter, who for the past few years has been
contradicting people. Mr Polevaulter, why <em>do</em> you
contradict people?
<p> Norman: I don't. <sup><a href="#fn1" id="r1">[1]</a></sup>
<p> Interviewer: You told me you did!
...
<section>
 <p id="fn1"><a href="#r1">[1]</a> This is, naturally, a lie,
 but paradoxically if it were true he could not say so without
 contradicting the interviewer and thus making it false.</p>
</section>

对于适用于整个章节的文本(而非特定的词和句子)的更长的边栏笔记, 应该使用 aside 元素。

在这个例子中,对话框后给出了一个边栏,里面给出了一些上下文。

<p> <span class="speaker">Customer</span>: I will not buy this record, it is scratched.
<p> <span class="speaker">Shopkeeper</span>: I'm sorry?
<p> <span class="speaker">Customer</span>: I will not buy this record, it is scratched.
<p> <span class="speaker">Shopkeeper</span>: No no no, this's'a tobacconist's.
<aside>
 <p>In 1970, the British Empire lay in ruins, and foreign
 nationalists frequented the streets — many of them Hungarians
 (not the streets — the foreign nationals). Sadly, Alexander
 Yalt has been publishing incompetently-written phrase books.
</aside>

对图表而言,脚注可以包含在相关的 figcaptioncaption 元素中, 或者周围的文章中。

在这个例子中, 表格的单元格中有一些来自文章脚注。 使用了一个 figure 元素为表格和脚注一起给出了一个图例。

<figure>
 <figcaption>Table 1. Alternative activities for knights.</figcaption>
 <table>
  <tr>
   <th> Activity
   <th> Location
   <th> Cost
  <tr>
   <td> Dance
   <td> Wherever possible
   <td> £0<sup><a href="#fn1">1</a></sup>
  <tr>
   <td> Routines, chorus scenes<sup><a href="#fn2">2</a></sup>
   <td> Undisclosed
   <td> Undisclosed
  <tr>
   <td> Dining<sup><a href="#fn3">3</a></sup>
   <td> Camelot
   <td> Cost of ham, jam, and spam<sup><a href="#fn4">4</a></sup>
 </table>
 <p id="fn1">1. Assumed.</p>
 <p id="fn2">2. Footwork impeccable.</p>
 <p id="fn3">3. Quality described as "well".</p>
 <p id="fn4">4. A lot.</p>
</figure>

4.15 Disabled elements

An element is said to be actually disabled if it is one of the following:

This definition is used to determine what elements are focusable and which elements match the :enabled and :disabled pseudo classes.

4.16 使用选择符和 CSS 匹配 HTML 元素

4.16.1 CSS 'attr()' 函数的大小写敏感性

CSS Values and Units 规范把 'attr()' 函数的属性名的大小写敏感性留给宿主语言来定义。 [CSSVALUES]

当比较 CSS 'attr()' 函数的属性名部分与 HTML 文档 中的 HTML 元素 的 无命名空间的属性名时, CSS 'attr()' 函数的属性名部分首先必须 转换为 ASCII 小写。 该函数与其他属性对比时必须根据它原有的大小写。 在上述两种情况下,比较过程都是大小写敏感的。

这与比较 CSS 属性选择器 的名字部分是一样的, 在下一节中说明。

4.16.2 Case-sensitivity of selectors

Selectors leaves the case-sensitivity of element names, attribute names, and attribute values to be defined by the host language. [SELECTORS]

When comparing a CSS element type selector to the names of HTML elements in HTML documents, the CSS element type selector must first be converted to ASCII lowercase. The same selector when compared to other elements must be compared according to its original case. In both cases, to match the values must be identical to each other (and therefore the comparison is case sensitive).

When comparing the name part of a CSS attribute selector to the names of attributes on HTML elements in HTML documents, the name part of the CSS attribute selector must first be converted to ASCII lowercase. The same selector when compared to other attributes must be compared according to its original case. In both cases, the comparison is case-sensitive.

Attribute selectors on an HTML element in an HTML document must treat the values of attributes with the following names as ASCII case-insensitive:

For example, the selector [bgcolor="#ffffff"] will match any HTML element with a bgcolor attribute with values including #ffffff, #FFFFFF and #fffFFF. This happens even if bgcolor has no effect for a given element (e.g., div).

The selector [type=a s] will match any HTML element with a type attribute whose value is a, but not whose value is A, due to the s flag.

All other attribute values and everything else must be treated as entirely identical to each other for the purposes of selector matching. This includes:

Selectors defines that ID and class selectors (such as #foo and .bar), when matched against elements in documents that are in quirks mode, will be matched in an ASCII case-insensitive manner. However, this does not apply for attribute selectors with "id" or "class" as the name part. The selector [class="foobar"] will treat its value as case-sensitive even in quirks mode.

4.16.3 Pseudo-classes

Pseudo-classes

There are a number of dynamic selectors that can be used with HTML. This section defines when these selectors match HTML elements. [SELECTORS] [CSSUI]

:defined

:defined

Support in all current engines.

Firefox63+Safari10+Chrome54+
Opera41+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10+Chrome Android54+WebView Android54+Samsung Internet6.0+Opera Android41+

The :defined pseudo-class must match any element that is defined.

:link

:link

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3.5+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android1.5+Samsung Internet1.0+Opera Android14+
:visited

:visited

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3.5+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android10.1+

All a elements that have an href attribute, all area elements that have an href attribute, and all link elements that have an href attribute, must match one of :link and :visited.

Other specifications might apply more specific rules regarding how these elements are to match these pseudo-classes, to mitigate some privacy concerns that apply with straightforward implementations of this requirement.

:active

:active

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera5+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

The :active pseudo-class is defined to match an element while an element is being activated by the user.

To determine whether a particular element is being activated for the purposes of defining the :active pseudo-class only, an HTML user agent must use the first relevant entry in the following list.

If the element has a descendant that is currently matching the :active pseudo-class

The element is being activated.

If the element is the labeled control of a label element that is currently matching :active

The element is being activated.

If the element is a button element
If the element is an input element whose type attribute is in the Submit Button, Image Button, Reset Button, or Button state

The element is being activated if it is in a formal activation state and it is not disabled.

For example, if the user is using a keyboard to push a button element by pressing the space bar, the element would match this pseudo-class in between the time that the element received the keydown event and the time the element received the keyup event.

If the element is an a element that has an href attribute
If the element is an area element that has an href attribute
If the element is a link element that has an href attribute
If the element is focusable

The element is being activated if it is in a formal activation state.

If the element is being actively pointed at

The element is being activated.

An element is said to be in a formal activation state between the time the user begins to indicate an intent to trigger the element's activation behavior and either the time the user stops indicating an intent to trigger the element's activation behavior, or the time the element's activation behavior has finished running, which ever comes first.

An element is said to be being actively pointed at while the user indicates the element using a pointing device while that pointing device is in the "down" state (e.g. for a mouse, between the time the mouse button is pressed and the time it is depressed; for a finger in a multitouch environment, while the finger is touching the display surface).

:hover

:hover

Support in all current engines.

Firefox1+Safari2+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

The :hover pseudo-class is defined to match an element while the user designates an element with a pointing device. For the purposes of defining the :hover pseudo-class only, an HTML user agent must consider an element as being one that the user designates if it is:

Consider in particular a fragment such as:

<p> <label for=c> <input id=a> </label> <span id=b> <input id=c> </span> </p>

If the user designates the element with ID "a" with their pointing device, then the p element (and all its ancestors not shown in the snippet above), the label element, the element with ID "a", and the element with ID "c" will match the :hover pseudo-class. The element with ID "a" matches it from condition 1, the label and p elements match it because of condition 2 (one of their descendants is designated), and the element with ID "c" matches it through condition 3 (its label element matches :hover). However, the element with ID "b" does not match :hover: its descendant is not designated, even though it matches :hover.

:focus

:focus

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera7+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

For the purposes of the CSS :focus pseudo-class, an element has the focus when:

:target

:target

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android2+Samsung Internet1.0+Opera Android10.1+

For the purposes of the CSS :target pseudo-class, the Document's target elements are a list containing the Document's target element, if it is not null, or containing no elements, if it is. [SELECTORS]

:enabled

:enabled

Support in all current engines.

Firefox1+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android2+Samsung Internet1.0+Opera Android10.1+

The :enabled pseudo-class must match any button, input, select, textarea, optgroup, option, fieldset element, or form-associated custom element that is not actually disabled.

:disabled

:disabled

Support in all current engines.

Firefox1+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android2+Samsung Internet1.0+Opera Android10.1+

The :disabled pseudo-class must match any element that is actually disabled.

:checked

:checked

Support in all current engines.

Firefox1+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android2+Samsung Internet1.0+Opera Android10.1+

The :checked pseudo-class must match any element falling into one of the following categories:

:indeterminate

:indeterminate

Support in all current engines.

Firefox2+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

The :indeterminate pseudo-class must match any element falling into one of the following categories:

:default

:default

Support in all current engines.

Firefox4+Safari5+Chrome10+
Opera10+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

The :default pseudo-class must match any element falling into one of the following categories:

:placeholder-shown

The :placeholder-shown pseudo-class must match any element falling into one of the following categories:

:valid

:valid

Support in all current engines.

Firefox4+Safari5+Chrome10+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

The :valid pseudo-class must match any element falling into one of the following categories:

:invalid

:invalid

Support in all current engines.

Firefox4+Safari5+Chrome10+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

The :invalid pseudo-class must match any element falling into one of the following categories:

:in-range

:in-range

Support in all current engines.

Firefox29+Safari5.1+Chrome10+
Opera11+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android16+Safari iOS5+Chrome Android18+WebView Android2.2+Samsung Internet1.0+Opera Android11+

The :in-range pseudo-class must match all elements that are candidates for constraint validation, have range limitations, and that are neither suffering from an underflow nor suffering from an overflow.

:out-of-range

:out-of-range

Support in all current engines.

Firefox29+Safari5.1+Chrome10+
Opera11+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android16+Safari iOS5+Chrome Android18+WebView Android2.2+Samsung Internet1.0+Opera Android11+

The :out-of-range pseudo-class must match all elements that are candidates for constraint validation, have range limitations, and that are either suffering from an underflow or suffering from an overflow.

:required

:required

Support in all current engines.

Firefox4+Safari5+Chrome10+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4.3+Samsung Internet1.0+Opera Android10.1+

The :required pseudo-class must match any element falling into one of the following categories:

:optional

:optional

Support in all current engines.

Firefox4+Safari5+Chrome10+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

The :optional pseudo-class must match any element falling into one of the following categories:

:read-only

:read-only

Support in all current engines.

Firefox78+Safari4+Chrome1+
Opera9+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android🔰 4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+
:read-write

:read-write

Support in all current engines.

Firefox78+Safari4+Chrome1+
Opera9+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android🔰 4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

The :read-write pseudo-class must match any element falling into one of the following categories, which for the purposes of Selectors are thus considered user-alterable: [SELECTORS]

The :read-only pseudo-class must match all other HTML elements.

:dir(ltr)

:dir

Support in one engine only.

Firefox49+SafariNoChromeNo
OperaNoEdgeNo
Edge (Legacy)NoInternet ExplorerNo
Firefox Android49+Safari iOSNoChrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo

The :dir(ltr) pseudo-class must match all elements whose directionality is 'ltr'.

:dir(rtl)

The :dir(rtl) pseudo-class must match all elements whose directionality is 'rtl'.

This specification does not define when an element matches the :lang() dynamic pseudo-class, as it is defined in sufficient detail in a language-agnostic fashion in Selectors. [SELECTORS]

5 微数据

5.1 概述

5.1.1 Overview

This section is non-normative.

Sometimes, it is desirable to annotate content with specific machine-readable labels, e.g. to allow generic scripts to provide services that are customized to the page, or to enable content from a variety of cooperating authors to be processed by a single script in a consistent manner.

For this purpose, authors can use the microdata features described in this section. Microdata allows nested groups of name-value pairs to be added to documents, in parallel with the existing content.

5.1.2 The basic syntax

This section is non-normative.

At a high level, microdata consists of a group of name-value pairs. The groups are called items, and each name-value pair is a property. Items and properties are represented by regular elements.

To create an item, the itemscope attribute is used.

To add a property to an item, the itemprop attribute is used on one of the item's descendants.

Here there are two items, each of which has the property "name":

<div itemscope>
 <p>My name is <span itemprop="name">Elizabeth</span>.</p>
</div>

<div itemscope>
 <p>My name is <span itemprop="name">Daniel</span>.</p>
</div>

Markup without the microdata-related attributes does not have any effect on the microdata model.

These two examples are exactly equivalent, at a microdata level, as the previous two examples respectively:

<div itemscope>
 <p>My <em>name</em> is <span itemprop="name">E<strong>liz</strong>abeth</span>.</p>
</div>

<section>
 <div itemscope>
  <aside>
   <p>My name is <span itemprop="name"><a href="/?user=daniel">Daniel</a></span>.</p>
  </aside>
 </div>
</section>

Properties generally have values that are strings.

Here the item has three properties:

<div itemscope>
 <p>My name is <span itemprop="name">Neil</span>.</p>
 <p>My band is called <span itemprop="band">Four Parts Water</span>.</p>
 <p>I am <span itemprop="nationality">British</span>.</p>
</div>

When a string value is a URL, it is expressed using the a element and its href attribute, the img element and its src attribute, or other elements that link to or embed external resources.

In this example, the item has one property, "image", whose value is a URL:

<div itemscope>
 <img itemprop="image" src="google-logo.png" alt="Google">
</div>

When a string value is in some machine-readable format unsuitable for human consumption, it is expressed using the value attribute of the data element, with the human-readable version given in the element's contents.

Here, there is an item with a property whose value is a product ID. The ID is not human-friendly, so the product's name is used the human-visible text instead of the ID.

<h1 itemscope>
 <data itemprop="product-id" value="9678AOU879">The Instigator 2000</data>
</h1>

For numeric data, the meter element and its value attribute can be used instead.

Here a rating is given using a meter element.

<div itemscope itemtype="http://schema.org/Product">
 <span itemprop="name">Panasonic White 60L Refrigerator</span>
 <img src="panasonic-fridge-60l-white.jpg" alt="">
  <div itemprop="aggregateRating"
       itemscope itemtype="http://schema.org/AggregateRating">
   <meter itemprop="ratingValue" min=0 value=3.5 max=5>Rated 3.5/5</meter>
   (based on <span itemprop="reviewCount">11</span> customer reviews)
  </div>
</div>

Similarly, for date- and time-related data, the time element and its datetime attribute can be used instead.

In this example, the item has one property, "birthday", whose value is a date:

<div itemscope>
 I was born on <time itemprop="birthday" datetime="2009-05-10">May 10th 2009</time>.
</div>

Properties can also themselves be groups of name-value pairs, by putting the itemscope attribute on the element that declares the property.

Items that are not part of others are called top-level microdata items.

In this example, the outer item represents a person, and the inner one represents a band:

<div itemscope>
 <p>Name: <span itemprop="name">Amanda</span></p>
 <p>Band: <span itemprop="band" itemscope> <span itemprop="name">Jazz Band</span> (<span itemprop="size">12</span> players)</span></p>
</div>

The outer item here has two properties, "name" and "band". The "name" is "Amanda", and the "band" is an item in its own right, with two properties, "name" and "size". The "name" of the band is "Jazz Band", and the "size" is "12".

The outer item in this example is a top-level microdata item.

Properties that are not descendants of the element with the itemscope attribute can be associated with the item using the itemref attribute. This attribute takes a list of IDs of elements to crawl in addition to crawling the children of the element with the itemscope attribute.

This example is the same as the previous one, but all the properties are separated from their items:

<div itemscope id="amanda" itemref="a b"></div>
<p id="a">Name: <span itemprop="name">Amanda</span></p>
<div id="b" itemprop="band" itemscope itemref="c"></div>
<div id="c">
 <p>Band: <span itemprop="name">Jazz Band</span></p>
 <p>Size: <span itemprop="size">12</span> players</p>
</div>

This gives the same result as the previous example. The first item has two properties, "name", set to "Amanda", and "band", set to another item. That second item has two further properties, "name", set to "Jazz Band", and "size", set to "12".

An item can have multiple properties with the same name and different values.

This example describes an ice cream, with two flavors:

<div itemscope>
 <p>Flavors in my favorite ice cream:</p>
 <ul>
  <li itemprop="flavor">Lemon sorbet</li>
  <li itemprop="flavor">Apricot sorbet</li>
 </ul>
</div>

This thus results in an item with two properties, both "flavor", having the values "Lemon sorbet" and "Apricot sorbet".

An element introducing a property can also introduce multiple properties at once, to avoid duplication when some of the properties have the same value.

Here we see an item with two properties, "favorite-color" and "favorite-fruit", both set to the value "orange":

<div itemscope>
 <span itemprop="favorite-color favorite-fruit">orange</span>
</div>

It's important to note that there is no relationship between the microdata and the content of the document where the microdata is marked up.

There is no semantic difference, for instance, between the following two examples:

<figure>
 <img src="castle.jpeg">
 <figcaption><span itemscope><span itemprop="name">The Castle</span></span> (1986)</figcaption>
</figure>
<span itemscope><meta itemprop="name" content="The Castle"></span>
<figure>
 <img src="castle.jpeg">
 <figcaption>The Castle (1986)</figcaption>
</figure>

Both have a figure with a caption, and both, completely unrelated to the figure, have an item with a name-value pair with the name "name" and the value "The Castle". The only difference is that if the user drags the caption out of the document, in the former case, the item will be included in the drag-and-drop data. In neither case is the image in any way associated with the item.

5.1.3 Typed items

This section is non-normative.

The examples in the previous section show how information could be marked up on a page that doesn't expect its microdata to be re-used. Microdata is most useful, though, when it is used in contexts where other authors and readers are able to cooperate to make new uses of the markup.

For this purpose, it is necessary to give each item a type, such as "https://example.com/person", or "https://example.org/cat", or "https://band.example.net/". Types are identified as URLs.

The type for an item is given as the value of an itemtype attribute on the same element as the itemscope attribute.

Here, the item's type is "https://example.org/animals#cat":

<section itemscope itemtype="https://example.org/animals#cat">
 <h1 itemprop="name">Hedral</h1>
 <p itemprop="desc">Hedral is a male american domestic
 shorthair, with a fluffy black fur with white paws and belly.</p>
 <img itemprop="img" src="hedral.jpeg" alt="" title="Hedral, age 18 months">
</section>

In this example the "https://example.org/animals#cat" item has three properties, a "name" ("Hedral"), a "desc" ("Hedral is..."), and an "img" ("hedral.jpeg").

The type gives the context for the properties, thus selecting a vocabulary: a property named "class" given for an item with the type "https://census.example/person" might refer to the economic class of an individual, while a property named "class" given for an item with the type "https://example.com/school/teacher" might refer to the classroom a teacher has been assigned. Several types can share a vocabulary. For example, the types "https://example.org/people/teacher" and "https://example.org/people/engineer" could be defined to use the same vocabulary (though maybe some properties would not be especially useful in both cases, e.g. maybe the "https://example.org/people/engineer" type might not typically be used with the "classroom" property). Multiple types defined to use the same vocabulary can be given for a single item by listing the URLs as a space-separated list in the attribute' value. An item cannot be given two types if they do not use the same vocabulary, however.

5.1.4 Global identifiers for items

This section is non-normative.

Sometimes, an item gives information about a topic that has a global identifier. For example, books can be identified by their ISBN number.

Vocabularies (as identified by the itemtype attribute) can be designed such that items get associated with their global identifier in an unambiguous way by expressing the global identifiers as URLs given in an itemid attribute.

The exact meaning of the URLs given in itemid attributes depends on the vocabulary used.

Here, an item is talking about a particular book:

<dl itemscope
    itemtype="https://vocab.example.net/book"
    itemid="urn:isbn:0-330-34032-8">
 <dt>Title
 <dd itemprop="title">The Reality Dysfunction
 <dt>Author
 <dd itemprop="author">Peter F. Hamilton
 <dt>Publication date
 <dd><time itemprop="pubdate" datetime="1996-01-26">26 January 1996</time>
</dl>

The "https://vocab.example.net/book" vocabulary in this example would define that the itemid attribute takes a urn: URL pointing to the ISBN of the book.

5.1.5 Selecting names when defining vocabularies

This section is non-normative.

Using microdata means using a vocabulary. For some purposes, an ad-hoc vocabulary is adequate. For others, a vocabulary will need to be designed. Where possible, authors are encouraged to re-use existing vocabularies, as this makes content re-use easier.

When designing new vocabularies, identifiers can be created either using URLs, or, for properties, as plain words (with no dots or colons). For URLs, conflicts with other vocabularies can be avoided by only using identifiers that correspond to pages that the author has control over.

For instance, if Jon and Adam both write content at example.com, at https://example.com/~jon/... and https://example.com/~adam/... respectively, then they could select identifiers of the form "https://example.com/~jon/name" and "https://example.com/~adam/name" respectively.

Properties whose names are just plain words can only be used within the context of the types for which they are intended; properties named using URLs can be reused in items of any type. If an item has no type, and is not part of another item, then if its properties have names that are just plain words, they are not intended to be globally unique, and are instead only intended for limited use. Generally speaking, authors are encouraged to use either properties with globally unique names (URLs) or ensure that their items are typed.

Here, an item is an "https://example.org/animals#cat", and most of the properties have names that are words defined in the context of that type. There are also a few additional properties whose names come from other vocabularies.

<section itemscope itemtype="https://example.org/animals#cat">
 <h1 itemprop="name https://example.com/fn">Hedral</h1>
 <p itemprop="desc">Hedral is a male american domestic
 shorthair, with a fluffy <span
 itemprop="https://example.com/color">black</span> fur with <span
 itemprop="https://example.com/color">white</span> paws and belly.</p>
 <img itemprop="img" src="hedral.jpeg" alt="" title="Hedral, age 18 months">
</section>

This example has one item with the type "https://example.org/animals#cat" and the following properties:

Property Value
name Hedral
https://example.com/fn Hedral
desc Hedral is a male american domestic shorthair, with a fluffy black fur with white paws and belly.
https://example.com/color black
https://example.com/color white
img .../hedral.jpeg

5.2 Encoding microdata

5.2.1 The microdata model

The microdata model consists of groups of name-value pairs known as items.

Each group is known as an item. Each item can have item types, a global identifier (if the vocabulary specified by the item types support global identifiers for items), and a list of name-value pairs. Each name in the name-value pair is known as a property, and each property has one or more values. Each value is either a string or itself a group of name-value pairs (an item). The names are unordered relative to each other, but if a particular name has multiple values, they do have a relative order.

5.2.2 Items

Global_attributes/itemscope

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Every HTML element may have an itemscope attribute specified. The itemscope attribute is a boolean attribute.

An element with the itemscope attribute specified creates a new item, a group of name-value pairs.


Global_attributes/itemtype

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Elements with an itemscope attribute may have an itemtype attribute specified, to give the item types of the item.

The itemtype attribute, if specified, must have a value that is an unordered set of unique space-separated tokens, none of which are identical to another token and each of which is a valid URL string that is an absolute URL, and all of which are defined to use the same vocabulary. The attribute's value must have at least one token.

The item types of an item are the tokens obtained by splitting the element's itemtype attribute's value on ASCII whitespace. If the itemtype attribute is missing or parsing it in this way finds no tokens, the item is said to have no item types.

The item types must all be types defined in applicable specifications and must all be defined to use the same vocabulary.

Except if otherwise specified by that specification, the URLs given as the item types should not be automatically dereferenced.

A specification could define that its item type can be dereferenced to provide the user with help information, for example. In fact, vocabulary authors are encouraged to provide useful information at the given URL.

Item types are opaque identifiers, and user agents must not dereference unknown item types, or otherwise deconstruct them, in order to determine how to process items that use them.

The itemtype attribute must not be specified on elements that do not have an itemscope attribute specified.


An item is said to be a typed item when either it has an item type, or it is the value of a property of a typed item. The relevant types for a typed item is the item's item types, if it has any, or else is the relevant types of the item for which it is a property's value.


Global_attributes/itemid

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Elements with an itemscope attribute and an itemtype attribute that references a vocabulary that is defined to support global identifiers for items may also have an itemid attribute specified, to give a global identifier for the item, so that it can be related to other items on pages elsewhere on the web.

The itemid attribute, if specified, must have a value that is a valid URL potentially surrounded by spaces.

The global identifier of an item is the value of its element's itemid attribute, if it has one, parsed relative to the node document of the element on which the attribute is specified. If the itemid attribute is missing or if resolving it fails, it is said to have no global identifier.

The itemid attribute must not be specified on elements that do not have both an itemscope attribute and an itemtype attribute specified, and must not be specified on elements with an itemscope attribute whose itemtype attribute specifies a vocabulary that does not support global identifiers for items, as defined by that vocabulary's specification.

The exact meaning of a global identifier is determined by the vocabulary's specification. It is up to such specifications to define whether multiple items with the same global identifier (whether on the same page or on different pages) are allowed to exist, and what the processing rules for that vocabulary are with respect to handling the case of multiple items with the same ID.


Global_attributes/itemref

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Elements with an itemscope attribute may have an itemref attribute specified, to give a list of additional elements to crawl to find the name-value pairs of the item.

The itemref attribute, if specified, must have a value that is an unordered set of unique space-separated tokens none of which are identical to another token and consisting of IDs of elements in the same tree.

The itemref attribute must not be specified on elements that do not have an itemscope attribute specified.

The itemref attribute is not part of the microdata data model. It is merely a syntactic construct to aid authors in adding annotations to pages where the data to be annotated does not follow a convenient tree structure. For example, it allows authors to mark up data in a table so that each column defines a separate item, while keeping the properties in the cells.

This example shows a simple vocabulary used to describe the products of a model railway manufacturer. The vocabulary has just five property names:

product-code
An integer that names the product in the manufacturer's catalog.
name
A brief description of the product.
scale
One of "HO", "1", or "Z" (potentially with leading or trailing whitespace), indicating the scale of the product.
digital
If present, one of "Digital", "Delta", or "Systems" (potentially with leading or trailing whitespace) indicating that the product has a digital decoder of the given type.
track-type
For track-specific products, one of "K", "M", "C" (potentially with leading or trailing whitespace) indicating the type of track for which the product is intended.

This vocabulary has four defined item types:

https://md.example.com/loco
Rolling stock with an engine
https://md.example.com/passengers
Passenger rolling stock
https://md.example.com/track
Track pieces
https://md.example.com/lighting
Equipment with lighting

Each item that uses this vocabulary can be given one or more of these types, depending on what the product is.

Thus, a locomotive might be marked up as:

<dl itemscope itemtype="https://md.example.com/loco
                        https://md.example.com/lighting">
 <dt>Name:
 <dd itemprop="name">Tank Locomotive (DB 80)
 <dt>Product code:
 <dd itemprop="product-code">33041
 <dt>Scale:
 <dd itemprop="scale">HO
 <dt>Digital:
 <dd itemprop="digital">Delta
</dl>

A turnout lantern retrofit kit might be marked up as:

<dl itemscope itemtype="https://md.example.com/track
                        https://md.example.com/lighting">
 <dt>Name:
 <dd itemprop="name">Turnout Lantern Kit
 <dt>Product code:
 <dd itemprop="product-code">74470
 <dt>Purpose:
 <dd>For retrofitting 2 <span itemprop="track-type">C</span> Track
 turnouts. <meta itemprop="scale" content="HO">
</dl>

A passenger car with no lighting might be marked up as:

<dl itemscope itemtype="https://md.example.com/passengers">
 <dt>Name:
 <dd itemprop="name">Express Train Passenger Car (DB Am 203)
 <dt>Product code:
 <dd itemprop="product-code">8710
 <dt>Scale:
 <dd itemprop="scale">Z
</dl>

Great care is necessary when creating new vocabularies. Often, a hierarchical approach to types can be taken that results in a vocabulary where each item only ever has a single type, which is generally much simpler to manage.

5.2.3 Names: the itemprop attribute

Global_attributes/itemprop

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

Every HTML element may have an itemprop attribute specified, if doing so adds one or more properties to one or more items (as defined below).

The itemprop attribute, if specified, must have a value that is an unordered set of unique space-separated tokens none of which are identical to another token, representing the names of the name-value pairs that it adds. The attribute's value must have at least one token.

Each token must be either:

Specifications that introduce defined property names must ensure all such property names contain no U+002E FULL STOP characters (.), no U+003A COLON characters (:), and no ASCII whitespace.

The rules above disallow U+003A COLON characters (:) in non-URL values because otherwise they could not be distinguished from URLs. Values with U+002E FULL STOP characters (.) are reserved for future extensions. ASCII whitespace are disallowed because otherwise the values would be parsed as multiple tokens.

When an element with an itemprop attribute adds a property to multiple items, the requirement above regarding the tokens applies for each item individually.

The property names of an element are the tokens that the element's itemprop attribute is found to contain when its value is split on ASCII whitespace, with the order preserved but with duplicates removed (leaving only the first occurrence of each name).

Within an item, the properties are unordered with respect to each other, except for properties with the same name, which are ordered in the order they are given by the algorithm that defines the properties of an item.

In the following example, the "a" property has the values "1" and "2", in that order, but whether the "a" property comes before the "b" property or not is not important:

<div itemscope>
 <p itemprop="a">1</p>
 <p itemprop="a">2</p>
 <p itemprop="b">test</p>
</div>

Thus, the following is equivalent:

<div itemscope>
 <p itemprop="b">test</p>
 <p itemprop="a">1</p>
 <p itemprop="a">2</p>
</div>

As is the following:

<div itemscope>
 <p itemprop="a">1</p>
 <p itemprop="b">test</p>
 <p itemprop="a">2</p>
</div>

And the following:

<div id="x">
 <p itemprop="a">1</p>
</div>
<div itemscope itemref="x">
 <p itemprop="b">test</p>
 <p itemprop="a">2</p>
</div>

5.2.4 Values

The property value of a name-value pair added by an element with an itemprop attribute is as given for the first matching case in the following list:

If the element also has an itemscope attribute

The value is the item created by the element.

If the element is a meta element

The value is the value of the element's content attribute, if any, or the empty string if there is no such attribute.

If the element is an audio, embed, iframe, img, source, track, or video element

The value is the resulting URL string that results from parsing the value of the element's src attribute relative to the node document of the element at the time the attribute is set, or the empty string if there is no such attribute or if parsing it results in an error.

If the element is an a, area, or link element

The value is the resulting URL string that results from parsing the value of the element's href attribute relative to the node document of the element at the time the attribute is set, or the empty string if there is no such attribute or if parsing it results in an error.

If the element is an object element

The value is the resulting URL string that results from parsing the value of the element's data attribute relative to the node document of the element at the time the attribute is set, or the empty string if there is no such attribute or if parsing it results in an error.

If the element is a data element

The value is the value of the element's value attribute, if it has one, or the empty string otherwise.

If the element is a meter element

The value is the value of the element's value attribute, if it has one, or the empty string otherwise.

If the element is a time element

The value is the element's datetime value.

Otherwise

The value is the element's descendant text content.

The URL property elements are the a, area, audio, embed, iframe, img, link, object, source, track, and video elements.

If a property's value, as defined by the property's definition, is an absolute URL, the property must be specified using a URL property element.

These requirements do not apply just because a property value happens to match the syntax for a URL. They only apply if the property is explicitly defined as taking such a value.

For example, a book about the first moon landing could be called "mission:moon". A "title" property from a vocabulary that defines a title as being a string would not expect the title to be given in an a element, even though it looks like a URL. On the other hand, if there was a (rather narrowly scoped!) vocabulary for "books whose titles look like URLs" which had a "title" property defined to take a URL, then the property would expect the title to be given in an a element (or one of the other URL property elements), because of the requirement above.

5.2.5 Associating names with items

To find the properties of an item defined by the element root, the user agent must run the following steps. These steps are also used to flag microdata errors.

  1. Let results, memory, and pending be empty lists of elements.

  2. Add the element root to memory.

  3. Add the child elements of root, if any, to pending.

  4. If root has an itemref attribute, split the value of that itemref attribute on ASCII whitespace. For each resulting token ID, if there is an element in the tree of root with the ID ID, then add the first such element to pending.

  5. While pending is not empty:

    1. Remove an element from pending and let current be that element.

    2. If current is already in memory, there is a microdata error; continue.

    3. Add current to memory.

    4. If current does not have an itemscope attribute, then: add all the child elements of current to pending.

    5. If current has an itemprop attribute specified and has one or more property names, then add current to results.

  6. Sort results in tree order.

  7. Return results.

A document must not contain any items for which the algorithm to find the properties of an item finds any microdata errors.

An item is a top-level microdata item if its element does not have an itemprop attribute.

All itemref attributes in a Document must be such that there are no cycles in the graph formed from representing each item in the Document as a node in the graph and each property of an item whose value is another item as an edge in the graph connecting those two items.

A document must not contain any elements that have an itemprop attribute that would not be found to be a property of any of the items in that document were their properties all to be determined.

In this example, a single license statement is applied to two works, using itemref from the items representing the works:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Photo gallery</title>
 </head>
 <body>
  <h1>My photos</h1>
  <figure itemscope itemtype="http://n.whatwg.org/work" itemref="licenses">
   <img itemprop="work" src="images/house.jpeg" alt="A white house, boarded up, sits in a forest.">
   <figcaption itemprop="title">The house I found.</figcaption>
  </figure>
  <figure itemscope itemtype="http://n.whatwg.org/work" itemref="licenses">
   <img itemprop="work" src="images/mailbox.jpeg" alt="Outside the house is a mailbox. It has a leaflet inside.">
   <figcaption itemprop="title">The mailbox.</figcaption>
  </figure>
  <footer>
   <p id="licenses">All images licensed under the <a itemprop="license"
   href="http://www.opensource.org/licenses/mit-license.php">MIT
   license</a>.</p>
  </footer>
 </body>
</html>

The above results in two items with the type "http://n.whatwg.org/work", one with:

work
images/house.jpeg
title
The house I found.
license
http://www.opensource.org/licenses/mit-license.php

...and one with:

work
images/mailbox.jpeg
title
The mailbox.
license
http://www.opensource.org/licenses/mit-license.php

5.2.6 Microdata and other namespaces

Currently, the itemscope, itemprop, and other microdata attributes are only defined for HTML elements. This means that attributes with the literal names "itemscope", "itemprop", etc, do not cause microdata processing to occur on elements in other namespaces, such as SVG.

Thus, in the following example there is only one item, not two.

<p itemscope></p> <!-- this is an item (with no properties and no type) -->
<svg itemscope></svg> <!-- this is not, it's just an SVG svg element with an invalid unknown attribute -->

5.3 Sample microdata vocabularies

The vocabularies in this section are primarily intended to demonstrate how a vocabulary is specified, though they are also usable in their own right.

5.3.1 vCard

An item with the item type http://microformats.org/profile/hcard represents a person's or organization's contact information.

This vocabulary does not support global identifiers for items.

The following are the type's defined property names. They are based on the vocabulary defined in vCard Format Specification (vCard) and its extensions, where more information on how to interpret the values can be found. [RFC6350]

kind

Describes what kind of contact the item represents.

The value must be text that is identical to one of the kind strings.

A single property with the name kind may be present within each item with the type http://microformats.org/profile/hcard.

fn

Gives the formatted text corresponding to the name of the person or organization.

The value must be text.

Exactly one property with the name fn must be present within each item with the type http://microformats.org/profile/hcard.

n

Gives the structured name of the person or organization.

The value must be an item with zero or more of each of the family-name, given-name, additional-name, honorific-prefix, and honorific-suffix properties.

Exactly one property with the name n must be present within each item with the type http://microformats.org/profile/hcard.

family-name (inside n)

Gives the family name of the person, or the full name of the organization.

The value must be text.

Any number of properties with the name family-name may be present within the item that forms the value of the n property of an item with the type http://microformats.org/profile/hcard.

given-name (inside n)

Gives the given-name of the person.

The value must be text.

Any number of properties with the name given-name may be present within the item that forms the value of the n property of an item with the type http://microformats.org/profile/hcard.

additional-name (inside n)

Gives the any additional names of the person.

The value must be text.

Any number of properties with the name additional-name may be present within the item that forms the value of the n property of an item with the type http://microformats.org/profile/hcard.

honorific-prefix (inside n)

Gives the honorific prefix of the person.

The value must be text.

Any number of properties with the name honorific-prefix may be present within the item that forms the value of the n property of an item with the type http://microformats.org/profile/hcard.

honorific-suffix (inside n)

Gives the honorific suffix of the person.

The value must be text.

Any number of properties with the name honorific-suffix may be present within the item that forms the value of the n property of an item with the type http://microformats.org/profile/hcard.

nickname

Gives the nickname of the person or organization.

The nickname is the descriptive name given instead of or in addition to the one belonging to a person, place, or thing. It can also be used to specify a familiar form of a proper name specified by the fn or n properties.

The value must be text.

Any number of properties with the name nickname may be present within each item with the type http://microformats.org/profile/hcard.

photo

Gives a photograph of the person or organization.

The value must be an absolute URL.

Any number of properties with the name photo may be present within each item with the type http://microformats.org/profile/hcard.

bday

Gives the birth date of the person or organization.

The value must be a valid date string.

A single property with the name bday may be present within each item with the type http://microformats.org/profile/hcard.

anniversary

Gives the birth date of the person or organization.

The value must be a valid date string.

A single property with the name anniversary may be present within each item with the type http://microformats.org/profile/hcard.

sex

Gives the biological sex of the person.

The value must be one of F, meaning "female", M, meaning "male", N, meaning "none or not applicable", O, meaning "other", or U, meaning "unknown".

A single property with the name sex may be present within each item with the type http://microformats.org/profile/hcard.

gender-identity

Gives the gender identity of the person.

The value must be text.

A single property with the name gender-identity may be present within each item with the type http://microformats.org/profile/hcard.

adr

Gives the delivery address of the person or organization.

The value must be an item with zero or more type, post-office-box, extended-address, and street-address properties, and optionally a locality property, optionally a region property, optionally a postal-code property, and optionally a country-name property.

If no type properties are present within an item that forms the value of an adr property of an item with the type http://microformats.org/profile/hcard, then the address type string work is implied.

Any number of properties with the name adr may be present within each item with the type http://microformats.org/profile/hcard.

type (inside adr)

Gives the type of delivery address.

The value must be text that is identical to one of the address type strings.

Any number of properties with the name type may be present within the item that forms the value of an adr property of an item with the type http://microformats.org/profile/hcard, but within each such adr property item there must only be one type property per distinct value.

post-office-box (inside adr)

Gives the post office box component of the delivery address of the person or organization.

The value must be text.

Any number of properties with the name post-office-box may be present within the item that forms the value of an adr property of an item with the type http://microformats.org/profile/hcard.

vCard urges authors not to use this field.

extended-address (inside adr)

Gives an additional component of the delivery address of the person or organization.

The value must be text.

Any number of properties with the name extended-address may be present within the item that forms the value of an adr property of an item with the type http://microformats.org/profile/hcard.

vCard urges authors not to use this field.

street-address (inside adr)

Gives the street address component of the delivery address of the person or organization.

The value must be text.

Any number of properties with the name street-address may be present within the item that forms the value of an adr property of an item with the type http://microformats.org/profile/hcard.

locality (inside adr)

Gives the locality component (e.g. city) of the delivery address of the person or organization.

The value must be text.

A single property with the name locality may be present within the item that forms the value of an adr property of an item with the type http://microformats.org/profile/hcard.

region (inside adr)

Gives the region component (e.g. state or province) of the delivery address of the person or organization.

The value must be text.

A single property with the name region may be present within the item that forms the value of an adr property of an item with the type http://microformats.org/profile/hcard.

postal-code (inside adr)

Gives the postal code component of the delivery address of the person or organization.

The value must be text.

A single property with the name postal-code may be present within the item that forms the value of an adr property of an item with the type http://microformats.org/profile/hcard.

country-name (inside adr)

Gives the country name component of the delivery address of the person or organization.

The value must be text.

A single property with the name country-name may be present within the item that forms the value of an adr property of an item with the type http://microformats.org/profile/hcard.

tel

Gives the telephone number of the person or organization.

The value must be either text that can be interpreted as a telephone number as defined in the CCITT specifications E.163 and X.121, or an item with zero or more type properties and exactly one value property. [E163] [X121]

If no type properties are present within an item that forms the value of a tel property of an item with the type http://microformats.org/profile/hcard, or if the value of such a tel property is text, then the telephone type string voice is implied.

Any number of properties with the name tel may be present within each item with the type http://microformats.org/profile/hcard.

type (inside tel)

Gives the type of telephone number.

The value must be text that is identical to one of the telephone type strings.

Any number of properties with the name type may be present within the item that forms the value of a tel property of an item with the type http://microformats.org/profile/hcard, but within each such tel property item there must only be one type property per distinct value.

value (inside tel)

Gives the actual telephone number of the person or organization.

The value must be text that can be interpreted as a telephone number as defined in the CCITT specifications E.163 and X.121. [E163] [X121]

Exactly one property with the name value must be present within the item that forms the value of a tel property of an item with the type http://microformats.org/profile/hcard.

email

Gives the email address of the person or organization.

The value must be text.

Any number of properties with the name email may be present within each item with the type http://microformats.org/profile/hcard.

impp

Gives a URL for instant messaging and presence protocol communications with the person or organization.

The value must be an absolute URL.

Any number of properties with the name impp may be present within each item with the type http://microformats.org/profile/hcard.

lang

Gives a language understood by the person or organization.

The value must be a valid BCP 47 language tag. [BCP47].

Any number of properties with the name lang may be present within each item with the type http://microformats.org/profile/hcard.

tz

Gives the time zone of the person or organization.

The value must be text and must match the following syntax:

  1. Either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character (-).
  2. A valid non-negative integer that is exactly two digits long and that represents a number in the range 00..23.
  3. A U+003A COLON character (:).
  4. A valid non-negative integer that is exactly two digits long and that represents a number in the range 00..59.

Any number of properties with the name tz may be present within each item with the type http://microformats.org/profile/hcard.

geo

Gives the geographical position of the person or organization.

The value must be text and must match the following syntax:

  1. Optionally, either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character (-).
  2. One or more ASCII digits.
  3. Optionally*, a U+002E FULL STOP character (.) followed by one or more ASCII digits.
  4. A U+003B SEMICOLON character (;).
  5. Optionally, either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character (-).
  6. One or more ASCII digits.
  7. Optionally*, a U+002E FULL STOP character (.) followed by one or more ASCII digits.

The optional components marked with an asterisk (*) should be included, and should have six digits each.

The value specifies latitude and longitude, in that order (i.e., "LAT LON" ordering), in decimal degrees. The longitude represents the location east and west of the prime meridian as a positive or negative real number, respectively. The latitude represents the location north and south of the equator as a positive or negative real number, respectively.

Any number of properties with the name geo may be present within each item with the type http://microformats.org/profile/hcard.

title

Gives the job title, functional position or function of the person or organization.

The value must be text.

Any number of properties with the name title may be present within each item with the type http://microformats.org/profile/hcard.

role

Gives the role, occupation, or business category of the person or organization.

The value must be text.

Any number of properties with the name role may be present within each item with the type http://microformats.org/profile/hcard.

Gives the logo of the person or organization.

The value must be an absolute URL.

Any number of properties with the name may be present within each item with the type http://microformats.org/profile/hcard.

agent

Gives the contact information of another person who will act on behalf of the person or organization.

The value must be either an item with the type http://microformats.org/profile/hcard, or an absolute URL, or text.

Any number of properties with the name agent may be present within each item with the type http://microformats.org/profile/hcard.

org

Gives the name and units of the organization.

The value must be either text or an item with one organization-name property and zero or more organization-unit properties.

Any number of properties with the name org may be present within each item with the type http://microformats.org/profile/hcard.

organization-name (inside org)

Gives the name of the organization.

The value must be text.

Exactly one property with the name organization-name must be present within the item that forms the value of an org property of an item with the type http://microformats.org/profile/hcard.

organization-unit (inside org)

Gives the name of the organization unit.

The value must be text.

Any number of properties with the name organization-unit may be present within the item that forms the value of the org property of an item with the type http://microformats.org/profile/hcard.

member

Gives a URL that represents a member of the group.

The value must be an absolute URL.

Any number of properties with the name member may be present within each item with the type http://microformats.org/profile/hcard if the item also has a property with the name kind whose value is "group".

related

Gives a relationship to another entity.

The value must be an item with one url property and one rel properties.

Any number of properties with the name related may be present within each item with the type http://microformats.org/profile/hcard.

url (inside related)

Gives the URL for the related entity.

The value must be an absolute URL.

Exactly one property with the name url must be present within the item that forms the value of a related property of an item with the type http://microformats.org/profile/hcard.

rel (inside related)

Gives the relationship between the entity and the related entity.

The value must be text that is identical to one of the relationship strings.

Exactly one property with the name rel must be present within the item that forms the value of a related property of an item with the type http://microformats.org/profile/hcard.

categories

Gives the name of a category or tag that the person or organization could be classified as.

The value must be text.

Any number of properties with the name categories may be present within each item with the type http://microformats.org/profile/hcard.

note

Gives supplemental information or a comment about the person or organization.

The value must be text.

Any number of properties with the name note may be present within each item with the type http://microformats.org/profile/hcard.

rev

Gives the revision date and time of the contact information.

The value must be text that is a valid global date and time string.

The value distinguishes the current revision of the information for other renditions of the information.

Any number of properties with the name rev may be present within each item with the type http://microformats.org/profile/hcard.

sound

Gives a sound file relating to the person or organization.

The value must be an absolute URL.

Any number of properties with the name sound may be present within each item with the type http://microformats.org/profile/hcard.

uid

Gives a globally unique identifier corresponding to the person or organization.

The value must be text.

A single property with the name uid may be present within each item with the type http://microformats.org/profile/hcard.

url

Gives a URL relating to the person or organization.

The value must be an absolute URL.

Any number of properties with the name url may be present within each item with the type http://microformats.org/profile/hcard.

The kind strings are:

individual

Indicates a single entity (e.g. a person).

group

Indicates multiple entities (e.g. a mailing list).

org

Indicates a single entity that is not a person (e.g. a company).

location

Indicates a geographical place (e.g. an office building).

The address type strings are:

home

Indicates a delivery address for a residence.

work

Indicates a delivery address for a place of work.

The telephone type strings are:

home

Indicates a residential number.

work

Indicates a telephone number for a place of work.

text

Indicates that the telephone number supports text messages (SMS).

voice

Indicates a voice telephone number.

fax

Indicates a facsimile telephone number.

cell

Indicates a cellular telephone number.

video

Indicates a video conferencing telephone number.

pager

Indicates a paging device telephone number.

textphone

Indicates a telecommunication device for people with hearing or speech difficulties.

The relationship strings are:

emergency

An emergency contact.

agent

Another entity that acts on behalf of this entity.

contact
acquaintance
friend
met
worker
colleague
resident
neighbor
child
parent
sibling
spouse
kin
muse
crush
date
sweetheart
me

Has the meaning defined in XFN. [XFN]

5.3.1.1 Conversion to vCard

Given a list of nodes nodes in a Document, a user agent must run the following algorithm to extract any vCard data represented by those nodes (only the first vCard is returned):

  1. If none of the nodes in nodes are items with the item type http://microformats.org/profile/hcard, then there is no vCard. Abort the algorithm, returning nothing.

  2. Let node be the first node in nodes that is an item with the item type http://microformats.org/profile/hcard.

  3. Let output be an empty string.

  4. Add a vCard line with the type "BEGIN" and the value "VCARD" to output.

  5. Add a vCard line with the type "PROFILE" and the value "VCARD" to output.

  6. Add a vCard line with the type "VERSION" and the value "4.0" to output.

  7. Add a vCard line with the type "SOURCE" and the result of escaping the vCard text string that is the document's URL as the value to output.

  8. If the title element is not null, add a vCard line with the type "NAME" and with the result of escaping the vCard text string obtained from the the title element's descendant text content as the value to output.

  9. Let sex be the empty string.

  10. Let gender-identity be the empty string.

  11. For each element element that is a property of the item node: for each name name in element's property names, run the following substeps:

    1. Let parameters be an empty set of name-value pairs.

    2. Run the appropriate set of substeps from the following list. The steps will set a variable value, which is used in the next step.

      If the property's value is an item subitem and name is n
      1. Let value be the empty string.

      2. Append to value the result of collecting the first vCard subproperty named family-name in subitem.

      3. Append a U+003B SEMICOLON character (;) to value.
      4. Append to value the result of collecting the first vCard subproperty named given-name in subitem.

      5. Append a U+003B SEMICOLON character (;) to value.
      6. Append to value the result of collecting the first vCard subproperty named additional-name in subitem.

      7. Append a U+003B SEMICOLON character (;) to value.
      8. Append to value the result of collecting the first vCard subproperty named honorific-prefix in subitem.

      9. Append a U+003B SEMICOLON character (;) to value.
      10. Append to value the result of collecting the first vCard subproperty named honorific-suffix in subitem.

      If the property's value is an item subitem and name is adr
      1. Let value be the empty string.

      2. Append to value the result of collecting vCard subproperties named post-office-box in subitem.

      3. Append a U+003B SEMICOLON character (;) to value.
      4. Append to value the result of collecting vCard subproperties named extended-address in subitem.

      5. Append a U+003B SEMICOLON character (;) to value.
      6. Append to value the result of collecting vCard subproperties named street-address in subitem.

      7. Append a U+003B SEMICOLON character (;) to value.
      8. Append to value the result of collecting the first vCard subproperty named locality in subitem.

      9. Append a U+003B SEMICOLON character (;) to value.
      10. Append to value the result of collecting the first vCard subproperty named region in subitem.

      11. Append a U+003B SEMICOLON character (;) to value.
      12. Append to value the result of collecting the first vCard subproperty named postal-code in subitem.

      13. Append a U+003B SEMICOLON character (;) to value.
      14. Append to value the result of collecting the first vCard subproperty named country-name in subitem.

      15. If there is a property named type in subitem, and the first such property has a value that is not an item and whose value consists only of ASCII alphanumerics, then add a parameter named "TYPE" whose value is the value of that property to parameters.

      If the property's value is an item subitem and name is org
      1. Let value be the empty string.

      2. Append to value the result of collecting the first vCard subproperty named organization-name in subitem.

      3. For each property named organization-unit in subitem, run the following steps:

        1. If the value of the property is an item, then skip this property.

        2. Append a U+003B SEMICOLON character (;) to value.

        3. Append the result of escaping the vCard text string given by the value of the property to value.

      If the property's value is an item subitem with the item type http://microformats.org/profile/hcard and name is related
      1. Let value be the empty string.

      2. If there is a property named url in subitem, and its element is a URL property element, then append the result of escaping the vCard text string given by the value of the first such property to value, and add a parameter with the name "VALUE" and the value "URI" to parameters.

      3. If there is a property named rel in subitem, and the first such property has a value that is not an item and whose value consists only of ASCII alphanumerics, then add a parameter named "RELATION" whose value is the value of that property to parameters.

      If the property's value is an item and name is none of the above
      1. Let value be the result of collecting the first vCard subproperty named value in subitem.

      2. If there is a property named type in subitem, and the first such property has a value that is not an item and whose value consists only of ASCII alphanumeric, then add a parameter named "TYPE" whose value is the value of that property to parameters.

      If the property's value is not an item and its name is sex

      If this is the first such property to be found, set sex to the property's value.

      If the property's value is not an item and its name is gender-identity

      If this is the first such property to be found, set gender-identity to the property's value.

      Otherwise (the property's value is not an item)
      1. Let value be the property's value.

      2. If element is one of the URL property elements, add a parameter with the name "VALUE" and the value "URI" to parameters.

      3. Otherwise, if name is bday or anniversary and the value is a valid date string, add a parameter with the name "VALUE" and the value "DATE" to parameters.

      4. Otherwise, if name is rev and the value is a valid global date and time string, add a parameter with the name "VALUE" and the value "DATE-TIME" to parameters.

      5. Prefix every U+005C REVERSE SOLIDUS character (\) in value with another U+005C REVERSE SOLIDUS character (\).

      6. Prefix every U+002C COMMA character (,) in value with a U+005C REVERSE SOLIDUS character (\).

      7. Unless name is geo, prefix every U+003B SEMICOLON character (;) in value with a U+005C REVERSE SOLIDUS character (\).

      8. Replace every U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF) in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL LETTER N character (n).

      9. Replace every remaining U+000D CARRIAGE RETURN (CR) or U+000A LINE FEED (LF) character in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL LETTER N character (n).

    3. Add a vCard line with the type name, the parameters parameters, and the value value to output.

  12. If either sex or gender-identity has a value that is not the empty string, add a vCard line with the type "GENDER" and the value consisting of the concatenation of sex, a U+003B SEMICOLON character (;), and gender-identity to output.

  13. Add a vCard line with the type "END" and the value "VCARD" to output.

When the above algorithm says that the user agent is to add a vCard line consisting of a type type, optionally some parameters, and a value value to a string output, it must run the following steps:

  1. Let line be an empty string.

  2. Append type, converted to ASCII uppercase, to line.

  3. If there are any parameters, then for each parameter, in the order that they were added, run these substeps:

    1. Append a U+003B SEMICOLON character (;) to line.

    2. Append the parameter's name to line.

    3. Append a U+003D EQUALS SIGN character (=) to line.

    4. Append the parameter's value to line.

  4. Append a U+003A COLON character (:) to line.

  5. Append value to line.

  6. Let maximum length be 75.

  7. While line's code point length is greater than maximum length:

    1. Append the first maximum length code points of line to output.

    2. Remove the first maximum length code points from line.

    3. Append a U+000D CARRIAGE RETURN character (CR) to output.

    4. Append a U+000A LINE FEED character (LF) to output.

    5. Append a U+0020 SPACE character to output.

    6. Let maximum length be 74.

  8. Append (what remains of) line to output.

  9. Append a U+000D CARRIAGE RETURN character (CR) to output.

  10. Append a U+000A LINE FEED character (LF) to output.

When the steps above require the user agent to obtain the result of collecting vCard subproperties named subname in subitem, the user agent must run the following steps:

  1. Let value be the empty string.

  2. For each property named subname in the item subitem, run the following substeps:

    1. If the value of the property is itself an item, then skip this property.

    2. If this is not the first property named subname in subitem (ignoring any that were skipped by the previous step), then append a U+002C COMMA character (,) to value.

    3. Append the result of escaping the vCard text string given by the value of the property to value.

  3. Return value.

When the steps above require the user agent to obtain the result of collecting the first vCard subproperty named subname in subitem, the user agent must run the following steps:

  1. If there are no properties named subname in subitem, then return the empty string.

  2. If the value of the first property named subname in subitem is an item, then return the empty string.

  3. Return the result of escaping the vCard text string given by the value of the first property named subname in subitem.

When the above algorithms say the user agent is to escape the vCard text string value, the user agent must use the following steps:

  1. Prefix every U+005C REVERSE SOLIDUS character (\) in value with another U+005C REVERSE SOLIDUS character (\).

  2. Prefix every U+002C COMMA character (,) in value with a U+005C REVERSE SOLIDUS character (\).

  3. Prefix every U+003B SEMICOLON character (;) in value with a U+005C REVERSE SOLIDUS character (\).

  4. Replace every U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF) in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL LETTER N character (n).

  5. Replace every remaining U+000D CARRIAGE RETURN (CR) or U+000A LINE FEED (LF) character in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL LETTER N character (n).

  6. Return the mutated value.

This algorithm can generate invalid vCard output, if the input does not conform to the rules described for the http://microformats.org/profile/hcard item type and defined property names.

5.3.1.2 Examples

This section is non-normative.

Here is a long example vCard for a fictional character called "Jack Bauer":

<section id="jack" itemscope itemtype="http://microformats.org/profile/hcard">
 <h1 itemprop="fn">
  <span itemprop="n" itemscope>
   <span itemprop="given-name">Jack</span>
   <span itemprop="family-name">Bauer</span>
  </span>
 </h1>
 <img itemprop="photo" alt="" src="jack-bauer.jpg">
 <p itemprop="org" itemscope>
  <span itemprop="organization-name">Counter-Terrorist Unit</span>
  (<span itemprop="organization-unit">Los Angeles Division</span>)
 </p>
 <p>
  <span itemprop="adr" itemscope>
   <span itemprop="street-address">10201 W. Pico Blvd.</span><br>
   <span itemprop="locality">Los Angeles</span>,
   <span itemprop="region">CA</span>
   <span itemprop="postal-code">90064</span><br>
   <span itemprop="country-name">United States</span><br>
  </span>
  <span itemprop="geo">34.052339;-118.410623</span>
 </p>
 <h2>Assorted Contact Methods</h2>
 <ul>
  <li itemprop="tel" itemscope>
   <span itemprop="value">+1 (310) 597 3781</span> <span itemprop="type">work</span>
   <meta itemprop="type" content="voice">
  </li>
  <li><a itemprop="url" href="https://en.wikipedia.org/wiki/Jack_Bauer">I'm on Wikipedia</a>
  so you can leave a message on my user talk page.</li>
  <li><a itemprop="url" href="http://www.jackbauerfacts.com/">Jack Bauer Facts</a></li>
  <li itemprop="email"><a href="mailto:j.bauer@la.ctu.gov.invalid">j.bauer@la.ctu.gov.invalid</a></li>
  <li itemprop="tel" itemscope>
   <span itemprop="value">+1 (310) 555 3781</span> <span>
   <meta itemprop="type" content="cell">mobile phone</span>
  </li>
 </ul>
 <ins datetime="2008-07-20 21:00:00+01:00">
  <meta itemprop="rev" content="2008-07-20 21:00:00+01:00">
  <p itemprop="tel" itemscope><strong>Update!</strong>
  My new <span itemprop="type">home</span> phone number is
  <span itemprop="value">01632 960 123</span>.</p>
 </ins>
</section>

The odd line wrapping is needed because newlines are meaningful in microdata: newlines would be preserved in a conversion to, for example, the vCard format.

This example shows a site's contact details (using the address element) containing an address with two street components:

<address itemscope itemtype="http://microformats.org/profile/hcard">
 <strong itemprop="fn"><span itemprop="n" itemscope><span itemprop="given-name">Alfred</span>
 <span itemprop="family-name">Person</span></span></strong> <br>
 <span itemprop="adr" itemscope>
  <span itemprop="street-address">1600 Amphitheatre Parkway</span> <br>
  <span itemprop="street-address">Building 43, Second Floor</span> <br>
  <span itemprop="locality">Mountain View</span>,
   <span itemprop="region">CA</span> <span itemprop="postal-code">94043</span>
 </span>
</address>

The vCard vocabulary can be used to just mark up people's names:

<span itemscope itemtype="http://microformats.org/profile/hcard"
><span itemprop=fn><span itemprop="n" itemscope><span itemprop="given-name"
>George</span> <span itemprop="family-name">Washington</span></span
></span></span>

This creates a single item with a two name-value pairs, one with the name "fn" and the value "George Washington", and the other with the name "n" and a second item as its value, the second item having the two name-value pairs "given-name" and "family-name" with the values "George" and "Washington" respectively. This is defined to map to the following vCard:

BEGIN:VCARD
PROFILE:VCARD
VERSION:4.0
SOURCE:document's address
FN:George Washington
N:Washington;George;;;
END:VCARD

5.3.2 vEvent

An item with the item type http://microformats.org/profile/hcalendar#vevent represents an event.

This vocabulary does not support global identifiers for items.

The following are the type's defined property names. They are based on the vocabulary defined in Internet Calendaring and Scheduling Core Object Specification (iCalendar), where more information on how to interpret the values can be found. [RFC5545]

Only the parts of the iCalendar vocabulary relating to events are used here; this vocabulary cannot express a complete iCalendar instance.

attach

Gives the address of an associated document for the event.

The value must be an absolute URL.

Any number of properties with the name attach may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

categories

Gives the name of a category or tag that the event could be classified as.

The value must be text.

Any number of properties with the name categories may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

class

Gives the access classification of the information regarding the event.

The value must be text with one of the following values:

This is merely advisory and cannot be considered a confidentiality measure.

A single property with the name class may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

comment

Gives a comment regarding the event.

The value must be text.

Any number of properties with the name comment may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

description

Gives a detailed description of the event.

The value must be text.

A single property with the name description may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

geo

Gives the geographical position of the event.

The value must be text and must match the following syntax:

  1. Optionally, either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character (-).
  2. One or more ASCII digits.
  3. Optionally*, a U+002E FULL STOP character (.) followed by one or more ASCII digits.
  4. A U+003B SEMICOLON character (;).
  5. Optionally, either a U+002B PLUS SIGN character (+) or a U+002D HYPHEN-MINUS character (-).
  6. One or more ASCII digits.
  7. Optionally*, a U+002E FULL STOP character (.) followed by one or more ASCII digits.

The optional components marked with an asterisk (*) should be included, and should have six digits each.

The value specifies latitude and longitude, in that order (i.e., "LAT LON" ordering), in decimal degrees. The longitude represents the location east and west of the prime meridian as a positive or negative real number, respectively. The latitude represents the location north and south of the equator as a positive or negative real number, respectively.

A single property with the name geo may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

location

Gives the location of the event.

The value must be text.

A single property with the name location may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

resources

Gives a resource that will be needed for the event.

The value must be text.

Any number of properties with the name resources may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

status

Gives the confirmation status of the event.

The value must be text with one of the following values:

A single property with the name status may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

summary

Gives a short summary of the event.

The value must be text.

User agents should replace U+000A LINE FEED (LF) characters in the value by U+0020 SPACE characters when using the value.

A single property with the name summary may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

dtend

Gives the date and time by which the event ends.

If the property with the name dtend is present within an item with the type http://microformats.org/profile/hcalendar#vevent that has a property with the name dtstart whose value is a valid date string, then the value of the property with the name dtend must be text that is a valid date string also. Otherwise, the value of the property must be text that is a valid global date and time string.

In either case, the value be later in time than the value of the dtstart property of the same item.

The time given by the dtend property is not inclusive. For day-long events, therefore, the dtend property's value will be the day after the end of the event.

A single property with the name dtend may be present within each item with the type http://microformats.org/profile/hcalendar#vevent, so long as that http://microformats.org/profile/hcalendar#vevent does not have a property with the name duration.

dtstart

Gives the date and time at which the event starts.

The value must be text that is either a valid date string or a valid global date and time string.

Exactly one property with the name dtstart must be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

duration

Gives the duration of the event.

The value must be text that is a valid vevent duration string.

The duration represented is the sum of all the durations represented by integers in the value.

A single property with the name duration may be present within each item with the type http://microformats.org/profile/hcalendar#vevent, so long as that http://microformats.org/profile/hcalendar#vevent does not have a property with the name dtend.

transp

Gives whether the event is to be considered as consuming time on a calendar, for the purpose of free-busy time searches.

The value must be text with one of the following values:

A single property with the name transp may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

contact

Gives the contact information for the event.

The value must be text.

Any number of properties with the name contact may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

url

Gives a URL for the event.

The value must be an absolute URL.

A single property with the name url may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

uid

Gives a globally unique identifier corresponding to the event.

The value must be text.

A single property with the name uid may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

exdate

Gives a date and time at which the event does not occur despite the recurrence rules.

The value must be text that is either a valid date string or a valid global date and time string.

Any number of properties with the name exdate may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

rdate

Gives a date and time at which the event recurs.

The value must be text that is one of the following:

Any number of properties with the name rdate may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

rrule

Gives a rule for finding dates and times at which the event occurs.

The value must be text that matches the RECUR value type defined in iCalendar. [RFC5545]

A single property with the name rrule may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

created

Gives the date and time at which the event information was first created in a calendaring system.

The value must be text that is a valid global date and time string.

A single property with the name created may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

last-modified

Gives the date and time at which the event information was last modified in a calendaring system.

The value must be text that is a valid global date and time string.

A single property with the name last-modified may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

sequence

Gives a revision number for the event information.

The value must be text that is a valid non-negative integer.

A single property with the name sequence may be present within each item with the type http://microformats.org/profile/hcalendar#vevent.

A string is a valid vevent duration string if it matches the following pattern:

  1. A U+0050 LATIN CAPITAL LETTER P character (P).
  2. One of the following:
5.3.2.1 Conversion to iCalendar

Given a list of nodes nodes in a Document, a user agent must run the following algorithm to extract any vEvent data represented by those nodes:

  1. If none of the nodes in nodes are items with the type http://microformats.org/profile/hcalendar#vevent, then there is no vEvent data. Abort the algorithm, returning nothing.

  2. Let output be an empty string.

  3. Add an iCalendar line with the type "BEGIN" and the value "VCALENDAR" to output.

  4. Add an iCalendar line with the type "PRODID" and the value equal to a user-agent-specific string representing the user agent to output.

  5. Add an iCalendar line with the type "VERSION" and the value "2.0" to output.

  6. For each node node in nodes that is an item with the type http://microformats.org/profile/hcalendar#vevent, run the following steps:

    1. Add an iCalendar line with the type "BEGIN" and the value "VEVENT" to output.

    2. Add an iCalendar line with the type "DTSTAMP" and a value consisting of an iCalendar DATE-TIME string representing the current date and time, with the annotation "VALUE=DATE-TIME", to output. [RFC5545]

    3. For each element element that is a property of the item node: for each name name in element's property names, run the appropriate set of substeps from the following list:

      If the property's value is an item

      Skip the property.

      If the property is dtend
      If the property is dtstart
      If the property is exdate
      If the property is rdate
      If the property is created
      If the property is last-modified

      Let value be the result of stripping all U+002D HYPHEN-MINUS (-) and U+003A COLON (:) characters from the property's value.

      If the property's value is a valid date string then add an iCalendar line with the type name and the value value to output, with the annotation "VALUE=DATE".

      Otherwise, if the property's value is a valid global date and time string then add an iCalendar line with the type name and the value value to output, with the annotation "VALUE=DATE-TIME".

      Otherwise skip the property.

      Otherwise

      Add an iCalendar line with the type name and the property's value to output.

    4. Add an iCalendar line with the type "END" and the value "VEVENT" to output.

  7. Add an iCalendar line with the type "END" and the value "VCALENDAR" to output.

When the above algorithm says that the user agent is to add an iCalendar line consisting of a type type, a value value, and optionally an annotation, to a string output, it must run the following steps:

  1. Let line be an empty string.

  2. Append type, converted to ASCII uppercase, to line.

  3. If there is an annotation:

    1. Append a U+003B SEMICOLON character (;) to line.

    2. Append the annotation to line.

  4. Append a U+003A COLON character (:) to line.

  5. Prefix every U+005C REVERSE SOLIDUS character (\) in value with another U+005C REVERSE SOLIDUS character (\).

  6. Prefix every U+002C COMMA character (,) in value with a U+005C REVERSE SOLIDUS character (\).

  7. Prefix every U+003B SEMICOLON character (;) in value with a U+005C REVERSE SOLIDUS character (\).

  8. Replace every U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF) in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL LETTER N character (n).

  9. Replace every remaining U+000D CARRIAGE RETURN (CR) or U+000A LINE FEED (LF) character in value with a U+005C REVERSE SOLIDUS character (\) followed by a U+006E LATIN SMALL LETTER N character (n).

  10. Append value to line.

  11. Let maximum length be 75.

  12. While line's code point length is greater than maximum length:

    1. Append the first maximum length code points of line to output.

    2. Remove the first maximum length code points from line.

    3. Append a U+000D CARRIAGE RETURN character (CR) to output.

    4. Append a U+000A LINE FEED character (LF) to output.

    5. Append a U+0020 SPACE character to output.

    6. Let maximum length be 74.

  13. Append (what remains of) line to output.

  14. Append a U+000D CARRIAGE RETURN character (CR) to output.

  15. Append a U+000A LINE FEED character (LF) to output.

This algorithm can generate invalid iCalendar output, if the input does not conform to the rules described for the http://microformats.org/profile/hcalendar#vevent item type and defined property names.

5.3.2.2 Examples

This section is non-normative.

Here is an example of a page that uses the vEvent vocabulary to mark up an event:

<body itemscope itemtype="http://microformats.org/profile/hcalendar#vevent">
 ...
 <h1 itemprop="summary">Bluesday Tuesday: Money Road</h1>
 ...
 <time itemprop="dtstart" datetime="2009-05-05T19:00:00Z">May 5th @ 7pm</time>
 (until <time itemprop="dtend" datetime="2009-05-05T21:00:00Z">9pm</time>)
 ...
 <a href="http://livebrum.co.uk/2009/05/05/bluesday-tuesday-money-road"
    rel="bookmark" itemprop="url">Link to this page</a>
 ...
 <p>Location: <span itemprop="location">The RoadHouse</span></p>
 ...
 <p><input type=button value="Add to Calendar"
           onclick="location = getCalendar(this)"></p>
 ...
 <meta itemprop="description" content="via livebrum.co.uk">
</body>

The getCalendar() function is left as an exercise for the reader.

The same page could offer some markup, such as the following, for copy-and-pasting into blogs:

<div itemscope itemtype="http://microformats.org/profile/hcalendar#vevent">
 <p>I'm going to
 <strong itemprop="summary">Bluesday Tuesday: Money Road</strong>,
 <time itemprop="dtstart" datetime="2009-05-05T19:00:00Z">May 5th at 7pm</time>
 to <time itemprop="dtend" datetime="2009-05-05T21:00:00Z">9pm</time>,
 at <span itemprop="location">The RoadHouse</span>!</p>
 <p><a href="http://livebrum.co.uk/2009/05/05/bluesday-tuesday-money-road"
       itemprop="url">See this event on livebrum.co.uk</a>.</p>
 <meta itemprop="description" content="via livebrum.co.uk">
</div>

5.3.3 Licensing works

An item with the item type http://n.whatwg.org/work represents a work (e.g. an article, an image, a video, a song, etc). This type is primarily intended to allow authors to include licensing information for works.

The following are the type's defined property names.

work

Identifies the work being described.

The value must be an absolute URL.

Exactly one property with the name work must be present within each item with the type http://n.whatwg.org/work.

title

Gives the name of the work.

A single property with the name title may be present within each item with the type http://n.whatwg.org/work.

author

Gives the name or contact information of one of the authors or creators of the work.

The value must be either an item with the type http://microformats.org/profile/hcard, or text.

Any number of properties with the name author may be present within each item with the type http://n.whatwg.org/work.

license

Identifies one of the licenses under which the work is available.

The value must be an absolute URL.

Any number of properties with the name license may be present within each item with the type http://n.whatwg.org/work.

5.3.3.1 Examples

This section is non-normative.

This example shows an embedded image entitled My Pond, licensed under the Creative Commons Attribution-Share Alike 4.0 International License and the MIT license simultaneously.

<figure itemscope itemtype="http://n.whatwg.org/work">
 <img itemprop="work" src="mypond.jpeg">
 <figcaption>
  <p><cite itemprop="title">My Pond</cite></p>
  <p><small>Licensed under the <a itemprop="license"
  href="https://creativecommons.org/licenses/by-sa/4.0/">Creative
  Commons Attribution-Share Alike 4.0 International License</a>
  and the <a itemprop="license"
  href="http://www.opensource.org/licenses/mit-license.php">MIT
  license</a>.</small>
 </figcaption>
</figure>

5.4 Converting HTML to other formats

5.4.1 JSON

Given a list of nodes nodes in a Document, a user agent must run the following algorithm to extract the microdata from those nodes into a JSON form:

  1. Let result be an empty object.

  2. Let items be an empty array.

  3. For each node in nodes, check if the element is a top-level microdata item, and if it is then get the object for that element and add it to items.

  4. Add an entry to result called "items" whose value is the array items.

  5. Return the result of serializing result to JSON in the shortest possible way (meaning no whitespace between tokens, no unnecessary zero digits in numbers, and only using Unicode escapes in strings for characters that do not have a dedicated escape sequence), and with a lowercase "e" used, when appropriate, in the representation of any numbers. [JSON]

This algorithm returns an object with a single property that is an array, instead of just returning an array, so that it is possible to extend the algorithm in the future if necessary.

When the user agent is to get the object for an item item, optionally with a list of elements memory, it must run the following substeps:

  1. Let result be an empty object.

  2. If no memory was passed to the algorithm, let memory be an empty list.

  3. Add item to memory.

  4. If the item has any item types, add an entry to result called "type" whose value is an array listing the item types of item, in the order they were specified on the itemtype attribute.

  5. If the item has a global identifier, add an entry to result called "id" whose value is the global identifier of item.

  6. Let properties be an empty object.

  7. For each element element that has one or more property names and is one of the properties of the item item, in the order those elements are given by the algorithm that returns the properties of an item, run the following substeps:

    1. Let value be the property value of element.

    2. If value is an item, then: If value is in memory, then let value be the string "ERROR". Otherwise, get the object for value, passing a copy of memory, and then replace value with the object returned from those steps.

    3. For each name name in element's property names, run the following substeps:

      1. If there is no entry named name in properties, then add an entry named name to properties whose value is an empty array.

      2. Append value to the entry named name in properties.

  8. Add an entry to result called "properties" whose value is the object properties.

  9. Return result.

For example, take this markup:

<!DOCTYPE HTML>
<html lang="en">
<title>My Blog</title>
<article itemscope itemtype="http://schema.org/BlogPosting">
 <header>
  <h1 itemprop="headline">Progress report</h1>
  <p><time itemprop="datePublished" datetime="2013-08-29">today</time></p>
  <link itemprop="url" href="?comments=0">
 </header>
 <p>All in all, he's doing well with his swim lessons. The biggest thing was he had trouble
 putting his head in, but we got it down.</p>
 <section>
  <h1>Comments</h1>
  <article itemprop="comment" itemscope itemtype="http://schema.org/UserComments" id="c1">
   <link itemprop="url" href="#c1">
   <footer>
    <p>Posted by: <span itemprop="creator" itemscope itemtype="http://schema.org/Person">
     <span itemprop="name">Greg</span>
    </span></p>
    <p><time itemprop="commentTime" datetime="2013-08-29">15 minutes ago</time></p>
   </footer>
   <p>Ha!</p>
  </article>
  <article itemprop="comment" itemscope itemtype="http://schema.org/UserComments" id="c2">
   <link itemprop="url" href="#c2">
   <footer>
    <p>Posted by: <span itemprop="creator" itemscope itemtype="http://schema.org/Person">
     <span itemprop="name">Charlotte</span>
    </span></p>
    <p><time itemprop="commentTime" datetime="2013-08-29">5 minutes ago</time></p>
   </footer>
   <p>When you say "we got it down"...</p>
  </article>
 </section>
</article>

It would be turned into the following JSON by the algorithm above (supposing that the page's URL was https://blog.example.com/progress-report):

{
  "items": [
    {
      "type": [ "http://schema.org/BlogPosting" ],
      "properties": {
        "headline": [ "Progress report" ],
        "datePublished": [ "2013-08-29" ],
        "url": [ "https://blog.example.com/progress-report?comments=0" ],
        "comment": [
          {
            "type": [ "http://schema.org/UserComments" ],
            "properties": {
              "url": [ "https://blog.example.com/progress-report#c1" ],
              "creator": [
                {
                  "type": [ "http://schema.org/Person" ],
                  "properties": {
                    "name": [ "Greg" ]
                  }
                }
              ],
              "commentTime": [ "2013-08-29" ]
            }
          },
          {
            "type": [ "http://schema.org/UserComments" ],
            "properties": {
              "url": [ "https://blog.example.com/progress-report#c2" ],
              "creator": [
                {
                  "type": [ "http://schema.org/Person" ],
                  "properties": {
                    "name": [ "Charlotte" ]
                  }
                }
              ],
              "commentTime": [ "2013-08-29" ]
            }
          }
        ]
      }
    }
  ]
}

6 用户交互

6.1 hidden 属性

所有 HTML 元素 都可以有 hidden 内容属性。hidden 属性是一个 布尔属性。 在元素上指定时,它表示该元素还没有(或不再)与当前页面状态直接相关。 或用来声明页面的其他部分会复用这部分内容,而不是让用户直接访问。 用户代理不应渲染设置了 hidden 属性的元素。 这一要求可以直接从样式层实现。例如,HTML+CSS 用户代理可以 使用在渲染一节中建议的规则 实现这些要求。

因为这个属性通常使用 CSS 实现,可能会被 CSS 覆盖。 例如,一个规则在所有元素上应用 'display: block',就会移除 hidden 属性的效果。 因此作者在编写样式表时必须小心,确保该属性的样式仍然符合预期。

在下面的例子中,该属性用于在用户未登录时隐藏 Web 游戏的主屏幕:

  <h1>The Example Game</h1>
  <section id="login">
   <h2>Login</h2>
   <form>
    ...
    <!-- calls login() once the user's credentials have been checked -->
   </form>
   <script>
    function login() {
      // switch screens
      document.getElementById('login').hidden = true;
      document.getElementById('game').hidden = false;
    }
   </script>
  </section>
  <section id="game" hidden>
   ...
  </section>

hidden 属性不得用于在其他显示中隐藏可以显示给用户的内容。 例如,使用 hidden 来隐藏选项卡中的面板是不正确的, 因为选项卡接口仅仅是一种溢出式显示 — 直接把所有表单控件显示在一个大页面上并配一个滚动条可以一样好地呈现。 使用该属性只在某个显示终端上隐藏内容是一样的不正确 — 如果某个元素被标记为 hidden,它就在所有显示终端上都隐藏,比如说包括屏幕阅读器。

自己不是 hidden 的元素不得 超链接hidden 的元素。 没有 hiddenlabeloutput 元素的 for 属性一样不可引用 hidden 的元素。 在两种场景中,这样的引用会导致用户困惑。

但是其他上下文中的元素和脚本可以引用 hidden 的元素。

例如,使用 href 属性链接到标记为 hidden 的小节可能是不正确的。 因为内容本身不可用或不相关,所以没有理由链接到它。

但是,使用 ARIA aria-describedby 属性引用 hidden 的描述是可以的。 这时隐藏描述意味着它们自己没有用处,它们只在被它们所描述的图片引用时才有用。

类似地,一个有 hidden 属性的 canvas 元素, 可以被一个图形引擎脚本用来作为屏幕外的缓冲,一个表单控件可以通过它的 form 属性引用一个隐藏的 form 元素。

hidden 属性隐藏的部分中的元素仍然是活跃的。 例如,这些部分中的脚本和表单控件仍然会执行和提交。只有它们对用户的显示变了。

HTMLElement/hidden

Support in all current engines.

Firefox1+Safari5.1+Chrome6+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android12+

hidden IDL 属性必须 反映 同名内容属性。

6.2 Inert subtrees

This section does not define or create any content attribute named "inert". This section merely defines an abstract concept of inertness.

A node (in particular elements and text nodes) can be marked as inert. When a node is inert, then the user agent must act as if the node was absent for the purposes of targeting user interaction events, may ignore the node for the purposes of find-in-page, and may prevent the user from selecting text in that node. User agents should allow the user to override the restrictions on search and text selection, however.

For example, consider a page that consists of just a single inert paragraph positioned in the middle of a body. If a user moves their pointing device from the body over to the inert paragraph and clicks on the paragraph, no mouseover event would be fired, and the mousemove and click events would be fired on the body element rather than the paragraph.

When a node is inert, it generally cannot be focused. Inert nodes that are commands will also get disabled.

While a browsing context container is marked as inert, its nested browsing context's active document, and all nodes in that Document, must be marked as inert.

An element is expressly inert if it is inert and its node document is not inert.

A Document document is blocked by a modal dialog subject if subject is the topmost dialog element in document's top layer. While document is so blocked, every node that is connected to document, with the exception of the subject element and its shadow-including descendants, must be marked inert. (The elements excepted by this paragraph can additionally be marked inert through other means; being part of a modal dialog does not "protect" a node from being marked inert.)

The dialog element's showModal() method causes this mechanism to trigger, by adding the dialog element to its node document's top layer.

6.3 Tracking user activation

To prevent abuse of certain APIs that could be annoying to users (e.g., opening popups or vibrating phones), user agents allow these APIs only when the user is actively interacting with the web page or has interacted with the page at least once. This "active interaction" state is maintained through the mechanisms defined in this section.

6.3.1 Data model

For the purpose of tracking user activation, each Window W has a last activation timestamp. This is a number indicating the last time W got an activation notification. It corresponds to a DOMHighResTimeStamp value except for two cases: positive infinity indicates that W has never been activated, while negative infinity indicates that a user activation-gated API has consumed the last user activation of W. The initial value is positive infinity.

A user agent also defines a transient activation duration, which is a constant number indicating how long a user activation is available for certain user activation-gated APIs (e.g., for opening popups).

The transient activation duration is expected be at most a few seconds, so that the user can possibly perceive the link between an interaction with the page and the page calling the activation-gated API.

These two values imply two boolean user activation states for W:

Sticky activation

When the current high resolution time is greater than or equal to the last activation timestamp in W, W is said to have sticky activation.

This is W's historical activation state, indicating whether the user has ever interacted in W. It starts false, then changes to true (and never changes back to false) when W gets the very first activation notification.

Transient activation

When the current high resolution time is greater than or equal to the last activation timestamp in W, and less than the last activation timestamp in W plus the transient activation duration, then W is said to have transient activation.

This is W's current activation state, indicating whether the user has interacted in W recently. This starts with a false value, and remains true for a limited time after every activation notification W gets.

The transient activation state is considered expired if it becomes false because the transient activation duration time has elapsed since the last user activation. Note that it can become false even before the expiry time through an activation consumption.

6.3.2 Processing model

When a user interaction in a browsing context B causes firing of an activation triggering input event in B's active document D, the user agent must perform the following activation notification steps before dispatching the event:

  1. Let browsingContexts be a list consisting of:

  2. Let windows be the list of Window objects constructed by taking the active window of each item in browsingContexts.

  3. For each window in windows, set window's last activation timestamp to the current high resolution time.

An activation triggering input event is any event whose isTrusted attribute is true and whose type is one of:

The event set is inconsistent across major browsers. See issue #3849.

Activation consuming APIs defined in this and other specifications can consume user activation by performing the following steps, given a Window W:

  1. If W's browsing context is null, then return.

  2. Let top be W's browsing context's top-level browsing context.

  3. Let browsingContexts be the list of the descendant browsing contexts of top's active document.

  4. Append top to browsingContexts.

  5. Let windows be the list of Window objects constructed by taking the active window of each item in browsingContexts.

  6. For each window in windows, if window's last activation timestamp is not positive infinity, then set window's last activation timestamp to negative infinity.

The spec is not clear about how to traverse a tree of documents. See issue #5020.

Note the asymmetry in the sets of browsing contexts in the page that are affected by an activation notification vs an activation consumption: an activation consumption changes (to false) the transient activation states for all browsing contexts in the page, but an activation notification changes (to true) the states for a subset of those browsing contexts. The exhaustive nature of consumption here is deliberate: it prevents malicious sites from making multiple calls to an activation consuming API from a single user activation (possibly by exploiting a deep hierarchy of iframes).

6.3.3 APIs gated by user activation

APIs that are dependent on user activation are classified into three different levels. The levels are as follows, sorted by their "strength of dependence" on user activation (from weakest to strongest):

Sticky activation-gated APIs

These APIs require the sticky activation state to be true, so they are blocked until the very first user activation.

Transient activation-gated APIs

These APIs require the transient activation state to be true, but they don't consume it, so multiple calls are allowed per user activation until the transient state expires.

Transient activation-consuming APIs

These APIs require the transient activation state to be true, and they consume user activation in each call to prevent multiple calls per user activation.

6.4 Activation behavior of elements

Certain elements in HTML have an activation behavior, which means that the user can activate them. This is always caused by a click event.

The user agent should allow the user to manually trigger elements that have an activation behavior, for instance using keyboard or voice input, or through mouse clicks. When the user triggers an element with a defined activation behavior in a manner other than clicking it, the default action of the interaction event must be to fire a click event at the element.

element . click()

HTMLElement/click

Support in all current engines.

Firefox3+Safari6+Chrome9+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+

Acts as if the element was clicked.

Each element has an associated click in progress flag, which is initially unset.

The click() method must run the following steps:

  1. If this element is a form control that is disabled, then return.

  2. If this element's click in progress flag is set, then return.

  3. Set this element's click in progress flag.

  4. Fire a synthetic mouse event named click at this element, with the not trusted flag set.

  5. Unset this element's click in progress flag.

6.5 焦点

6.5.1 概述

This section is non-normative.

HTML UI 通常包括多个交互组件,比如表单控件,可滚动区域,超链接,对话框,浏览器选项卡等等。 这些组件互相嵌套,一些(比如浏览器选项卡、对话框)包含着另外一些组件(例如超链接、表单控件)。

当使用键盘与接口交互时,按键输入来自系统,通过可交互的组件层级,到达活跃组件,这个组件称为 focused

考虑一个 HTML 应用,在图形环境下运行着一个浏览器选项卡。 假设这个应用有一个页面包含一些文本控件和链家,现在正在显示一个模态对话框, 这个对话框又有一个文本控件和一个按钮。

在这个场景中,可获得焦点的组件层级包括浏览器窗口(它的浏览器选项卡可能包含一个 HTML 应用), 选项卡自己可能包含各种链接和文本控件,以及那个对话框。这个对话框包含文本控件和按钮。

这个例子中如果 focus 的组件是对话框中的文本控件, 那么键盘输入会从图形系统到 ① Web 浏览器,然后到 ② 选项卡, 然后到 ③ 对话框,最后到达 ④ 文本控件。

键盘 事件 的目标总是这个 focused 元素。

6.5.2 数据模型

术语 可聚焦区域 用来指可以成为键盘输入目标的 UI 区域。 可聚焦区域可以是元素、元素的一部分,或者用户代理管理的其他区域。

每个 可聚焦区域 有一个 DOM 锚点,这是一个 Node 对象,表示 DOM 中 可聚焦区域 的位置。 当 可聚焦区域 自己是一个 Node 时, 它就是自己的 DOM 锚点。) 在一些 API 中,当没有其他 DOM 对象表示 可聚焦区域 时, DOM 锚点 被用作 可聚焦区域 的替代品。

下面的表格描述了什么对象可以成为 可聚焦区域。 左侧的单元格描述了可以成为 可聚焦区域 的对象; 右侧的单元格描述了那些元素的 DOM 锚点。 (横跨两列的单元格是非规范描述的例子)

可聚焦区域 DOM 锚点
示例
满足下面所有条件的元素: 元素自己。

iframe<input type=text>,有时还包括 <a href=""> (取决于平台惯例)。

在与 正在被渲染的 且没有 明确不活动的img 元素关联的 图片 maparea 元素的形状。 img 元素

下面的例子中,area 元素创建了两个形状,每个图片一个。 第一个形状的 DOM 锚点 是第一个 img 元素, 第二个形状的 DOM 锚点 是第二个 img 元素。

<map id=wallmap><area alt="Enter Door" coords="10,10,100,200" href="door.html"></map>
...
<img src="images/innerwall.jpeg" alt="There is a white wall here, with a door." usemap="#wallmap">
...
<img src="images/outerwall.jpeg" alt="There is a red wall here, with a door." usemap="#wallmap">
用户代理提供的 正在被渲染 且没有 真正禁用明确不活动的 元素的子组件 可聚焦区域 是这些子组件的元素

video 元素的 UI 控件<input type=number> 的旋钮控件的上下按钮, <input type=range multiple> 中的两个范围控件, details 元素的渲染结果中可以使用键盘输入使元素打开和关闭的部分。

正在被渲染 且没有 明确不活动的 元素的可滚动区域。 为其创建可滚动区域的滚动框的元素。

CSS 'overflow' 属性的 'scroll' 值就创建了一个可滚动区域

有非空 浏览上下文 且不是 不活动的 Document视口 为其创建 视口Document

iframe 的内容

任何由用户代理确定的属于可聚焦区域的其他元素或元素的一部分,尤其是提高可访问性或更好地匹配平台惯例的那些元素 该元素本身

用户代理可以把所有列表项标志变成 可顺序聚焦 的,这样用户可以更容易地在列表中导航。

类似地,用户代理可以让所有有 title 属性的元素可顺序聚焦,这样就可以访问它们的提示信息了。

浏览上下文容器 (例如一个 iframe) 是一个 可聚焦区域,但路由到 浏览上下文容器 的键盘事件会立即路由到 嵌套浏览上下文活动文档。 类似地,在顺序焦点导航中,浏览 浏览上下文容器 本质上仅充当其 嵌套浏览上下文活动文档 的占位符。


每个 Document 都有一个 可聚焦区域 被指定为 文档的焦点区域。 被指定的具体是哪个控件会随时间变化,取决于本规范中的算法。 如果 Document 没有 可聚焦区域, 它就没有 焦点区域

任意一刻顶级浏览上下文 topLevelBC的当前焦点区域,由以下算法返回:

  1. candidatetopLevelBC活动文档

  2. 只要 candidate活动区域 为 有着非空 嵌套浏览环境浏览环境容器 时: 设置 candidate 为这个 浏览环境容器嵌套浏览环境活动文档

  3. 如果 candidate聚焦区域 非空, 设置 candidatecandidate聚焦区域

  4. 返回 candidate

可聚焦区域DOM 锚点 的元素 获得焦点 是指 可聚焦区域 成为了 顶级浏览上下文的当前焦点区域。 当一个元素是 顶级浏览上下文的当前焦点区域可聚焦区域DOM 锚点 时,它就是 focused

可聚焦区域 subject焦点链 是这样构造的有序列表:

  1. current objectsubject

  2. output 为一个空列表。

  3. Loop:把 current object 添加到 output

  4. 如果 current object 是一个 area 元素的形状,就把那个 area 元素添加到 output

    否则,如果 current object可聚焦区域 元素, 且它的 DOM 锚点 不是 current object 自己,把那个 DOM 锚点 元素添加到 output

  5. 如果 current object 是一个 浏览上下文子浏览环境Document, 设置 current objectcurrent object浏览环境容器 并返回到标签为 loop 的步骤。

  6. 返回 output

    这个链条从 subject 开始 (如果 subject 是或者可以是 顶级浏览上下文的当前焦点区域), 一直向上到 顶级浏览上下文Document

All elements that are focusable areas are said to be focusable.

There are two special types of focusability for focusable areas:

Elements which are not focusable are not focusable areas, and thus not sequentially focusable and not click focusable.

Being focusable is a statement about whether an element can be focused programmatically, e.g. via the focus() method or autofocus attribute. In contrast, sequentially focusable and click focusable govern how the user agent responds to user interaction: respectively, to sequential focus navigation and as activation behavior.

The user agent might determine that an element is not sequentially focusable even if it is focusable and is included in its Document's sequential focus navigation order, according to user preferences. For example, macOS users can set the user agent to skip non-form control elements, or can skip links when doing sequential focus navigation with just the Tab key (as opposed to using both the Option and Tab keys).

Similarly, the user agent might determine that an element is not click focusable even if it is focusable. For example, in some user agents, clicking on a non-editable form control does not focus it, i.e. the user agent has determined that such controls are not click focusable.

Thus, an element can be focusable, but neither sequentially focusable nor click focusable. For example, in some user agents, a non-editable form-control with a negative-integer tabindex value would not be focusable via user interaction, only via programmatic APIs.

When a user activates a click focusable focusable area, the user agent must run the focusing steps on the focusable area with focus trigger set to "click".

Note that focusing is not an activation behavior, i.e. calling the click() method on an element or dispatching a synthetic click event on it won't cause the element to get focused.


A node is a focus navigation scope owner if it is a document, a shadow host or a slot.

Each focus navigation scope owner has a focus navigation scope, which is a list of elements. Its contents are determined as follows:

Every element element has an associated focus navigation owner, which is either null or a focus navigation scope owner. It is determined by the following algorithm:

  1. If element's parent is null, then return null.

  2. If element's parent is a shadow host, then return element's assigned slot.

  3. If element's parent is a shadow root, then return the parent's host.

  4. If element's parent is the document element, then return the parent's node document.

  5. Return element's parent's associated focus navigation owner.

Then, the contents of a given focus navigation scope owner owner's focus navigation scope are all elements whose associated focus navigation owner is owner.

The order of elements within a focus navigation scope does not impact any of the algorithms in this specification. Ordering only becomes important for the tabindex-ordered focus navigation scope and flattened tabindex-ordered focus navigation scope concepts defined below.

A tabindex-ordered focus navigation scope is a list of focusable areas and focus navigation scope owners. Every focus navigation scope owner owner has tabindex-ordered focus navigation scope, whose contents are determined as follows:

The order within a tabindex-ordered focus navigation scope is determined by each element's tabindex value, as described in the section below.

The rules there do not give a precise ordering, as they are composed mostly of "should" statements and relative orderings.

A flattened tabindex-ordered focus navigation scope is a list of focusable areas. Every focus navigation scope owner owner owns a distinct flattened tabindex-ordered focus navigation scope, whose contents are determined by the following algorithm:

  1. Let result be a clone of owner's tabindex-ordered focus navigation scope.

  2. For each item of result:

    1. If item is not a focus navigation scope owner, then continue.

    2. If item is not a focusable area, then replace item with all of the items in item's flattened tabindex-ordered focus navigation scope.

    3. Otherwise, insert the contents of item's flattened tabindex-ordered focus navigation scope after item.

6.5.3 The tabindex attribute

Global_attributes/tabindex

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

The tabindex content attribute allows authors to make an element and regions that have the element as its DOM anchor be focusable areas, allow or prevent them from being sequentially focusable, and determine their relative ordering for sequential focus navigation.

The name "tab index" comes from the common use of the Tab key to navigate through the focusable elements. The term "tabbing" refers to moving forward through sequentially focusable focusable areas.

The tabindex attribute, if specified, must have a value that is a valid integer. Positive numbers specify the relative position of the element's focusable areas in the sequential focus navigation order, and negative numbers indicate that the control is not sequentially focusable.

Developers should use caution when using values other than 0 or −1 for their tabindex attributes as this is complicated to do correctly.

The following provides a non-normative summary of the behaviors of the possible tabindex attribute values. The below processing model gives the more precise rules.

omitted (or non-integer values)
The user agent will decide whether the element is focusable, and if it is, whether it is sequentially focusable or click focusable (or both).
−1 (or other negative integer values)
Causes the element to be focusable, and indicates that the author would prefer the element to be click focusable but not sequentially focusable. The user agent might ignore this preference for click and sequential focusability, e.g., for specific element types according to platform conventions, or for keyboard-only users.
0
Causes the element to be focusable, and indicates that the author would prefer the element to be both click focusable and sequentially focusable. The user agent might ignore this preference for click and sequential focusabiity.
positive integer values
Behaves the same as 0, but in addition creates a relative ordering within a tabindex-ordered focus navigation scope, so that elements with higher tabindex attribute value come later.

Note that the tabindex attribute cannot be used to make an element non-focusable. The only way a page author can do that is by disabling the element, or making it inert.


The tabindex value of an element is the value of its tabindex attribute, parsed using the rules for parsing integers. If parsing fails or the attribute is not specified, then the tabindex value is null.

The tabindex value of a focusable area is the tabindex value of its DOM anchor.

The tabindex value of an element must be interpreted as follows:

If the value is null

The user agent should follow platform conventions to determine if the element should be considered as a focusable area and if so, whether the element and any focusable areas that have the element as their DOM anchor are sequentially focusable, and if so, what their relative position in their tabindex-ordered focus navigation scope is to be. If the element is a focus navigation scope owner, it must be included in its tabindex-ordered focus navigation scope even if it is not a focusable area.

The relative ordering within a tabindex-ordered focus navigation scope for elements and focusable areas that belong to the same focus navigation scope and whose tabindex value is null should be in shadow-including tree order.

Modulo platform conventions, it is suggested that the following elements should be considered as focusable areas and be sequentially focusable:

If the value is a negative integer

The user agent must consider the element as a focusable area, but should omit the element from any tabindex-ordered focus navigation scope.

One valid reason to ignore the requirement that sequential focus navigation not allow the author to lead to the element would be if the user's only mechanism for moving the focus is sequential focus navigation. For instance, a keyboard-only user would be unable to click on a text control with a negative tabindex, so that user's user agent would be well justified in allowing the user to tab to the control regardless.

If the value is a zero

The user agent must allow the element to be considered as a focusable area and should allow the element and any focusable areas that have the element as their DOM anchor to be sequentially focusable.

The relative ordering within a tabindex-ordered focus navigation scope for elements and focusable areas that belong to the same focus navigation scope and whose tabindex value is zero should be in shadow-including tree order.

If the value is greater than zero

The user agent must allow the element to be considered as a focusable area and should allow the element and any focusable areas that have the element as their DOM anchor to be sequentially focusable, and should place the element — referenced as candidate below — and the aforementioned focusable areas in the tabindex-ordered focus navigation scope where the element is a part of so that, relative to other elements and focusable areas that belong to the same focus navigation scope, they are:

HTMLElement/tabIndex

Support in all current engines.

Firefox1+Safari3.1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)18Internet Explorer🔰 5.5+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The tabIndex IDL attribute must reflect the value of the tabindex content attribute. The default value is 0 if the element is an a, area, button, frame, iframe, input, object, select, textarea, or SVG a element, or is a summary element that is a summary for its parent details. The default value is −1 otherwise.

The varying default value based on element type is a historical artifact.

6.5.4 Processing model

To get the focusable area for a focus target that is either an element that is not a focusable area, or is a browsing context, given an optional string focus trigger, run the first matching set of steps from the following list:

If focus target is an area element with one or more shapes that are focusable areas

Return the shape corresponding to the first img element in tree order that uses the image map to which the area element belongs.

If focus target is an element with one or more scrollable regions that are focusable areas

Return the element's first scrollable region, according to a pre-order, depth-first traversal of the flat tree. [CSSSCOPING]

If focus target is the document element of its Document

Return the Document's viewport.

If focus target is a browsing context

Return the browsing context's active document.

If focus target is a browsing context container with a non-null nested browsing context

Return the browsing context container's nested browsing context's active document.

If focus target is a shadow host whose shadow root's delegates focus is true
  1. If focus target is a shadow-including inclusive ancestor of the currently focused area of a top-level browsing context's DOM anchor, then return null.
  2. Otherwise:

    1. If focus trigger is "click", then let possible focus delegates be the list of all click focusable focusable areas whose DOM anchor is a descendant of focus target in the flat tree.
    2. Otherwise, let possible focus delegates be the list of all focusable areas whose DOM anchor is a descendant of focus target in the flat tree.
    3. Return the first focusable area in tree order of their DOM anchors in possible focus delegates, or null if possible focus delegates is empty.

For sequential focusability, the handling of shadow hosts and delegates focus is done when constructing the sequential focus navigation order. That is, the focusing steps will never be called on such shadow hosts as part of sequential focus navigation.

Otherwise

Return null.

The focusing steps for an object new focus target that is either a focusable area, or an element that is not a focusable area, or a browsing context, are as follows. They can optionally be run with a fallback target and a string focus trigger.

  1. If new focus target is not a focusable area, then set new focus target to the result of getting the focusable area for new focus target, given focus trigger if it was passed.

  2. If new focus target is null, then:

    1. If no fallback target was specified, then return.

    2. Otherwise, set new focus target to the fallback target.

  3. If new focus target is a browsing context container with non-null nested browsing context, then set new focus target to the nested browsing context's active document, and redo this step.

  4. If new focus target is a focusable area and its DOM anchor is inert, then return.

  5. If new focus target is the currently focused area of a top-level browsing context, then return.

  6. Let old chain be the focus chain of the currently focused area of the top-level browsing context in which new focus target finds itself.

  7. Let new chain be the focus chain of new focus target.

  8. Run the focus update steps with old chain, new chain, and new focus target respectively.

User agents must immediately run the focusing steps for a focusable area or browsing context candidate whenever the user attempts to move the focus to candidate.

The unfocusing steps for an object old focus target that is either a focusable area or an element that is not a focusable area are as follows:

  1. If old focus target is inert, then return.

  2. If old focus target is an area element and one of its shapes is the currently focused area of a top-level browsing context, or, if old focus target is an element with one or more scrollable regions, and one of them is the currently focused area of a top-level browsing context, then let old focus target be that currently focused area of a top-level browsing context.

  3. Let old chain be the focus chain of the currently focused area of a top-level browsing context.

  4. If old focus target is not one of the entries in old chain, then return.

  5. If old focus target is a focusable area, then let new focus target be its Document's viewport.

    Otherwise, let new focus target be null.

  6. If new focus target is not null, then run the focusing steps for new focus target.

When the currently focused area of a top-level browsing context is somehow unfocused without another element being explicitly focused in its stead, the user agent must immediately run the unfocusing steps for that object.

The unfocusing steps do not always result in the focus changing, even when applied to the currently focused area of a top-level browsing context. For example, if the currently focused area of a top-level browsing context is a viewport, then it will usually keep its focus regardless until another focusable area is explicitly focused with the focusing steps.


Focus fixup rule: When the designated focused area of the document is removed from that Document in some way (e.g. it stops being a focusable area, it is removed from the DOM, it becomes expressly inert, etc.), designate the Document's viewport to be the new focused area of the document.

For example, this might happen because an element is removed from its Document, or has a hidden attribute added. It might also happen to an input element when the element gets disabled.

In a Document whose focused area is a button element, removing, disabling, or hiding that button would cause the page's new focused area to be the viewport of the Document. This would, in turn, be reflected through the activeElement API as the body element.


The focus update steps, given an old chain, a new chain, and a new focus target respectively, are as follows:

  1. If the last entry in old chain and the last entry in new chain are the same, pop the last entry from old chain and the last entry from new chain and redo this step.

  2. For each entry entry in old chain, in order, run these substeps:

    1. If entry is an input element, and the change event applies to the element, and the element does not have a defined activation behavior, and the user has changed the element's value or its list of selected files while the control was focused without committing that change (such that it is different to what it was when the control was first focused), then fire an event named change at the element, with the bubbles attribute initialized to true.

    2. If entry is an element, let blur event target be entry.

      If entry is a Document object, let blur event target be that Document object's relevant global object.

      Otherwise, let blur event target be null.

    3. If entry is the last entry in old chain, and entry is an Element, and the last entry in new chain is also an Element, then let related blur target be the last entry in new chain. Otherwise, let related blur target be null.

    4. If blur event target is not null, fire a focus event named blur at blur event target, with related blur target as the related target.

      In some cases, e.g. if entry is an area element's shape, a scrollable region, or a viewport, no event is fired.

  3. Apply any relevant platform-specific conventions for focusing new focus target. (For example, some platforms select the contents of a text control when that control is focused.)

  4. For each entry entry in new chain, in reverse order, run these substeps:

    1. If entry is a focusable area: designate entry as the focused area of the document.

    2. If entry is an element, let focus event target be entry.

      If entry is a Document object, let focus event target be that Document object's relevant global object.

      Otherwise, let focus event target be null.

    3. If entry is the last entry in new chain, and entry is an Element, and the last entry in old chain is also an Element, then let related focus target be the last entry in old chain. Otherwise, let related focus target be null.

    4. If focus event target is not null, fire a focus event named focus at focus event target, with related focus target as the related target.

      In some cases, e.g. if entry is an area element's shape, a scrollable region, or a viewport, no event is fired.

To fire a focus event named e at an element t with a given related target r, fire an event named e at t, using FocusEvent, with the relatedTarget attribute initialized to r, the view attribute initialized to t's node document's relevant global object, and the composed flag set.


When a key event is to be routed in a top-level browsing context, the user agent must run the following steps:

  1. Let target area be the currently focused area of the top-level browsing context.

  2. If target area is a focusable area, let target node be target area's DOM anchor. Otherwise, target area is a dialog; let target node be target area.

  3. If target node is a Document that has a body element, then let target node be the body element of that Document.

    Otherwise, if target node is a Document object that has a non-null document element, then let target node be that document element.

  4. If target node is not inert, then:

    It is possible for the currently focused area of a top-level browsing context to be inert, for example if a modal dialog is shown, and then that dialog element is made inert. It is likely to be the result of a logic error in the application, though.

    1. Let canHandle be the result of dispatching the key event at target node.

    2. If canHandle is true, then let target area handle the key event. This might include firing a click event at target node.


The has focus steps, given a Document object target, are as follows:

  1. Let candidate be target's top-level browsing context's active document.

  2. While true:

    1. If candidate is target, then return true.

    2. If the focused area of candidate is a browsing context container with a non-null nested browsing context, then set candidate to the active document of that browsing context container's nested browsing context.

    3. Otherwise, return false.

6.5.5 Sequential focus navigation

Each Document has a sequential focus navigation order, which orders some or all of the focusable areas in the Document relative to each other. Its contents and ordering are given by the flattened tabindex-ordered focus navigation scope of the Document.

Per the rules defining the flattened tabindex-ordered focus navigation scope, the ordering is not necessarily related to the tree order of the Document.

If a focusable area is omitted from the sequential focus navigation order of its Document, then it is unreachable via sequential focus navigation.

There can also be a sequential focus navigation starting point. It is initially unset. The user agent may set it when the user indicates that it should be moved.

For example, the user agent could set it to the position of the user's click if the user clicks on the document contents.

User agents are required to set the sequential focus navigation starting point to the target element when navigating to a fragment.

When the user requests that focus move from the currently focused area of a top-level browsing context to the next or previous focusable area (e.g. as the default action of pressing the tab key), or when the user requests that focus sequentially move to a top-level browsing context in the first place (e.g. from the browser's location bar), the user agent must use the following algorithm:

  1. Let starting point be the currently focused area of a top-level browsing context, if the user requested to move focus sequentially from there, or else the top-level browsing context itself, if the user instead requested to move focus from outside the top-level browsing context.

  2. If there is a sequential focus navigation starting point defined and it is inside starting point, then let starting point be the sequential focus navigation starting point instead.

  3. Let direction be forward if the user requested the next control, and backward if the user requested the previous control.

    Typically, pressing tab requests the next control, and pressing shift+tab requests the previous control.

  4. Loop: Let selection mechanism be sequential if the starting point is a browsing context or if starting point is in its Document's sequential focus navigation order.

    Otherwise, starting point is not in its Document's sequential focus navigation order; let selection mechanism be DOM.

  5. Let candidate be the result of running the sequential navigation search algorithm with starting point, direction, and selection mechanism as the arguments.

  6. If candidate is not null, then run the focusing steps for candidate and return.

  7. Otherwise, unset the sequential focus navigation starting point.

  8. If starting point is the top-level browsing context, or a focusable area in the top-level browsing context, the user agent should transfer focus to its own controls appropriately (if any), honouring direction, and then return.

    For example, if direction is backward, then the last sequentially focusable control before the browser's rendering area would be the control to focus.

    If the user agent has no sequentially focusable controls — a kiosk-mode browser, for instance — then the user agent may instead restart these steps with the starting point being the top-level browsing context itself.

  9. Otherwise, starting point is a focusable area in a child browsing context. Set starting point to that child browsing context's container and return to the step labeled loop.

The sequential navigation search algorithm consists of the following steps. This algorithm takes three arguments: starting point, direction, and selection mechanism.

  1. Pick the appropriate cell from the following table, and follow the instructions in that cell.

    The appropriate cell is the one that is from the column whose header describes direction and from the first row whose header describes starting point and selection mechanism.

    direction is forward direction is backward
    starting point is a browsing context Let candidate be the first suitable sequentially focusable area in starting point's active document, if any; or else null Let candidate be the last suitable sequentially focusable area in starting point's active document, if any; or else null
    selection mechanism is DOM Let candidate be the first suitable sequentially focusable area in the home document following starting point, if any; or else null Let candidate be the last suitable sequentially focusable area in the home document preceding starting point, if any; or else null
    selection mechanism is sequential Let candidate be the first suitable sequentially focusable area in the home sequential focus navigation order following starting point, if any; or else null Let candidate be the last suitable sequentially focusable area in the home sequential focus navigation order preceding starting point, if any; or else null

    A suitable sequentially focusable area is a focusable area whose DOM anchor is not inert and is sequentially focusable.

    The home document is the Document to which starting point belongs.

    The home sequential focus navigation order is the sequential focus navigation order to which starting point belongs.

    The home sequential focus navigation order is the home document's sequential focus navigation order, but is only used when the starting point is in that sequential focus navigation order (when it's not, selection mechanism will be DOM).

  2. If candidate is a browsing context container with a non-null nested browsing context, then let new candidate be the result of running the sequential navigation search algorithm with candidate's nested browsing context as the first argument, direction as the second, and sequential as the third.

    If new candidate is null, then let starting point be candidate, and return to the top of this algorithm. Otherwise, let candidate be new candidate.

  3. Return candidate.

6.5.6 Focus management APIs

dictionary FocusOptions {
  boolean preventScroll = false;
};
documentOrShadowRoot . activeElement

Document/activeElement

Support in all current engines.

Firefox3+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer6+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

ShadowRoot/activeElement

Support in all current engines.

Firefox63+Safari10.1+Chrome53+
Opera40+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10.3+Chrome Android53+WebView Android53+Samsung Internet6.0+Opera Android41+

Returns the deepest element in the document through which or to which key events are being routed. This is, roughly speaking, the focused element in the document.

For the purposes of this API, when a child browsing context is focused, its container is focused in the parent browsing context. For example, if the user moves the focus to a text control in an iframe, the iframe is the element returned by the activeElement API in the iframe's node document.

Similarly, when the focused element is in a different node tree than documentOrShadowRoot, the element returned will be the host that's located in the same node tree as documentOrShadowRoot if documentOrShadowRoot is a shadow-including inclusive ancestor of the focused element, and null if not.

document . hasFocus()

Document/hasFocus

Support in all current engines.

Firefox3+Safari4+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+

Returns true if key events are being routed through or to the document; otherwise, returns false. Roughly speaking, this corresponds to the document, or a document nested inside this one, being focused.

window . focus()

Window/focus

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Moves the focus to the window's browsing context, if any.

element . focus([ { preventScroll: true } ])

HTMLElement/focus

Support in all current engines.

Firefox1.5+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android10.1+

Moves the focus to the element.

If the element is a browsing context container, moves the focus to its nested browsing context instead.

By default, this method also scrolls the element into view. Providing the preventScroll option and setting it to true prevents this behavior.

element . blur()

HTMLElement/blur

Support in all current engines.

Firefox1.5+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android10.1+

Moves the focus to the viewport. Use of this method is discouraged; if you want to focus the viewport, call the focus() method on the Document's document element.

Do not use this method to hide the focus ring if you find the focus ring unsightly. Instead, use a CSS rule to override the 'outline' property, and provide a different way to show what element is focused. Be aware that if an alternative focusing style isn't made available, the page will be significantly less usable for people who primarily navigate pages using a keyboard, or those with reduced vision who use focus outlines to help them navigate the page.

For example, to hide the outline from links and instead use a yellow background to indicate focus, you could use:

:link:focus, :visited:focus { outline: none; background: yellow; color: black; }

The activeElement attribute's getter must run these steps:

  1. Let candidate be the DOM anchor of the focused area of this DocumentOrShadowRoot's node document.

  2. Set candidate to the result of retargeting candidate against this DocumentOrShadowRoot.

  3. If candidate's root is not this DocumentOrShadowRoot, then return null.

  4. If candidate is not a Document object, then return candidate.

  5. If candidate has a body element, then return that body element.

  6. If candidate's document element is non-null, then return that document element.

  7. Return null.

The hasFocus() method on the Document object, when invoked, must return the result of running the has focus steps with the Document object as the argument.

The focus() method, when invoked, must run these steps:

  1. Let current be this Window object's browsing context.

  2. If current is null, then return.

  3. Run the focusing steps with current.

  4. If current is a top-level browsing context, user agents are encouraged to trigger some sort of notification to indicate to the user that the page is attempting to gain focus.

Window/blur

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

The blur() method, when invoked, provides a hint to the user agent that the script believes the user probably is not currently interested in the contents of this Window object's browsing context, if non-null, but that the contents might become interesting again in the future.

User agents are encouraged to ignore calls to this blur() method entirely.

Historically, the focus() and blur() methods actually affected the system-level focus of the system widget (e.g., tab or window) that contained the browsing context, but hostile sites widely abuse this behavior to the user's detriment.

The focus(options) method on elements, when invoked, must run the following steps:

  1. If the element is marked as locked for focus, then return.

  2. Mark the element as locked for focus.

  3. Run the focusing steps for the element.

  4. If the value of the preventScroll dictionary member of options is false, then scroll the element into view with scroll behavior "auto", block flow direction position set to an implementation-defined value, and inline base direction position set to an implementation-defined value.

  5. Unmark the element as locked for focus.

The blur() method, when invoked, should run the unfocusing steps for the element on which the method was called. User agents may selectively or uniformly ignore calls to this method for usability reasons.

For example, if the blur() method is unwisely being used to remove the focus ring for aesthetics reasons, the page would become unusable by keyboard users. Ignoring calls to this method would thus allow keyboard users to interact with the page.

6.5.7 The autofocus attribute

The autofocus content attribute allows the author to indicate that an element is to be focused as soon as the page is loaded or as soon as the dialog within which it finds itself is shown, allowing the user to just start typing without having to manually focus the main element.

The autofocus attribute is a boolean attribute.

An element's nearest ancestor autofocus scoping root element is the element itself if the element is a dialog element, or else is the element's nearest ancestor dialog element, if any, or else is the element's last inclusive ancestor element.

There must not be two elements with the same nearest ancestor autofocus scoping root element that both have the autofocus attribute specified.

Each Document has an autofocus candidates list, initially empty.

Each Document has an autofocus processed flag boolean, initially false.

When an element with the autofocus attribute specified is inserted into a document, run the following steps:

  1. If the user has indicated (for example, by starting to type in a form control) that they do not wish focus to be changed, then optionally return.

  2. Let target be the element's node document.

  3. If target's browsing context is null, then return.

  4. If target's active sandboxing flag set has the sandboxed automatic features browsing context flag, then return.

  5. Let topDocument be the active document of target's browsing context's top-level browsing context.

  6. If target's origin is not the same as the origin of topDocument, then return.

  7. If topDocument's autofocus processed flag is false, then remove the element from topDocument's autofocus candidates, and append the element to topDocument's autofocus candidates.

We do not check if an element is a focusable area before storing it in the autofocus candidates list, because even if it is not a focusable area when it is inserted, it could become one by the time flush autofocus candidates sees it.

To flush autofocus candidates for a document topDocument, run these steps:

  1. If topDocument's autofocus processed flag is true, then return.

  2. Let candidates be topDocument's autofocus candidates.

  3. If candidates is empty, then return.

  4. If topDocument's focused area is not topDocument itself, or topDocument's URL's fragment is not empty, then:

    1. Empty candidates.

    2. Set topDocument's autofocus processed flag to true.

    3. Return.

  5. While candidates is not empty:

    1. Let element be candidates[0].

    2. Let doc be element's node document.

    3. If doc is not fully active, then remove element from candidates, and continue.

    4. If doc's browsing context's top-level browsing context is not same as topDocument's browsing context, then remove element from candidates, and continue.

    5. If doc's script-blocking style sheet counter is greater than 0, then return.

      In this case, element is the currently-best candidate, but doc is not ready for autofocusing. We'll try again next time flush autofocus candidates is called.

    6. Remove element from candidates.

    7. Let inclusiveAncestorDocuments be a list consisting of doc, plus the active documents of each of doc's browsing context's ancestor browsing contexts.

    8. If URL's fragment of any Document in inclusiveAncestorDocuments is not empty, then continue.

    9. Let target be element.

    10. If target is not a focusable area, then set target to the result of getting the focusable area for target.

      Autofocus candidates can contain elements which are not focusable areas. In addition to the special cases handled in the get the focusable area algorithm, this can happen because a non-focusable area element with an autofocus attribute was inserted into a document and it never became focusable, or because the element was focusable but its status changed while it was stored in autofocus candidates.

    11. If target is not null, then:

      1. Empty candidates.

      2. Set topDocument's autofocus processed flag to true.

      3. Run the focusing steps for target.

This handles the automatic focusing during document load. The show() and showModal() methods of dialog elements also processes the autofocus attribute.

Focusing the element does not imply that the user agent has to focus the browser window if it has lost focus.

Global_attributes/autofocus

Support in one engine only.

Firefox🔰 1+Safari🔰 4+Chrome79+
Opera66+Edge79+
Edge (Legacy)NoInternet Explorer🔰 10+
Firefox Android🔰 4+Safari iOS🔰 3.2+Chrome Android79+WebView Android79+Samsung Internet12.0+Opera Android57+

The autofocus IDL attribute must reflect the content attribute of the same name.

In the following snippet, the text control would be focused when the document was loaded.

<input maxlength="256" name="q" value="" autofocus>
<input type="submit" value="Search">

The autofocus attribute applies to all elements, not just to form controls. This allows examples such as the following:

<div contenteditable autofocus>Edit <strong>me!</strong><div>

6.6 指定快捷键

6.6.1 概述

This section is non-normative.

每个可以激活和获得焦点的元素都可以使用 accesskey 属性指定一个组合键来激活它。

具体的快捷键由用户代理决定,基于用户键盘的信息,平台上既有的快捷键, 以及已经在页面上指定的快捷键,使用在 accesskey 属性中提供的信息作为指导。

为了确保相关的键盘快捷键对多数输入设备都可用,作者可以在 accesskey 属性中提供一些替代快捷键。

每个替代键包含一个字符,比如一个字母或者数字。

用户代理可以给用户提供一个快捷键列表,但是也鼓励作者提供快捷键列表。 accessKeyLabel IDL 属性返回一个字符串, 表示用户代理实际指定的组合键。

在这个例子中,作者提供了一个可以用快捷键调用的按钮。 为了支持全键盘,作者提供了 "C" 作为一个可能的键。 为了支持只有数字键的设备,作者提供了 "1" 作为另一个可能的键。

<input type=button value=Collect onclick="collect()"
       accesskey="C 1" id=c>

为了告诉用户快捷键是什么,作者在这里有这样一个脚本,显式地把组合键添加到按钮的标签上:

function addShortcutKeyLabel(button) {
  if (button.accessKeyLabel != '')
    button.value += ' (' + button.accessKeyLabel + ')';
}
addShortcutKeyLabel(document.getElementById('c'));

不同平台的浏览器会显示不同的标签。即使是同样的组合键,基于该平台流行的惯例也可能有所不同。 例如,如果一个组合键是 Control , Shift 和字母 C, 一个 Windows 浏览器可能显示为 "Ctrl+Shift+C", 而一个 Mac 浏览器可能显示为 "^⇧C", 而在 Emacs 浏览器中可能只是显示为 "C-C"。 类似地,如果组合键是一个 Alt 和 Escape 键,Windows 可能会使用 "Alt+Esc", Mac 可能会使用 "⌥⎋", Emacs 浏览器可能会使用 "M-ESC" 或 "ESC ESC"。

因此通常来讲,尝试解析 accessKeyLabel IDL 属性返回的值是不明智的。

6.6.2 The accesskey attribute

Global_attributes/accesskey

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

All HTML elements may have the accesskey content attribute set. The accesskey attribute's value is used by the user agent as a guide for creating a keyboard shortcut that activates or focuses the element.

If specified, the value must be an ordered set of unique space-separated tokens none of which are identical to another token and each of which must be exactly one code point in length.

In the following example, a variety of links are given with access keys so that keyboard users familiar with the site can more quickly navigate to the relevant pages:

<nav>
 <p>
  <a title="Consortium Activities" accesskey="A" href="/Consortium/activities">Activities</a> |
  <a title="Technical Reports and Recommendations" accesskey="T" href="/TR/">Technical Reports</a> |
  <a title="Alphabetical Site Index" accesskey="S" href="/Consortium/siteindex">Site Index</a> |
  <a title="About This Site" accesskey="B" href="/Consortium/">About Consortium</a> |
  <a title="Contact Consortium" accesskey="C" href="/Consortium/contact">Contact</a>
 </p>
</nav>

In the following example, the search field is given two possible access keys, "s" and "0" (in that order). A user agent on a device with a full keyboard might pick Ctrl+Alt+S as the shortcut key, while a user agent on a small device with just a numeric keypad might pick just the plain unadorned key 0:

<form action="/search">
 <label>Search: <input type="search" name="q" accesskey="s 0"></label>
 <input type="submit">
</form>

In the following example, a button has possible access keys described. A script then tries to update the button's label to advertise the key combination the user agent selected.

<input type=submit accesskey="N @ 1" value="Compose">
...
<script>
 function labelButton(button) {
   if (button.accessKeyLabel)
     button.value += ' (' + button.accessKeyLabel + ')';
 }
 var inputs = document.getElementsByTagName('input');
 for (var i = 0; i < inputs.length; i += 1) {
   if (inputs[i].type == "submit")
     labelButton(inputs[i]);
 }
</script>

On one user agent, the button's label might become "Compose (⌘N)". On another, it might become "Compose (Alt+⇧+1)". If the user agent doesn't assign a key, it will be just "Compose". The exact string depends on what the assigned access key is, and on how the user agent represents that key combination.

6.6.3 Processing model

An element's assigned access key is a key combination derived from the element's accesskey content attribute. Initially, an element must not have an assigned access key.

Whenever an element's accesskey attribute is set, changed, or removed, the user agent must update the element's assigned access key by running the following steps:

  1. If the element has no accesskey attribute, then skip to the fallback step below.

  2. Otherwise, split the attribute's value on ASCII whitespace, and let keys be the resulting tokens.

  3. For each value in keys in turn, in the order the tokens appeared in the attribute's value, run the following substeps:

    1. If the value is not a string exactly one code point in length, then skip the remainder of these steps for this value.

    2. If the value does not correspond to a key on the system's keyboard, then skip the remainder of these steps for this value.

    3. (This is a tracking vector.) If the user agent can find a mix of zero or more modifier keys that, combined with the key that corresponds to the value given in the attribute, can be used as the access key, then the user agent may assign that combination of keys as the element's assigned access key and return.

  4. Fallback: Optionally, the user agent may assign a key combination of its choosing as the element's assigned access key and then return.

  5. If this step is reached, the element has no assigned access key.

Once a user agent has selected and assigned an access key for an element, the user agent should not change the element's assigned access key unless the accesskey content attribute is changed or the element is moved to another Document.

When the user presses the key combination corresponding to the assigned access key for an element, if the element defines a command, the command's Hidden State facet is false (visible), the command's Disabled State facet is also false (enabled), the element is in a document that has a non-null browsing context, and neither the element nor any of its ancestors has a hidden attribute specified, then the user agent must trigger the Action of the command.

User agents might expose elements that have an accesskey attribute in other ways as well, e.g. in a menu displayed in response to a specific key combination.


HTMLElement/accessKey

Support in all current engines.

Firefox5+Safari6+Chrome17+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android5+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The accessKey IDL attribute must reflect the accesskey content attribute.

HTMLElement/accessKeyLabel

Firefox8+Safari14+ChromeNo
OperaNoEdgeNo
Edge (Legacy)NoInternet ExplorerNo
Firefox Android8+Safari iOS14+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo

The accessKeyLabel IDL attribute must return a string that represents the element's assigned access key, if any. If the element does not have one, then the IDL attribute must return the empty string.

6.7 编辑

6.7.1 Making document regions editable: The contenteditable content attribute

HTMLElement/contentEditable

Support in all current engines.

Firefox3+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android10.1+
interface mixin ElementContentEditable {
  [CEReactions] attribute DOMString contentEditable;
  [CEReactions] attribute DOMString enterKeyHint;
  readonly attribute boolean isContentEditable;
  [CEReactions] attribute DOMString inputMode;
};

Global_attributes/contenteditable

Support in all current engines.

Firefox3+SafariYesChromeYes
Opera9+EdgeYes
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

The contenteditable content attribute is an enumerated attribute whose keywords are the empty string, true, and false. The empty string and the true keyword map to the true state. The false keyword maps to the false state. In addition, there is a third state, the inherit state, which is the missing value default and the invalid value default.

The true state indicates that the element is editable. The inherit state indicates that the element is editable if its parent is. The false state indicates that the element is not editable.

For example, consider a page that has a form and a textarea to publish a new article, where the user is expected to write the article using HTML:

<form method=POST>
 <fieldset>
  <legend>New article</legend>
  <textarea name=article>&lt;p>Hello world.&lt;/p></textarea>
 </fieldset>
 <p><button>Publish</button></p>
</form>

When scripting is enabled, the textarea element could be replaced with a rich text control instead, using the contenteditable attribute:

<form method=POST>
 <fieldset>
  <legend>New article</legend>
  <textarea id=textarea name=article>&lt;p>Hello world.&lt;/p></textarea>
  <div id=div style="white-space: pre-wrap" hidden><p>Hello world.</p></div>
  <script>
   let textarea = document.getElementById("textarea");
   let div = document.getElementById("div");
   textarea.hidden = true;
   div.hidden = false;
   div.contentEditable = "true";
   div.oninput = (e) => {
     textarea.value = div.innerHTML;
   };
  </script>
 </fieldset>
 <p><button>Publish</button></p>
</form>

Features to enable, e.g., inserting links, can be implemented using the document.execCommand() API, or using Selection APIs and other DOM APIs. [EXECCOMMAND] [SELECTION] [DOM]

The contenteditable attribute can also be used to great effect:

<!doctype html>
<html lang=en>
<title>Live CSS editing!</title>
<style style=white-space:pre contenteditable>
html { margin:.2em; font-size:2em; color:lime; background:purple }
head, title, style { display:block }
body { display:none }
</style>
element . contentEditable [ = value ]

Returns "true", "false", or "inherit", based on the state of the contenteditable attribute.

Can be set, to change that state.

Throws a "SyntaxError" DOMException if the new value isn't one of those strings.

element . isContentEditable

HTMLElement/isContentEditable

Support in all current engines.

Firefox4+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

Returns true if the element is editable; otherwise, returns false.

The contentEditable IDL attribute, on getting, must return the string "true" if the content attribute is set to the true state, "false" if the content attribute is set to the false state, and "inherit" otherwise. On setting, if the new value is an ASCII case-insensitive match for the string "inherit" then the content attribute must be removed, if the new value is an ASCII case-insensitive match for the string "true" then the content attribute must be set to the string "true", if the new value is an ASCII case-insensitive match for the string "false" then the content attribute must be set to the string "false", and otherwise the attribute setter must throw a "SyntaxError" DOMException.

The isContentEditable IDL attribute, on getting, must return true if the element is either an editing host or editable, and false otherwise.

6.7.2 Making entire documents editable: the designMode getter and setter

document . designMode [ = value ]

Document/designMode

Support in all current engines.

Firefox1+Safari1.2+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Returns "on" if the document is editable, and "off" if it isn't.

Can be set, to change the document's current state. This focuses the document and resets the selection in that document.

Document objects have an associated design mode enabled, which is a boolean. It is initially false.

The designMode getter steps are to return "on" if this's design mode enabled is true; otherwise "off".

The designMode setter steps are:

  1. Let value be the given value, converted to ASCII lowercase.

  2. If value is "on" and this's design mode enabled is false, then:

    1. Set this's design mode enabled to true.

    2. Reset this's active range's start and end boundary points to be at the start of this.

    3. Run the focusing steps for this's document element, if non-null.

  3. If value is "off", then set this's design mode enabled to false.

6.7.3 Best practices for in-page editors

Authors are encouraged to set the 'white-space' property on editing hosts and on markup that was originally created through these editing mechanisms to the value 'pre-wrap'. Default HTML whitespace handling is not well suited to WYSIWYG editing, and line wrapping will not work correctly in some corner cases if 'white-space' is left at its default value.

As an example of problems that occur if the default 'normal' value is used instead, consider the case of the user typing "yellow␣␣ball", with two spaces (here represented by "␣") between the words. With the editing rules in place for the default value of 'white-space' ('normal'), the resulting markup will either consist of "yellow&nbsp; ball" or "yellow &nbsp;ball"; i.e., there will be a non-breaking space between the two words in addition to the regular space. This is necessary because the 'normal' value for 'white-space' requires adjacent regular spaces to be collapsed together.

In the former case, "yellow⍽" might wrap to the next line ("⍽" being used here to represent a non-breaking space) even though "yellow" alone might fit at the end of the line; in the latter case, "⍽ball", if wrapped to the start of the line, would have visible indentation from the non-breaking space.

When 'white-space' is set to 'pre-wrap', however, the editing rules will instead simply put two regular spaces between the words, and should the two words be split at the end of a line, the spaces would be neatly removed from the rendering.

6.7.4 Editing APIs

An editing host is either an HTML element with its contenteditable attribute in the true state, or a child HTML element of a Document whose design mode enabled is true.

The definition of the terms active range, editing host of, and editable, the user interface requirements of elements that are editing hosts or editable, the execCommand(), queryCommandEnabled(), queryCommandIndeterm(), queryCommandState(), queryCommandSupported(), and queryCommandValue() methods, text selections, and the delete the selection algorithm are defined in execCommand. [EXECCOMMAND]

6.7.5 Spelling and grammar checking

User agents can support the checking of spelling and grammar of editable text, either in form controls (such as the value of textarea elements), or in elements in an editing host (e.g. using contenteditable).

For each element, user agents must establish a default behavior, either through defaults or through preferences expressed by the user. There are three possible default behaviors for each element:

true-by-default
The element will be checked for spelling and grammar if its contents are editable and spellchecking is not explicitly disabled through the spellcheck attribute.
false-by-default
The element will never be checked for spelling and grammar unless spellchecking is explicitly enabled through the spellcheck attribute.
inherit-by-default
The element's default behavior is the same as its parent element's. Elements that have no parent element cannot have this as their default behavior.

Global_attributes/spellcheck

Support in all current engines.

FirefoxYesSafariYesChrome9+
OperaYesEdge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android57+Safari iOS9.3+Chrome Android47+WebView Android47+Samsung Internet5.0+Opera Android37+

The spellcheck attribute is an enumerated attribute whose keywords are the empty string, true and false. The empty string and the true keyword map to the true state. The false keyword maps to the false state. In addition, there is a third state, the default state, which is the missing value default and the invalid value default.

The true state indicates that the element is to have its spelling and grammar checked. The default state indicates that the element is to act according to a default behavior, possibly based on the parent element's own spellcheck state, as defined below. The false state indicates that the element is not to be checked.


element . spellcheck [ = value ]

Returns true if the element is to have its spelling and grammar checked; otherwise, returns false.

Can be set, to override the default and set the spellcheck content attribute.

The spellcheck IDL attribute, on getting, must return true if the element's spellcheck content attribute is in the true state, or if the element's spellcheck content attribute is in the default state and the element's default behavior is true-by-default, or if the element's spellcheck content attribute is in the default state and the element's default behavior is inherit-by-default and the element's parent element's spellcheck IDL attribute would return true; otherwise, if none of those conditions applies, then the attribute must instead return false.

The spellcheck IDL attribute is not affected by user preferences that override the spellcheck content attribute, and therefore might not reflect the actual spellchecking state.

On setting, if the new value is true, then the element's spellcheck content attribute must be set to the literal string "true", otherwise it must be set to the literal string "false".


User agents must only consider the following pieces of text as checkable for the purposes of this feature:

For text that is part of a Text node, the element with which the text is associated is the element that is the immediate parent of the first character of the word, sentence, or other piece of text. For text in attributes, it is the attribute's element. For the values of input and textarea elements, it is the element itself.

To determine if a word, sentence, or other piece of text in an applicable element (as defined above) is to have spelling- and grammar-checking enabled, the UA must use the following algorithm:

  1. If the user has disabled the checking for this text, then the checking is disabled.
  2. Otherwise, if the user has forced the checking for this text to always be enabled, then the checking is enabled.
  3. Otherwise, if the element with which the text is associated has a spellcheck content attribute, then: if that attribute is in the true state, then checking is enabled; otherwise, if that attribute is in the false state, then checking is disabled.
  4. Otherwise, if there is an ancestor element with a spellcheck content attribute that is not in the default state, then: if the nearest such ancestor's spellcheck content attribute is in the true state, then checking is enabled; otherwise, checking is disabled.
  5. Otherwise, if the element's default behavior is true-by-default, then checking is enabled.
  6. Otherwise, if the element's default behavior is false-by-default, then checking is disabled.
  7. Otherwise, if the element's parent element has its checking enabled, then checking is enabled.
  8. Otherwise, checking is disabled.

If the checking is enabled for a word/sentence/text, the user agent should indicate spelling and grammar errors in that text. User agents should take into account the other semantics given in the document when suggesting spelling and grammar corrections. User agents may use the language of the element to determine what spelling and grammar rules to use, or may use the user's preferred language settings. UAs should use input element attributes such as pattern to ensure that the resulting value is valid, where possible.

If checking is disabled, the user agent should not indicate spelling or grammar errors for that text.

The element with ID "a" in the following example would be the one used to determine if the word "Hello" is checked for spelling errors. In this example, it would not be.

<div contenteditable="true">
 <span spellcheck="false" id="a">Hell</span><em>o!</em>
</div>

The element with ID "b" in the following example would have checking enabled (the leading space character in the attribute's value on the input element causes the attribute to be ignored, so the ancestor's value is used instead, regardless of the default).

<p spellcheck="true">
 <label>Name: <input spellcheck=" false" id="b"></label>
</p>

This specification does not define the user interface for spelling and grammar checkers. A user agent could offer on-demand checking, could perform continuous checking while the checking is enabled, or could use other interfaces.

6.7.6 Autocapitalization

Some methods of entering text, for example virtual keyboards on mobile devices, and also voice input, often assist users by automatically capitalizing the first letter of sentences (when composing text in a language with this convention). A virtual keyboard that implements autocapitalization might automatically switch to showing uppercase letters (but allow the user to toggle it back to lowercase) when a letter that should be autocapitalized is about to be typed. Other types of input, for example voice input, may perform autocapitalization in a way that does not give users an option to intervene first. The autocapitalize attribute allows authors to control such behavior.

The autocapitalize attribute, as typically implemented, does not affect behavior when typing on a physical keyboard. (For this reason, as well as the ability for users to override the autocapitalization behavior in some cases or edit the text after initial input, the attribute must not be relied on for any sort of input validation.)

The autocapitalize attribute can be used on an editing host to control autocapitalization behavior for the hosted editable region, on an input or textarea element to control the behavior for inputting text into that element, or on a form element to control the default behavior for all autocapitalize-inheriting elements associated with the form element.

The autocapitalize attribute never causes autocapitalization to be enabled for input elements whose type attribute is in one of the URL, Email, or Password states. (This behavior is included in the used autocapitalization hint algorithm below.)

The autocapitalization processing model is based on selecting among five autocapitalization hints, defined as follows:

default

The user agent and input method should use make their own determination of whether or not to enable autocapitalization.

none

No autocapitalization should be applied (all letters should default to lowercase).

sentences

The first letter of each sentence should default to a capital letter; all other letters should default to lowercase.

words

The first letter of each word should default to a capital letter; all other letters should default to lowercase.

characters

All letters should default to uppercase.

Global_attributes/autocapitalize

Support in all current engines.

Firefox🔰 83+SafariNoChrome43+
Opera?Edge79+
Edge (Legacy)NoInternet Explorer?
Firefox AndroidNoSafari iOS5+Chrome Android43+WebView Android43+Samsung Internet4.0+Opera Android?

The autocapitalize attribute is an enumerated attribute whose states are the possible autocapitalization hints. The autocapitalization hint specified by the attribute's state combines with other considerations to form the used autocapitalization hint, which informs the behavior of the user agent. The keywords for this attribute and their state mappings are as follows:

Keyword State
off none
none
on sentences
sentences
words words
characters characters

The invalid value default is the sentences state. The missing value default is the default state.

element . autocapitalize [ = value ]

Returns the current autocapitalization state for the element, or an empty string if it hasn't been set. Note that for input and textarea elements that inherit their state from a form element, this will return the autocapitalization state of the form element, but for an element in an editable region, this will not return the autocapitalization state of the editing host (unless this element is, in fact, the editing host).

Can be set, to set the autocapitalize content attribute (and thereby change the autocapitalization behavior for the element).

To compute the own autocapitalization hint of an element element, run the following steps:

  1. If the autocapitalize content attribute is present on element, and its value is not the empty string, return the state of the attribute.

  2. If element is an autocapitalize-inheriting element and has a non-null form owner, return the own autocapitalization hint of element's form owner.

  3. Return default.

The autocapitalize getter steps are to:

  1. Let state be the own autocapitalization hint of this.

  2. If state is default, then return the empty string.

  3. If state is none, then return "none".

  4. If state is sentences, then return "sentences".

  5. Return the keyword value corresponding to state.

The autocapitalize setter steps are to set the autocapitalize content attribute to the given value.


User agents that support customizable autocapitalization behavior for a text input method and wish to allow web developers to control this functionality should, during text input into an element, compute the used autocapitalization hint for the element. This will be an autocapitalization hint that describes the recommended autocapitalization behavior for text input into the element.

User agents or input methods may choose to ignore or override the used autocapitalization hint in certain circumstances.

The used autocapitalization hint for an element element is computed using the following algorithm:

  1. If element is an input element whose type attribute is in one of the URL, Email, or Password states, then return default.

  2. If element is an input element or a textarea element, then return element's own autocapitalization hint.

  3. If element is an editing host or an editable element, then return the own autocapitalization hint of the editing host of element.

  4. Assert: this step is never reached, since text input only occurs in elements that meet one of the above criteria.

6.7.7 Input modalities: the inputmode attribute

User agents can support the inputmode attribute on form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable).

Global_attributes/inputmode

Support in all current engines.

Firefox95+SafariNoChrome66+
Opera53+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS12.2+Chrome Android66+WebView Android66+Samsung Internet9.0+Opera Android47+

The inputmode content attribute is an enumerated attribute that specifies what kind of input mechanism would be most helpful for users entering content.

Keyword Description
none The user agent should not display a virtual keyboard. This keyword is useful for content that renders its own keyboard control.
text The user agent should display a virtual keyboard capable of text input in the user's locale.
tel The user agent should display a virtual keyboard capable of telephone number input. This should including keys for the digits 0 to 9, the "#" character, and the "*" character. In some locales, this can also include alphabetic mnemonic labels (e.g., in the US, the key labeled "2" is historically also labeled with the letters A, B, and C).
url The user agent should display a virtual keyboard capable of text input in the user's locale, with keys for aiding in the input of URLs, such as that for the "/" and "." characters and for quick input of strings commonly found in domain names such as "www." or ".com".
email The user agent should display a virtual keyboard capable of text input in the user's locale, with keys for aiding in the input of email addresses, such as that for the "@" character and the "." character.
numeric The user agent should display a virtual keyboard capable of numeric input. This keyword is useful for PIN entry.
decimal The user agent should display a virtual keyboard capable of fractional numeric input. Numeric keys and the format separator for the locale should be shown.
search The user agent should display a virtual keyboard optimized for search.

The inputMode IDL attribute must reflect the inputmode content attribute, limited to only known values.

When inputmode is unspecified (or is in a state not supported by the user agent), the user agent should determine the default virtual keyboard to be shown. Contextual information such as the input type or pattern attributes should be used to determine which type of virtual keyboard should be presented to the user.

6.7.8 Input modalities: the enterkeyhint attribute

User agents can support the enterkeyhint attribute on form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable).

Global_attributes/enterkeyhint

Support in all current engines.

Firefox94+Safari13.1+Chrome77+
Opera66+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android94+Safari iOS13.4+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android57+

The enterkeyhint content attribute is an enumerated attribute that specifies what action label (or icon) to present for the enter key on virtual keyboards. This allows authors to customize the presentation of the enter key in order to make it more helpful for users.

Keyword Description
enter The user agent should present a cue for the operation 'enter', typically inserting a new line.
done The user agent should present a cue for the operation 'done', typically meaning there is nothing more to input and the input method editor (IME) will be closed.
go The user agent should present a cue for the operation 'go', typically meaning to take the user to the target of the text they typed.
next The user agent should present a cue for the operation 'next', typically taking the user to the next field that will accept text.
previous The user agent should present a cue for the operation 'previous', typically taking the user to the previous field that will accept text.
search The user agent should present a cue for the operation 'search', typically taking the user to the results of searching for the text they have typed.
send The user agent should present a cue for the operation 'send', typically delivering the text to its target.

HTMLElement/enterKeyHint

Support in all current engines.

Firefox94+Safari13.1+Chrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android94+Safari iOS13.4+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+

The enterKeyHint IDL attribute must reflect the enterkeyhint content attribute, limited to only known values.

When enterkeyhint is unspecified (or is in a state not supported by the user agent), the user agent should determine the default action label (or icon) to present. Contextual information such as the inputmode, type, or pattern attributes should be used to determine which action label (or icon) to present on the virtual keyboard.

6.8 Find-in-page

6.8.1 Introduction

This section defines find-in-page — a common user-agent mechanism which allows users to search through the contents of the page for particular information.

Access to find-in-page feature is provided via a find-in-page interface. This is a user-agent provided user interface, which allows the user to specify input and the parameters of the search. This interface can appear as a result of a shortcut or a menu selection.

A combination of text input and settings in the find-in-page interface represents the user query. This typically includes the text that the user wants to search for, as well as optional settings (e.g., the ability to restrict the search to whole words only).

The user-agent processes page contents for a given query, and identifies zero or more matches, which are content ranges that satisfy the user query.

One of the matches is identified to the user as the active match. It is highlighted and scrolled into view. The user can navigate through the matches by advancing the active match using the find-in-page interface.

Issue #3539 tracks standardizing how find-in-page underlies the currently-unspecified window.find() API.

6.8.2 Interaction with selection

The find-in-page process is invoked in the context of a document, and may have an effect on the selection of that document. Specifically, the range that defines the active match can dictate the current selection. These selection updates, however, can happen at different times during the find-in-page process (e.g. upon the find-in-page interface dismissal or upon a change in the active match range).

6.9 Drag and drop

HTML_Drag_and_Drop_API

Support in all current engines.

Firefox3.5+Safari3.1+Chrome4+
Opera12+Edge79+
Edge (Legacy)18Internet Explorer5.5+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android4.4+Samsung Internet1.5+Opera Android14+

This section defines an event-based drag-and-drop mechanism.

This specification does not define exactly what a drag-and-drop operation actually is.

On a visual medium with a pointing device, a drag operation could be the default action of a mousedown event that is followed by a series of mousemove events, and the drop could be triggered by the mouse being released.

When using an input modality other than a pointing device, users would probably have to explicitly indicate their intention to perform a drag-and-drop operation, stating what they wish to drag and where they wish to drop it, respectively.

However it is implemented, drag-and-drop operations must have a starting point (e.g. where the mouse was clicked, or the start of the selection or element that was selected for the drag), may have any number of intermediate steps (elements that the mouse moves over during a drag, or elements that the user picks as possible drop points as they cycle through possibilities), and must either have an end point (the element above which the mouse button was released, or the element that was finally selected), or be canceled. The end point must be the last element selected as a possible drop point before the drop occurs (so if the operation is not canceled, there must be at least one element in the middle step).

6.9.1 Introduction

This section is non-normative.

To make an element draggable, give the element a draggable attribute, and set an event listener for dragstart that stores the data being dragged.

The event handler typically needs to check that it's not a text selection that is being dragged, and then needs to store data into the DataTransfer object and set the allowed effects (copy, move, link, or some combination).

For example:

<p>What fruits do you like?</p>
<ol ondragstart="dragStartHandler(event)">
 <li draggable="true" data-value="fruit-apple">Apples</li>
 <li draggable="true" data-value="fruit-orange">Oranges</li>
 <li draggable="true" data-value="fruit-pear">Pears</li>
</ol>
<script>
  var internalDNDType = 'text/x-example'; // set this to something specific to your site
  function dragStartHandler(event) {
    if (event.target instanceof HTMLLIElement) {
      // use the element's data-value="" attribute as the value to be moving:
      event.dataTransfer.setData(internalDNDType, event.target.dataset.value);
      event.dataTransfer.effectAllowed = 'move'; // only allow moves
    } else {
      event.preventDefault(); // don't allow selection to be dragged
    }
  }
</script>

To accept a drop, the drop target has to listen to the following events:

  1. The dragenter event handler reports whether or not the drop target is potentially willing to accept the drop, by canceling the event.
  2. The dragover event handler specifies what feedback will be shown to the user, by setting the dropEffect attribute of the DataTransfer associated with the event. This event also needs to be canceled.
  3. The drop event handler has a final chance to accept or reject the drop. If the drop is accepted, the event handler must perform the drop operation on the target. This event needs to be canceled, so that the dropEffect attribute's value can be used by the source. Otherwise, the drop operation is rejected.

For example:

<p>Drop your favorite fruits below:</p>
<ol ondragenter="dragEnterHandler(event)" ondragover="dragOverHandler(event)"
    ondrop="dropHandler(event)">
</ol>
<script>
  var internalDNDType = 'text/x-example'; // set this to something specific to your site
  function dragEnterHandler(event) {
    var items = event.dataTransfer.items;
    for (var i = 0; i < items.length; ++i) {
      var item = items[i];
      if (item.kind == 'string' && item.type == internalDNDType) {
        event.preventDefault();
        return;
      }
    }
  }
  function dragOverHandler(event) {
    event.dataTransfer.dropEffect = 'move';
    event.preventDefault();
  }
  function dropHandler(event) {
    var li = document.createElement('li');
    var data = event.dataTransfer.getData(internalDNDType);
    if (data == 'fruit-apple') {
      li.textContent = 'Apples';
    } else if (data == 'fruit-orange') {
      li.textContent = 'Oranges';
    } else if (data == 'fruit-pear') {
      li.textContent = 'Pears';
    } else {
      li.textContent = 'Unknown Fruit';
    }
    event.target.appendChild(li);
  }
</script>

To remove the original element (the one that was dragged) from the display, the dragend event can be used.

For our example here, that means updating the original markup to handle that event:

<p>What fruits do you like?</p>
<ol ondragstart="dragStartHandler(event)" ondragend="dragEndHandler(event)">
 ...as before...
</ol>
<script>
  function dragStartHandler(event) {
    // ...as before...
  }
  function dragEndHandler(event) {
    if (event.dataTransfer.dropEffect == 'move') {
      // remove the dragged element
      event.target.parentNode.removeChild(event.target);
    }
  }
</script>

6.9.2 The drag data store

The data that underlies a drag-and-drop operation, known as the drag data store, consists of the following information:

When a drag data store is created, it must be initialized such that its drag data store item list is empty, it has no drag data store default feedback, it has no drag data store bitmap and drag data store hot spot coordinate, its drag data store mode is protected mode, and its drag data store allowed effects state is the string "uninitialized".

6.9.3 The DataTransfer interface

DataTransfer

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12+

DataTransfer objects are used to expose the drag data store that underlies a drag-and-drop operation.

[Exposed=Window]
interface DataTransfer {
  constructor();

  attribute DOMString dropEffect;
  attribute DOMString effectAllowed;

  [SameObject] readonly attribute DataTransferItemList items;

  undefined setDragImage(Element image, long x, long y);

  /* old interface */
  readonly attribute FrozenArray<DOMString> types;
  DOMString getData(DOMString format);
  undefined setData(DOMString format, DOMString data);
  undefined clearData(optional DOMString format);
  [SameObject] readonly attribute FileList files;
};
dataTransfer = new DataTransfer()

DataTransfer/DataTransfer

Support in all current engines.

Firefox62+Safari14.1+Chrome59+
Opera46+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android62+Safari iOS14.5+Chrome Android59+WebView Android59+Samsung Internet8.0+Opera Android44+

Creates a new DataTransfer object with an empty drag data store.

dataTransfer . dropEffect [ = value ]

DataTransfer/dropEffect

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the kind of operation that is currently selected. If the kind of operation isn't one of those that is allowed by the effectAllowed attribute, then the operation will fail.

Can be set, to change the selected operation.

The possible values are "none", "copy", "link", and "move".

dataTransfer . effectAllowed [ = value ]

DataTransfer/effectAllowed

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the kinds of operations that are to be allowed.

Can be set (during the dragstart event), to change the allowed operations.

The possible values are "none", "copy", "copyLink", "copyMove", "link", "linkMove", "move", "all", and "uninitialized",

dataTransfer . items

DataTransfer/items

Support in all current engines.

Firefox50+Safari11.1+Chrome4+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android52+Safari iOS11.3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12+

Returns a DataTransferItemList object, with the drag data.

dataTransfer . setDragImage(element, x, y)

DataTransfer/setDragImage

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Uses the given element to update the drag feedback, replacing any previously specified feedback.

dataTransfer . types

DataTransfer/types

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns a frozen array listing the formats that were set in the dragstart event. In addition, if any files are being dragged, then one of the types will be the string "Files".

data = dataTransfer . getData(format)

DataTransfer/getData

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns the specified data. If there is no such data, returns the empty string.

dataTransfer . setData(format, data)

DataTransfer/setData

Support in all current engines.

Firefox3.5+Safari5+Chrome3+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12+

Adds the specified data.

dataTransfer . clearData( [ format ] )

DataTransfer/clearData

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Removes the data of the specified formats. Removes all data if the argument is omitted.

dataTransfer . files

DataTransfer/files

Support in all current engines.

Firefox3.6+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

Returns a FileList of the files being dragged, if any.

DataTransfer objects that are created as part of drag-and-drop events are only valid while those events are being fired.

A DataTransfer object is associated with a drag data store while it is valid.

A DataTransfer object has an associated types array, which is a FrozenArray<DOMString>, initially empty. When the contents of the DataTransfer object's drag data store item list change, or when the DataTransfer object becomes no longer associated with a drag data store, run the following steps:

  1. Let L be an empty sequence.

  2. If the DataTransfer object is still associated with a drag data store, then:

    1. For each item in the DataTransfer object's drag data store item list whose kind is text, add an entry to L consisting of the item's type string.

    2. If there are any items in the DataTransfer object's drag data store item list whose kind is File, then add an entry to L consisting of the string "Files". (This value can be distinguished from the other values because it is not lowercase.)

  3. Set the DataTransfer object's types array to the result of creating a frozen array from L.

The DataTransfer() constructor, when invoked, must return a newly created DataTransfer object initialized as follows:

  1. Set the drag data store's item list to be an empty list.

  2. Set the drag data store's mode to read/write mode.

  3. Set the dropEffect and effectAllowed to "none".

The dropEffect attribute controls the drag-and-drop feedback that the user is given during a drag-and-drop operation. When the DataTransfer object is created, the dropEffect attribute is set to a string value. On getting, it must return its current value. On setting, if the new value is one of "none", "copy", "link", or "move", then the attribute's current value must be set to the new value. Other values must be ignored.

The effectAllowed attribute is used in the drag-and-drop processing model to initialize the dropEffect attribute during the dragenter and dragover events. When the DataTransfer object is created, the effectAllowed attribute is set to a string value. On getting, it must return its current value. On setting, if drag data store's mode is the read/write mode and the new value is one of "none", "copy", "copyLink", "copyMove", "link", "linkMove", "move", "all", or "uninitialized", then the attribute's current value must be set to the new value. Otherwise it must be left unchanged.

The items attribute must return a DataTransferItemList object associated with the DataTransfer object.

The setDragImage(element, x, y) method must run the following steps:

  1. If the DataTransfer object is no longer associated with a drag data store, return. Nothing happens.

  2. If the drag data store's mode is not the read/write mode, return. Nothing happens.

  3. If element is an img element, then set the drag data store bitmap to the element's image (at its intrinsic size); otherwise, set the drag data store bitmap to an image generated from the given element (the exact mechanism for doing so is not currently specified).

  4. Set the drag data store hot spot coordinate to the given x, y coordinate.

The types attribute must return this DataTransfer object's types array.

The getData(format) method must run the following steps:

  1. If the DataTransfer object is no longer associated with a drag data store, then return the empty string.

  2. If the drag data store's mode is the protected mode, then return the empty string.

  3. Let format be the first argument, converted to ASCII lowercase.

  4. Let convert-to-URL be false.

  5. If format equals "text", change it to "text/plain".

  6. If format equals "url", change it to "text/uri-list" and set convert-to-URL to true.

  7. If there is no item in the drag data store item list whose kind is text and whose type string is equal to format, return the empty string.

  8. Let result be the data of the item in the drag data store item list whose kind is Plain Unicode string and whose type string is equal to format.

  9. If convert-to-URL is true, then parse result as appropriate for text/uri-list data, and then set result to the first URL from the list, if any, or the empty string otherwise. [RFC2483]

  10. Return result.

The setData(format, data) method must run the following steps:

  1. If the DataTransfer object is no longer associated with a drag data store, return. Nothing happens.

  2. If the drag data store's mode is not the read/write mode, return. Nothing happens.

  3. Let format be the first argument, converted to ASCII lowercase.

  4. If format equals "text", change it to "text/plain".

    If format equals "url", change it to "text/uri-list".

  5. Remove the item in the drag data store item list whose kind is text and whose type string is equal to format, if there is one.

  6. Add an item to the drag data store item list whose kind is text, whose type string is equal to format, and whose data is the string given by the method's second argument.

The clearData() method must run the following steps:

  1. If the DataTransfer object is no longer associated with a drag data store, return. Nothing happens.

  2. If the drag data store's mode is not the read/write mode, return. Nothing happens.

  3. If the method was called with no arguments, remove each item in the drag data store item list whose kind is Plain Unicode string, and return.

  4. Let format be the first argument, converted to ASCII lowercase.

  5. If format equals "text", change it to "text/plain".

    If format equals "url", change it to "text/uri-list".

  6. Remove the item in the drag data store item list whose kind is text and whose type string is equal to format, if there is one.

The clearData() method does not affect whether any files were included in the drag, so the types attribute's list might still not be empty after calling clearData() (it would still contain the "Files" string if any files were included in the drag).

The files attribute must return a live FileList sequence consisting of File objects representing the files found by the following steps. Furthermore, for a given FileList object and a given underlying file, the same File object must be used each time.

  1. Start with an empty list L.

  2. If the DataTransfer object is no longer associated with a drag data store, the FileList is empty. Return the empty list L.

  3. If the drag data store's mode is the protected mode, Return the empty list L.

  4. For each item in the drag data store item list whose kind is File , add the item's data (the file, in particular its name and contents, as well as its type) to the list L.

  5. The files found by these steps are those in the list L.

This version of the API does not expose the types of the files during the drag.

6.9.3.1 The DataTransferItemList interface

DataTransferItemList

Support in all current engines.

Firefox50+Safari6+Chrome13+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android50+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android14+

Each DataTransfer object is associated with a DataTransferItemList object.

[Exposed=Window]
interface DataTransferItemList {
  readonly attribute unsigned long length;
  getter DataTransferItem (unsigned long index);
  DataTransferItem? add(DOMString data, DOMString type);
  DataTransferItem? add(File data);
  undefined remove(unsigned long index);
  undefined clear();
};
items . length

DataTransferItemList/length

Support in all current engines.

Firefox50+Safari6+Chrome13+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android50+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android14+

Returns the number of items in the drag data store.

items[index]

Returns the DataTransferItem object representing the indexth entry in the drag data store.

items . remove(index)

DataTransferItemList/remove

Support in all current engines.

Firefox50+Safari6+Chrome31+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android50+Safari iOS6+Chrome Android31+WebView Android4.4.3+Samsung Internet2.0+Opera Android14+

Removes the indexth entry in the drag data store.

items . clear()

DataTransferItemList/clear

Support in all current engines.

Firefox50+Safari6+Chrome13+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android50+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android14+

Removes all the entries in the drag data store.

items . add(data)

DataTransferItemList/add

Support in all current engines.

Firefox50+Safari6+Chrome13+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android50+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android14+
items . add(data, type)

Adds a new entry for the given data to the drag data store. If the data is plain text then a type string has to be provided also.

While the DataTransferItemList object's DataTransfer object is associated with a drag data store, the DataTransferItemList object's mode is the same as the drag data store mode. When the DataTransferItemList object's DataTransfer object is not associated with a drag data store, the DataTransferItemList object's mode is the disabled mode. The drag data store referenced in this section (which is used only when the DataTransferItemList object is not in the disabled mode) is the drag data store with which the DataTransferItemList object's DataTransfer object is associated.

The length attribute must return zero if the object is in the disabled mode; otherwise it must return the number of items in the drag data store item list.

When a DataTransferItemList object is not in the disabled mode, its supported property indices are the numbers in the range 0 .. n-1, where n is the number of items in the drag data store item list.

To determine the value of an indexed property i of a DataTransferItemList object, the user agent must return a DataTransferItem object representing the ith item in the drag data store. The same object must be returned each time a particular item is obtained from this DataTransferItemList object. The DataTransferItem object must be associated with the same DataTransfer object as the DataTransferItemList object when it is first created.

The add() method must run the following steps:

  1. If the DataTransferItemList object is not in the read/write mode, return null.

  2. Jump to the appropriate set of steps from the following list:

    If the first argument to the method is a string

    If there is already an item in the drag data store item list whose kind is text and whose type string is equal to the value of the method's second argument, converted to ASCII lowercase, then throw a "NotSupportedError" DOMException.

    Otherwise, add an item to the drag data store item list whose kind is text, whose type string is equal to the value of the method's second argument, converted to ASCII lowercase, and whose data is the string given by the method's first argument.

    If the first argument to the method is a File

    Add an item to the drag data store item list whose kind is File, whose type string is the type of the File, converted to ASCII lowercase, and whose data is the same as the File's data.

  3. Determine the value of the indexed property corresponding to the newly added item, and return that value (a newly created DataTransferItem object).

The remove() method, when invoked with the argument i, must run these steps:

  1. If the DataTransferItemList object is not in the read/write mode, throw an "InvalidStateError" DOMException.

  2. Remove the ith item from the drag data store.

The clear() method, if the DataTransferItemList object is in the read/write mode, must remove all the items from the drag data store. Otherwise, it must do nothing.

6.9.3.2 The DataTransferItem interface

DataTransferItem

Support in all current engines.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android50+Safari iOS5+Chrome Android18+WebView Android4+Samsung Internet1.0+Opera Android14+

Each DataTransferItem object is associated with a DataTransfer object.

[Exposed=Window]
interface DataTransferItem {
  readonly attribute DOMString kind;
  readonly attribute DOMString type;
  undefined getAsString(FunctionStringCallback? _callback);
  File? getAsFile();
};

callback FunctionStringCallback = undefined (DOMString data);
item . kind

DataTransferItem/kind

Support in all current engines.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android50+Safari iOS5+Chrome Android18+WebView Android4+Samsung Internet1.0+Opera Android14+

Returns the drag data item kind, one of: "string", "file".

item . type

DataTransferItem/type

Support in all current engines.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android50+Safari iOS5+Chrome Android18+WebView Android4+Samsung Internet1.0+Opera Android14+

Returns the drag data item type string.

item . getAsString(callback)

DataTransferItem/getAsString

Support in all current engines.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android50+Safari iOS5+Chrome Android18+WebView Android4+Samsung Internet1.0+Opera Android14+

Invokes the callback with the string data as the argument, if the drag data item kind is text.

file = item . getAsFile()

DataTransferItem/getAsFile

Support in all current engines.

Firefox50+Safari5.1+Chrome11+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android50+Safari iOS5+Chrome Android18+WebView Android4+Samsung Internet1.0+Opera Android14+

Returns a File object, if the drag data item kind is File.

While the DataTransferItem object's DataTransfer object is associated with a drag data store and that drag data store's drag data store item list still contains the item that the DataTransferItem object represents, the DataTransferItem object's mode is the same as the drag data store mode. When the DataTransferItem object's DataTransfer object is not associated with a drag data store, or if the item that the DataTransferItem object represents has been removed from the relevant drag data store item list, the DataTransferItem object's mode is the disabled mode. The drag data store referenced in this section (which is used only when the DataTransferItem object is not in the disabled mode) is the drag data store with which the DataTransferItem object's DataTransfer object is associated.

The kind attribute must return the empty string if the DataTransferItem object is in the disabled mode; otherwise it must return the string given in the cell from the second column of the following table from the row whose cell in the first column contains the drag data item kind of the item represented by the DataTransferItem object:

Kind String
Text "string"
File "file"

The type attribute must return the empty string if the DataTransferItem object is in the disabled mode; otherwise it must return the drag data item type string of the item represented by the DataTransferItem object.

The getAsString(callback) method must run the following steps:

  1. If the callback is null, return.

  2. If the DataTransferItem object is not in the read/write mode or the read-only mode, return. The callback is never invoked.

  3. If the drag data item kind is not text, then return. The callback is never invoked.

  4. Otherwise, queue a task to invoke callback, passing the actual data of the item represented by the DataTransferItem object as the argument.

The getAsFile() method must run the following steps:

  1. If the DataTransferItem object is not in the read/write mode or the read-only mode, then return null.

  2. If the drag data item kind is not File, then return null.

  3. Return a new File object representing the actual data of the item represented by the DataTransferItem object.

6.9.4 The DragEvent interface

DragEvent/DragEvent

Support in all current engines.

Firefox3.5+Safari3.1+Chrome46+
Opera12+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android4+Safari iOSNoChrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo

DragEvent

Support in all current engines.

Firefox3.5+Safari3.1+Chrome3+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOSNoChrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo

The drag-and-drop processing model involves several events. They all use the DragEvent interface.

[Exposed=Window]
interface DragEvent : MouseEvent {
  constructor(DOMString type, optional DragEventInit eventInitDict = {});

  readonly attribute DataTransfer? dataTransfer;
};

dictionary DragEventInit : MouseEventInit {
  DataTransfer? dataTransfer = null;
};
event . dataTransfer

DragEvent/dataTransfer

Support in all current engines.

Firefox3.5+Safari3.1+Chrome46+
Opera33+Edge79+
Edge (Legacy)12+Internet Explorer🔰 10+
Firefox Android4+Safari iOSNoChrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo

Returns the DataTransfer object for the event.

Although, for consistency with other event interfaces, the DragEvent interface has a constructor, it is not particularly useful. In particular, there's no way to create a useful DataTransfer object from script, as DataTransfer objects have a processing and security model that is coordinated by the browser during drag-and-drops.

The dataTransfer attribute of the DragEvent interface must return the value it was initialized to. It represents the context information for the event.

When a user agent is required to fire a DND event named e at an element, using a particular drag data store, and optionally with a specific related target, the user agent must run the following steps:

  1. Let dataDragStoreWasChanged be false.
  2. If no specific related target was provided, set related target to null.

  3. Let window be the relevant global object of the Document object of the specified target element.

  4. If e is dragstart, then set the drag data store mode to the read/write mode and set dataDragStoreWasChanged to true.

    If e is drop, set the drag data store mode to the read-only mode.

  5. Let dataTransfer be a newly created DataTransfer object associated with the given drag data store.

  6. Set the effectAllowed attribute to the drag data store's drag data store allowed effects state.

  7. Set the dropEffect attribute to "none" if e is dragstart, drag, or dragleave; to the value corresponding to the current drag operation if e is drop or dragend; and to a value based on the effectAllowed attribute's value and the drag-and-drop source, as given by the following table, otherwise (i.e. if e is dragenter or dragover):

    effectAlloweddropEffect
    "none""none"
    "copy""copy"
    "copyLink""copy", or, if appropriate, "link"
    "copyMove""copy", or, if appropriate, "move"
    "all""copy", or, if appropriate, either "link" or "move"
    "link""link"
    "linkMove""link", or, if appropriate, "move"
    "move""move"
    "uninitialized" when what is being dragged is a selection from a text control"move", or, if appropriate, either "copy" or "link"
    "uninitialized" when what is being dragged is a selection"copy", or, if appropriate, either "link" or "move"
    "uninitialized" when what is being dragged is an a element with an href attribute"link", or, if appropriate, either "copy" or "move"
    Any other case"copy", or, if appropriate, either "link" or "move"

    Where the table above provides possibly appropriate alternatives, user agents may instead use the listed alternative values if platform conventions dictate that the user has requested those alternate effects.

    For example, Windows platform conventions are such that dragging while holding the "alt" key indicates a preference for linking the data, rather than moving or copying it. Therefore, on a Windows system, if "link" is an option according to the table above while the "alt" key is depressed, the user agent could select that instead of "copy" or "move".

  8. Let event be the result of creating an event using DragEvent.

  9. Initialize event's type attribute to e, its bubbles attribute to true, its view attribute to window, its relatedTarget attribute to related target, and its dataTransfer attribute to dataTransfer.

  10. If e is not dragleave or dragend, then initialize event's cancelable attribute to true.

  11. Initialize event's mouse and key attributes initialized according to the state of the input devices as they would be for user interaction events.

    If there is no relevant pointing device, then initialize event's screenX, screenY, clientX, clientY, and button attributes to 0.

  12. Dispatch event at the specified target element.

  13. Set the drag data store allowed effects state to the current value of dataTransfer's effectAllowed attribute. (It can only have changed value if e is dragstart.)

  14. If dataDragStoreWasChanged is true, then set the drag data store mode back to the protected mode.

  15. Break the association between dataTransfer and the drag data store.

6.9.5 Processing model

When the user attempts to begin a drag operation, the user agent must run the following steps. User agents must act as if these steps were run even if the drag actually started in another document or application and the user agent was not aware that the drag was occurring until it intersected with a document under the user agent's purview.

  1. Determine what is being dragged, as follows:

    If the drag operation was invoked on a selection, then it is the selection that is being dragged.

    Otherwise, if the drag operation was invoked on a Document, it is the first element, going up the ancestor chain, starting at the node that the user tried to drag, that has the IDL attribute draggable set to true. If there is no such element, then nothing is being dragged; return, the drag-and-drop operation is never started.

    Otherwise, the drag operation was invoked outside the user agent's purview. What is being dragged is defined by the document or application where the drag was started.

    img elements and a elements with an href attribute have their draggable attribute set to true by default.

  2. Create a drag data store. All the DND events fired subsequently by the steps in this section must use this drag data store.

  3. Establish which DOM node is the source node, as follows:

    If it is a selection that is being dragged, then the source node is the Text node that the user started the drag on (typically the Text node that the user originally clicked). If the user did not specify a particular node, for example if the user just told the user agent to begin a drag of "the selection", then the source node is the first Text node containing a part of the selection.

    Otherwise, if it is an element that is being dragged, then the source node is the element that is being dragged.

    Otherwise, the source node is part of another document or application. When this specification requires that an event be dispatched at the source node in this case, the user agent must instead follow the platform-specific conventions relevant to that situation.

    Multiple events are fired on the source node during the course of the drag-and-drop operation.

  4. Determine the list of dragged nodes, as follows:

    If it is a selection that is being dragged, then the list of dragged nodes contains, in tree order, every node that is partially or completely included in the selection (including all their ancestors).

    Otherwise, the list of dragged nodes contains only the source node, if any.

  5. If it is a selection that is being dragged, then add an item to the drag data store item list, with its properties set as follows:

    The drag data item type string
    "text/plain"
    The drag data item kind
    Text
    The actual data
    The text of the selection

    Otherwise, if any files are being dragged, then add one item per file to the drag data store item list, with their properties set as follows:

    The drag data item type string
    The MIME type of the file, if known, or "application/octet-stream" otherwise.
    The drag data item kind
    File
    The actual data
    The file's contents and name.

    Dragging files can currently only happen from outside a browsing context, for example from a file system manager application.

    If the drag initiated outside of the application, the user agent must add items to the drag data store item list as appropriate for the data being dragged, honoring platform conventions where appropriate; however, if the platform conventions do not use MIME types to label dragged data, the user agent must make a best-effort attempt to map the types to MIME types, and, in any case, all the drag data item type strings must be converted to ASCII lowercase.

    User agents may also add one or more items representing the selection or dragged element(s) in other forms, e.g. as HTML.

  6. If the list of dragged nodes is not empty, then extract the microdata from those nodes into a JSON form, and add one item to the drag data store item list, with its properties set as follows:

    The drag data item type string
    application/microdata+json
    The drag data item kind
    Text
    The actual data
    The resulting JSON string.
  7. Run the following substeps:

    1. Let urls be an empty list of absolute URLs.

    2. For each node in the list of dragged nodes:

      If the node is an a element with an href attribute
      Add to urls the result of parsing the element's href content attribute relative to the element's node document.
      If the node is an img element with a src attribute
      Add to urls the result of parsing the element's src content attribute relative to the element's node document.
    3. If urls is still empty, then return.

    4. Let url string be the result of concatenating the strings in urls, in the order they were added, separated by a U+000D CARRIAGE RETURN U+000A LINE FEED character pair (CRLF).

    5. Add one item to the drag data store item list, with its properties set as follows:

      The drag data item type string
      text/uri-list
      The drag data item kind
      Text
      The actual data
      url string
  8. Update the drag data store default feedback as appropriate for the user agent (if the user is dragging the selection, then the selection would likely be the basis for this feedback; if the user is dragging an element, then that element's rendering would be used; if the drag began outside the user agent, then the platform conventions for determining the drag feedback should be used).

  9. Fire a DND event named dragstart at the source node.

    If the event is canceled, then the drag-and-drop operation should not occur; return.

    Since events with no event listeners registered are, almost by definition, never canceled, drag-and-drop is always available to the user if the author does not specifically prevent it.

  10. Initiate the drag-and-drop operation in a manner consistent with platform conventions, and as described below.

    The drag-and-drop feedback must be generated from the first of the following sources that is available:

    1. The drag data store bitmap, if any. In this case, the drag data store hot spot coordinate should be used as hints for where to put the cursor relative to the resulting image. The values are expressed as distances in CSS pixels from the left side and from the top side of the image respectively. [CSS]
    2. The drag data store default feedback.

From the moment that the user agent is to initiate the drag-and-drop operation, until the end of the drag-and-drop operation, device input events (e.g. mouse and keyboard events) must be suppressed.

During the drag operation, the element directly indicated by the user as the drop target is called the immediate user selection. (Only elements can be selected by the user; other nodes must not be made available as drop targets.) However, the immediate user selection is not necessarily the current target element, which is the element currently selected for the drop part of the drag-and-drop operation.

The immediate user selection changes as the user selects different elements (either by pointing at them with a pointing device, or by selecting them in some other way). The current target element changes when the immediate user selection changes, based on the results of event listeners in the document, as described below.

Both the current target element and the immediate user selection can be null, which means no target element is selected. They can also both be elements in other (DOM-based) documents, or other (non-web) programs altogether. (For example, a user could drag text to a word-processor.) The current target element is initially null.

In addition, there is also a current drag operation, which can take on the values "none", "copy", "link", and "move". Initially, it has the value "none". It is updated by the user agent as described in the steps below.

User agents must, as soon as the drag operation is initiated and every 350ms (±200ms) thereafter for as long as the drag operation is ongoing, queue a task to perform the following steps in sequence:

  1. If the user agent is still performing the previous iteration of the sequence (if any) when the next iteration becomes due, return for this iteration (effectively "skipping missed frames" of the drag-and-drop operation).

  2. Fire a DND event named drag at the source node. If this event is canceled, the user agent must set the current drag operation to "none" (no drag operation).

  3. If the drag event was not canceled and the user has not ended the drag-and-drop operation, check the state of the drag-and-drop operation, as follows:

    1. If the user is indicating a different immediate user selection than during the last iteration (or if this is the first iteration), and if this immediate user selection is not the same as the current target element, then update the current target element as follows:

      If the new immediate user selection is null

      Set the current target element to null also.

      If the new immediate user selection is in a non-DOM document or application

      Set the current target element to the immediate user selection.

      Otherwise

      Fire a DND event named dragenter at the immediate user selection.

      If the event is canceled, then set the current target element to the immediate user selection.

      Otherwise, run the appropriate step from the following list:

      If the immediate user selection is a text control (e.g., textarea, or an input element whose type attribute is in the Text state) or an editing host or editable element, and the drag data store item list has an item with the drag data item type string "text/plain" and the drag data item kind text

      Set the current target element to the immediate user selection anyway.

      If the immediate user selection is the body element

      Leave the current target element unchanged.

      Otherwise

      Fire a DND event named dragenter at the body element, if there is one, or at the Document object, if not. Then, set the current target element to the body element, regardless of whether that event was canceled or not.

    2. If the previous step caused the current target element to change, and if the previous target element was not null or a part of a non-DOM document, then fire a DND event named dragleave at the previous target element, with the new current target element as the specific related target.

    3. If the current target element is a DOM element, then fire a DND event named dragover at this current target element.

      If the dragover event is not canceled, run the appropriate step from the following list:

      If the current target element is a text control (e.g., textarea, or an input element whose type attribute is in the Text state) or an editing host or editable element, and the drag data store item list has an item with the drag data item type string "text/plain" and the drag data item kind text

      Set the current drag operation to either "copy" or "move", as appropriate given the platform conventions.

      Otherwise

      Reset the current drag operation to "none".

      Otherwise (if the dragover event is canceled), set the current drag operation based on the values of the effectAllowed and dropEffect attributes of the DragEvent object's dataTransfer object as they stood after the event dispatch finished, as per the following table:

      effectAlloweddropEffectDrag operation
      "uninitialized", "copy", "copyLink", "copyMove", or "all""copy""copy"
      "uninitialized", "link", "copyLink", "linkMove", or "all""link""link"
      "uninitialized", "move", "copyMove", "linkMove", or "all""move""move"
      Any other case"none"
    4. Otherwise, if the current target element is not a DOM element, use platform-specific mechanisms to determine what drag operation is being performed (none, copy, link, or move), and set the current drag operation accordingly.

    5. Update the drag feedback (e.g. the mouse cursor) to match the current drag operation, as follows:

      Drag operationFeedback
      "copy"Data will be copied if dropped here.
      "link"Data will be linked if dropped here.
      "move"Data will be moved if dropped here.
      "none"No operation allowed, dropping here will cancel the drag-and-drop operation.
  4. Otherwise, if the user ended the drag-and-drop operation (e.g. by releasing the mouse button in a mouse-driven drag-and-drop interface), or if the drag event was canceled, then this will be the last iteration. Run the following steps, then stop the drag-and-drop operation:

    1. If the current drag operation is "none" (no drag operation), or, if the user ended the drag-and-drop operation by canceling it (e.g. by hitting the Escape key), or if the current target element is null, then the drag operation failed. Run these substeps:

      1. Let dropped be false.

      2. If the current target element is a DOM element, fire a DND event named dragleave at it; otherwise, if it is not null, use platform-specific conventions for drag cancelation.

      3. Set the current drag operation to "none".

      Otherwise, the drag operation might be a success; run these substeps:

      1. Let dropped be true.

      2. If the current target element is a DOM element, fire a DND event named drop at it; otherwise, use platform-specific conventions for indicating a drop.

      3. If the event is canceled, set the current drag operation to the value of the dropEffect attribute of the DragEvent object's dataTransfer object as it stood after the event dispatch finished.

        Otherwise, the event is not canceled; perform the event's default action, which depends on the exact target as follows:

        If the current target element is a text control (e.g., textarea, or an input element whose type attribute is in the Text state) or an editing host or editable element, and the drag data store item list has an item with the drag data item type string "text/plain" and the drag data item kind text

        Insert the actual data of the first item in the drag data store item list to have a drag data item type string of "text/plain" and a drag data item kind that is text into the text control or editing host or editable element in a manner consistent with platform-specific conventions (e.g. inserting it at the current mouse cursor position, or inserting it at the end of the field).

        Otherwise

        Reset the current drag operation to "none".

    2. Fire a DND event named dragend at the source node.

    3. Run the appropriate steps from the following list as the default action of the dragend event:

      If dropped is true, the current target element is a text control (see below), the current drag operation is "move", and the source of the drag-and-drop operation is a selection in the DOM that is entirely contained within an editing host

      Delete the selection.

      If dropped is true, the current target element is a text control (see below), the current drag operation is "move", and the source of the drag-and-drop operation is a selection in a text control

      The user agent should delete the dragged selection from the relevant text control.

      If dropped is false or if the current drag operation is "none"

      The drag was canceled. If the platform conventions dictate that this be represented to the user (e.g. by animating the dragged selection going back to the source of the drag-and-drop operation), then do so.

      Otherwise

      The event has no default action.

      For the purposes of this step, a text control is a textarea element or an input element whose type attribute is in one of the Text, Search, Tel, URL, Email, Password, or Number states.

User agents are encouraged to consider how to react to drags near the edge of scrollable regions. For example, if a user drags a link to the bottom of the viewport on a long page, it might make sense to scroll the page so that the user can drop the link lower on the page.

This model is independent of which Document object the nodes involved are from; the events are fired as described above and the rest of the processing model runs as described above, irrespective of how many documents are involved in the operation.

6.9.6 Events summary

This section is non-normative.

The following events are involved in the drag-and-drop model.

Event name Target Cancelable? Drag data store mode dropEffect Default Action
dragstart

Document/dragstart_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome4+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox AndroidNoSafari iOS11+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo
Source node✓ CancelableRead/write mode "none"Initiate the drag-and-drop operation
drag

Document/drag_event

Firefox🔰 3.5+Safari3.1+Chrome4+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox AndroidNoSafari iOS11+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo
Source node✓ CancelableProtected mode "none"Continue the drag-and-drop operation
dragenter

Document/dragenter_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome4+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox AndroidNoSafari iOS11+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo
Immediate user selection or the body element✓ CancelableProtected mode Based on effectAllowed valueReject immediate user selection as potential target element
dragleave

Document/dragleave_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome4+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox AndroidNoSafari iOS11+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo
Previous target elementProtected mode "none"None
dragover

Document/dragover_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome4+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox AndroidNoSafari iOS11+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo
Current target element✓ CancelableProtected mode Based on effectAllowed valueReset the current drag operation to "none"
drop

Document/drop_event

Support in all current engines.

Firefox3.5+Safari3.1+Chrome4+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox AndroidNoSafari iOS11+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo
Current target element✓ CancelableRead-only mode Current drag operationVaries
dragend

Document/dragend_event

Firefox🔰 3.5+Safari3.1+Chrome4+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox AndroidNoSafari iOS11+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo
Source nodeProtected mode Current drag operationVaries

Not shown in the above table: all these events bubble, are composed, and the effectAllowed attribute always has the value it had after the dragstart event, defaulting to "uninitialized" in the dragstart event.

6.9.7 The draggable attribute

Global_attributes/draggable

Support in all current engines.

Firefox2+SafariYesChromeYes
Opera12+EdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox Android4+Safari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

All HTML elements may have the draggable content attribute set. The draggable attribute is an enumerated attribute. It has three states. The first state is true and it has the keyword true. The second state is false and it has the keyword false. The third state is auto; it has no keywords but it is the missing value default and the invalid value default.

The true state means the element is draggable; the false state means that it is not. The auto state uses the default behavior of the user agent.

An element with a draggable attribute should also have a title attribute that names the element for the purpose of non-visual interactions.

element . draggable [ = value ]

Returns true if the element is draggable; otherwise, returns false.

Can be set, to override the default and set the draggable content attribute.

The draggable IDL attribute, whose value depends on the content attribute's in the way described below, controls whether or not the element is draggable. Generally, only text selections are draggable, but elements whose draggable IDL attribute is true become draggable as well.

If an element's draggable content attribute has the state true, the draggable IDL attribute must return true.

Otherwise, if the element's draggable content attribute has the state false, the draggable IDL attribute must return false.

Otherwise, the element's draggable content attribute has the state auto. If the element is an img element, an object element that represents an image, or an a element with an href content attribute, the draggable IDL attribute must return true; otherwise, the draggable IDL attribute must return false.

If the draggable IDL attribute is set to the value false, the draggable content attribute must be set to the literal value "false". If the draggable IDL attribute is set to the value true, the draggable content attribute must be set to the literal value "true".

6.9.8 拖放模型中的安全风险

用户代理在 dragstart 事件对脚本可用的期间, 不得把数据添加到 DataTransfer 对象, 直到 drop 事件为止。 因为否则的话,如果用户从一个文档拖动敏感信息到第二个文档,过程中经过了一个恶意的第三个文档, 这个恶意的文档就可以截获数据。

同样的原因,只有在用户明确停止了拖动操作时用户代理才能认为拖放操作成功。 — 如果任何脚本停止了拖动操作,就必须把它视为未成功的(取消的)并且不得触发 drop 事件。

用户代理应该小心不要被脚本触发拖放操作。例如,在有鼠标和窗口的环境中, 如果在用户按下鼠标的过程中一个脚本移动了窗口,用户代理不得把它视为一个拖放操作。 这很重要,否则的话用户代理可能会在未经用户同意的情况下把数据从敏感数据源拖动到恶意的文档中。

在拖动和释放时,用户代理应该使用已知的安全特性白名单来过滤掉可能包含的活跃 (比如脚本)内容(比如 HTML)。类似地,应该把 相对 URL 转为绝对 URL 来避免引用发生预期之外的改变。本规范没有指定具体如何操作。

考虑一个恶意的页面,提供了一些内容并诱导用户选择和拖放(或者拷贝和粘贴) 该内容给一个受害页面 contenteditable 区域。 如果浏览器不确保拖动的只有安全内容,就可能释放(或粘贴)非安全内容(比如脚本和选中的事件处理器) 到受害站点,获取该站点的权限。可能因此导致跨站脚本攻击。

7 加载 Web 页面

This section describes features that apply most directly to Web browsers. Having said that, except where specified otherwise, the requirements defined in this section do apply to all user agents, whether they are Web browsers or not.

7.1 Browsing contexts

A browsing context is an environment in which Document objects are presented to the user.

A tab or window in a web browser typically contains a browsing context, as does an iframe or frames in a frameset.

A browsing context has a corresponding WindowProxy object.

A browsing context has an opener browsing context, which is null or a browsing context. It is initially null.

A browsing context has a disowned boolean. It is initially false.

A browsing context has an is closing boolean. It is initially false.

The following example illustrates the various possibilities of a browsing context. It can be disowned, is closing, neither, or both.

// Neither disowned nor is closing:
const popup1 = window.open();

// Disowned, but not is closing:
const popup2 = window.open();
popup2.opener = null;

// Not disowned, but is closing:
const popup3 = window.open();
popup3.close();

// Disowned, is closing:
const popup4 = window.open();
popup4.opener = null;
popup4.close();

A browsing context has a session history, which lists the Document objects that the browsing context has presented, is presenting, or will present. A Document's browsing context is the browsing context whose session history contains the Document, if any such browsing context exists and has not been discarded, and null otherwise.

A Document does not necessarily have a non-null browsing context. In particular, data mining tools are likely to never instantiate browsing contexts. A Document created using an API such as createDocument() never has a non-null browsing context. And the Document originally created for an iframe element, which has since been removed from the document, has no associated browsing context, since that browsing context was discarded.

A browsing context's active window is its WindowProxy object's [[Window]] internal slot value. A browsing context's active document is its active window's associated Document.

In general, there is a 1-to-1 mapping from the Window object to the Document object, as long as the Document object has a non-null browsing context. There is one exception. A Window can be reused for the presentation of a second Document in the same browsing context, such that the mapping is then 1-to-2. This occurs when a browsing context is navigated from the initial about:blank Document to another, with historyHandling set to "replace".

7.1.1 Creating browsing contexts

To set the active document of a browsing context browsingContext to a Document object document, run these steps:

  1. Let window be document's relevant global object.

    Per this standard document can be created before window, which does not make much sense. See issue #2688.

  2. Set browsingContext's active window to window.

  3. Set window's associated Document to document.

  4. Set window's relevant settings object's execution ready flag.


A browsing context has an associated creator origin (null or returns an origin), creator URL (null or returns a URL), and creator base URL (null or returns a URL). These are all initially null.

To determine the origin, given browsing context browsingContext, URL url, sandboxing flag set sandboxFlags, and two origins invocationOrigin and activeDocumentNavigationOrigin:

  1. If sandboxFlags has its sandboxed origin browsing context flag set, then return a new opaque origin.

  2. If url is null, then return a new opaque origin.

  3. If activeDocumentNavigationOrigin is not null, and url's scheme is "javascript", then return activeDocumentNavigationOrigin.

  4. If invocationOrigin is non-null and url is about:blank, then return invocationOrigin.

    The result here is that two documents end up with the same underlying origin, meaning that document.domain affects both.

  5. If url is about:srcdoc, then return the origin of browsingContext's container document.

  6. Return url's origin.

To create a new browsing context, given null or a Document object creator, null or an element embedder, and a browsing context group group, run these steps:

  1. Let browsingContext be a new browsing context.

  2. If creator is non-null, then set browsingContext's creator origin to return creator's origin, browsingContext's creator URL to return creator's URL, and browsingContext's creator base URL to return creator's base URL.

  3. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and embedder.

  4. Let origin be the result of determining the origin given browsingContext, about:blank, sandboxFlags, browsingContext's creator origin, and null.

  5. Let permissionsPolicy be the result of creating a permissions policy given browsingContext and origin. [PERMISSIONSPOLICY]

    This needs to use embedder.

  6. Let agent be the result of obtaining a similar-origin window agent given origin, group, and false.

  7. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:

  8. Let topLevelCreationURL be about:blank if embedder is null; otherwise embedder's relevant settings object's top-level creation URL.

  9. Let topLevelOrigin be origin if embedder is null; otherwise embedder's relevant settings object's top-level origin.

  10. Let settingsObject be the result of setting up a window environment settings object with realm execution context, null, topLevelCreationURL, and topLevelOrigin.

  11. Let coop be "unsafe-none".

  12. If creator is non-null and creator's origin is same origin with creator's relevant settings object's top-level origin, then set coop to creator's browsing context's top-level browsing context's active document's cross-origin opener policy.

  13. Let document be a new Document, marked as an HTML document in quirks mode, whose content type is "text/html", origin is origin, active sandboxing flag set is sandboxFlags, permissions policy is permissionsPolicy, cross-origin opener policy is coop, and which is ready for post-load tasks.

  14. Ensure that document has a single child html node, which itself has two empty child nodes: a head element, and a body element.

  15. Set the active document of browsingContext to document.

  16. If browsingContext's creator URL is non-null, then set document's referrer to the serialization of it.

  17. If creator is non-null, then set document's referrer policy to creator's referrer policy.

  18. If creator is non-null, then set document's embedder policy to creator's embedder policy.

  19. Add document to browsingContext's session history.

  20. Completely finish loading document.

  21. Return browsingContext.

To create a new top-level browsing context:

  1. Let group be the result of creating a new browsing context group.

  2. Return group's browsing context set[0].

This creates a top-level browsing context.

To create a new auxiliary browsing context, given a browsing context opener:

  1. Let group be opener's top-level browsing context's group

  2. Assert: group is non-null, as navigating invokes this directly.

  3. Let browsingContext be the result of creating a new browsing context with opener's active document, null, and group.

  4. Append browsingContext to group.

  5. Set browsingContext's opener browsing context to opener.

  6. Legacy-clone a browsing session storage shed with opener's browsing session and browsingContext's browsing session. [STORAGE]

  7. Return browsingContext.

This creates a top-level browsing context that is also an auxiliary browsing context.

To create a new nested browsing context, given an element element:

  1. Let group be element's node document's browsing context's top-level browsing context's group.

  2. Let browsingContext be the result of creating a new browsing context with element's node document, element, and group.

  3. Set element's nested browsing context to browsingContext.

  4. If element has a name attribute, then set browsingContext's name to the value of this attribute.

7.1.2 Related browsing contexts

Certain elements (for example, iframe elements) can instantiate further browsing contexts. These elements are called browsing context containers.

Each browsing context container has a nested browsing context, which is either a browsing context or null. It is initially null.

The container of a browsing context bc is the browsing context container whose nested browsing context is bc, or null if there is no such element.

Each browsing context bc has a container document, which is the result of running these steps:

  1. If bc's container is null, then return null.

  2. Return bc's container's node document.

    This is equal to bc's container's shadow-including root as bc's container has to be connected.

A browsing context child is said to be a child browsing context of another browsing context parent, if child's container document is non-null and child's container document's browsing context is parent.

A browsing context child is a document-tree child browsing context of parent if child is a child browsing context and child's container is in a document tree.

A browsing context child may have a parent browsing context. This is the unique browsing context that has child as a child browsing context, if any such browsing context exists. Otherwise, the browsing context has no parent browsing context.

A browsing context A is said to be an ancestor of a browsing context B if there exists a browsing context A' that is a child browsing context of A and that is itself an ancestor of B, or if the browsing context A is the parent browsing context of B.

A browsing context that has no parent browsing context is the top-level browsing context for itself and all of the browsing contexts for which it is an ancestor browsing context.

A top-level browsing context has an associated group (null or a browsing context group). It is initially null.

It is possible to create new browsing contexts that are related to a top-level browsing context while their container is null. Such browsing contexts are called auxiliary browsing contexts. Auxiliary browsing contexts are always top-level browsing contexts.

The transitive closure of parent browsing contexts for a browsing context that is a child browsing context gives the list of ancestor browsing contexts.

The list of the descendant browsing contexts of a Document d is the (ordered) list returned by the following algorithm:

  1. Let list be an empty list.

  2. For each browsing context container container, whose nested browsing context is non-null and whose shadow-including root is d, in shadow-including tree order:

    1. Let nestedBC be container's nested browsing context.

    2. Append nestedBC to list.

    3. Extend list with the list of the descendant browsing contexts of nestedBC's active document.

  3. Return list.

A Document d is said to be fully active when d's browsing context is non-null, d's browsing context's active document is d, and either d's browsing context is a top-level browsing context, or d's container document is fully active.

Because they are associated with an element, child browsing contexts are always tied to a specific Document in their parent browsing context. User agents must not allow the user to interact with child browsing contexts of elements that are in Documents that are not themselves fully active.

The following example illustrates the differences between active and fully active Document objects. Here a.html is loaded into a browser window, b-1.html starts out loaded into an iframe as shown, and b-2.html and c.html are omitted (they can simply be an empty document).

<!-- a.html -->
<!DOCTYPE html>
<html lang="en">
<title>Browsing context A</title>

<iframe src="b-1.html"></iframe>
<button onclick="frames[0].location.href = 'b-2.html'">Click me</button>

<!-- b-1.html -->
<!DOCTYPE html>
<html lang="en">
<title>Browsing context B</title>

<iframe src="c.html"></iframe>

At this point, the documents given by a.html, b-1.html, and c.html are all the active documents of their respective browsing contexts. They are also all fully active.

After clicking on the button, and thus loading a new Document from b-2.html into browsing context B, we have the following results:

For more explorations of the complexities involved here, especially as it impacts the session history, see A Model of Navigation History. [NAVMODEL]

A child browsing context can be put into a delaying load events mode. This is used when it is navigated, to delay the load event of its container before the new Document is created.

The document family of a browsing context consists of the union of all the Document objects in that browsing context's session history and the document families of all those Document objects. The document family of a Document object consists of the union of all the document families of the browsing contexts in the list of the descendant browsing contexts of the Document object.

The content document of a browsing context container container is the result of the following algorithm:

  1. If container's nested browsing context is null, then return null.

  2. Let context be container's nested browsing context.

  3. Let document be context's active document.

  4. If document's origin and container's node document's origin are not same origin-domain, then return null.

  5. Return document.

window . top

Window/top

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the WindowProxy for the top-level browsing context.

window . opener [ = value ]

Window/opener

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Returns the WindowProxy for the opener browsing context.

Returns null if there isn't one or if it has been set to null.

Can be set to null.

window . parent

Window/parent

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Returns the WindowProxy for the parent browsing context.

window . frameElement

Window/frameElement

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the Element for the browsing context container.

Returns null if there isn't one, and in cross-origin situations.

The top attribute's getter must run these steps:

  1. If this Window object's browsing context is null, then return null.

  2. Return this Window object's browsing context's top-level browsing context's WindowProxy object.

The opener attribute's getter must run these steps:

  1. Let current be this Window object's browsing context.

  2. If current is null, then return null.

  3. If current's disowned is true, then return null.

  4. If current's opener browsing context is null, then return null.

  5. Return current's opener browsing context's WindowProxy object.

The opener attribute's setter must run these steps:

  1. If the given value is null and this Window object's browsing context is non-null, then set this Window object's browsing context's disowned to true.

  2. If the given value is non-null, then return ? OrdinaryDefineOwnProperty(this Window object, "opener", { [[Value]]: the given value, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }).

If a browsing context's disowned is true, its window.opener attribute is null. That prevents scripts in the browsing context from changing any properties of its opener browsing context's Window object (i.e., the Window object from which the browsing context was created).

Otherwise, if a browsing context's disowned is false, then scripts in that browsing context can use window.opener to change properties of its opener browsing context's Window object. For example, a script running in the browsing context can change the value of window.opener.location, causing the opener browsing context to navigate to a completely different document.

The parent attribute's getter must run these steps:

  1. Let current be this Window object's browsing context.

  2. If current is null, then return null.

  3. If current is a child browsing context of another browsing context parent, then return parent's WindowProxy object.

  4. Assert: current is a top-level browsing context.

  5. Return current's WindowProxy object.

The frameElement attribute's getter must run these steps:

  1. Let current be this Window object's browsing context.

  2. If current is null, then return null.

  3. Let container be current's container.

  4. If container is null, then return null.

  5. If container's node document's origin is not same origin-domain with the current settings object's origin, then return null.

  6. Return container.

An example of when these IDL attributes can return null is as follows:

<!DOCTYPE html>
<iframe></iframe>

<script>
"use strict";
const element = document.querySelector("iframe");
const iframeWindow = element.contentWindow;
element.remove();

console.assert(iframeWindow.top === null);
console.assert(iframeWindow.parent === null);
console.assert(iframeWindow.frameElement === null);
</script>

Here the browsing context corresponding to iframeWindow was discarded when element was removed from the document.

7.1.3 Security

A browsing context A is familiar with a second browsing context B if one of the following conditions is true:


A browsing context A is allowed to navigate a second browsing context B if the following algorithm returns true:

  1. If A is not the same browsing context as B, and A is not one of the ancestor browsing contexts of B, and B is not a top-level browsing context, and A's active document's active sandboxing flag set has its sandboxed navigation browsing context flag set, then return false.

  2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, then:

    1. If A's active window has transient activation and A's active document's active sandboxing flag set has its sandboxed top-level navigation with user activation browsing context flag set, then return false.

    2. Otherwise, if A's active window does not have transient activation and A's active document's active sandboxing flag set has its sandboxed top-level navigation without user activation browsing context flag set, then return false.

  3. Otherwise, if B is a top-level browsing context, and is neither A nor one of the ancestor browsing contexts of A, and A's Document's active sandboxing flag set has its sandboxed navigation browsing context flag set, and A is not the one permitted sandboxed navigator of B, then return false.

  4. Return true.


An element has a browsing context scope origin if its Document's browsing context is a top-level browsing context or if all of its Document's ancestor browsing contexts all have active documents whose origin are the same origin as the element's node document's origin. If an element has a browsing context scope origin, then its value is the origin of the element's node document.

7.1.4 浏览上下文分组

用户代理持有 浏览上下文分组的集合 (一个 浏览上下文分组集合)。

浏览上下文分组 持有 浏览上下文集合 (一个 顶级浏览上下文集合)。

创建分组时顶级浏览上下文 添加到 组内。 所有后续添加到 组内顶级浏览上下文 都是 附属浏览上下文

浏览上下文组 有一个关联的 代理群映射 (一个 代理群的键代理群 的弱 映射)。 用户代理负责收集已经没有地方能访问的代理群。

浏览上下文组 有一个 跨域隔离 布尔,初始为 false。

浏览上下文组 有一个关联的 历史代理群键映射,是一个 代理群键映射。 通过记录哪些代理群键之前用于给定的源,这个映射用于确保 域隔离 特性的一致性。

历史代理群键映射 的条目只能在浏览上下文组的生命期内获得。

创建浏览上下文组 要执行以下步骤:

  1. group 为一个新的 浏览上下文组

  2. group 到用户代理的 浏览上下文组集合

  3. browsingContext 为用 null, null 和 group 创建新的浏览上下文 的结果。

  4. browsingContext group

  5. 返回 group

顶级浏览上下文 browsingContext 浏览上下文组 group 的步骤如下:

  1. browsingContext 加到 group浏览上下文集合

  2. 设置 browsingContextgroupgroup

移除 顶级浏览上下文 browsingContext 的步骤如下:

  1. 断言 browsingContextgroup 非空,因为 浏览环境 只能 丢弃 一次。

  2. groupbrowsingContextgroup

  3. 设置 browsingContextgroup 为 null。

  4. group浏览上下文集合 移除 browsingContext

  5. 如果 group浏览上下文集合 为空,就从用户代理的 浏览上下文组集合移除 group

追加移除 是定义 浏览上下文组 生命期的基本操作, 会被 创建浏览上下文组创建附属浏览上下文丢弃浏览上下文 调用。


HTML 标准层定义过 "相关浏览上下文单元" 和 "相关 similar-origin 浏览上下文单元"。 因为它们不够充分已经被移除。

7.1.5 Browsing context names

Browsing contexts can have a browsing context name. Unless stated otherwise, it is the empty string.

A valid browsing context name is any string with at least one character that does not start with a U+005F LOW LINE character. (Names starting with an underscore are reserved for special keywords.)

A valid browsing context name or keyword is any string that is either a valid browsing context name or that is an ASCII case-insensitive match for one of: _blank, _self, _parent, or _top.

These values have different meanings based on whether the page is sandboxed or not, as summarized in the following (non-normative) table. In this table, "current" means the browsing context that the link or script is in, "parent" means the parent browsing context of the one the link or script is in, "top" means the top-level browsing context of the one the link or script is in, "new" means a new top-level browsing context or auxiliary browsing context is to be created, subject to various user preferences and user agent policies, "none" means that nothing will happen, and "maybe new" means the same as "new" if the "allow-popups" keyword is also specified on the sandbox attribute (or if the user overrode the sandboxing), and the same as "none" otherwise.

Keyword Ordinary effect Effect in an iframe with...
sandbox="" sandbox="allow-top-navigation"
none specified, for links and form submissions current current current
empty string current current current
_blank new maybe new maybe new
_self current current current
_parent if there isn't a parent current current current
_parent if parent is also top parent/top none parent/top
_parent if there is one and it's not top parent none none
_top if top is current current current current
_top if top is not current top none top
name that doesn't exist new maybe new maybe new
name that exists and is a descendant specified descendant specified descendant specified descendant
name that exists and is current current current current
name that exists and is an ancestor that is top specified ancestor none specified ancestor/top
name that exists and is an ancestor that is not top specified ancestor none none
other name that exists with common top specified none none
name that exists with different top, if familiar and one permitted sandboxed navigator specified specified specified
name that exists with different top, if familiar but not one permitted sandboxed navigator specified none none
name that exists with different top, not familiar new maybe new maybe new

Most of the restrictions on sandboxed browsing contexts are applied by other algorithms, e.g. the navigation algorithm, not the rules for choosing a browsing context given below.


The rules for choosing a browsing context, given a browsing context name name, a browsing context current, and a boolean noopener are as follows:

  1. Let chosen be null.

  2. Let windowType be "existing or none".

  3. Let sandboxingFlagSet be current's active document's active sandboxing flag set.

  4. If name is the empty string or an ASCII case-insensitive match for "_self", then set chosen to current.

  5. Otherwise, if name is an ASCII case-insensitive match for "_parent", set chosen to current's parent browsing context, if any, and current otherwise.

  6. Otherwise, if name is an ASCII case-insensitive match for "_top", set chosen to current's top-level browsing context, if any, and current otherwise.

  7. Otherwise, if name is not an ASCII case-insensitive match for "_blank", there exists a browsing context whose name is the same as name, current is familiar with that browsing context, and the user agent determines that the two browsing contexts are related enough that it is ok if they reach each other, set chosen to that browsing context. If there are multiple matching browsing contexts, the user agent should set chosen to one in some arbitrary consistent manner, such as the most recently opened, most recently focused, or more closely related.

    This will be made more precise in issue #313.

  8. Otherwise, a new browsing context is being requested, and what happens depends on the user agent's configuration and abilities — it is determined by the rules given for the first applicable option from the following list:

    The user agent may inform the user that a popup has been blocked.

    If sandboxingFlagSet has the sandboxed auxiliary navigation browsing context flag set

    The user agent may report to a developer console that a popup has been blocked.

    If the user agent has been configured such that in this instance it will create a new browsing context
    1. Set windowType to "new and unrestricted".

    2. If current's top-level browsing context's active document's cross-origin opener policy is "same-origin" or "same-origin-plus-COEP", then:

      1. Let currentDocument be current's active document.

      2. If currentDocument's origin is not same origin with currentDocument's relevant settings object's top-level origin, then set noopener to true, name to "_blank", and windowType to "new with no opener".

        In the presence of a cross-origin opener policy, nested documents that are cross-origin with their top-level browsing context's active document always set noopener to true.

    3. If noopener is true, then set chosen to the result of creating a new top-level browsing context.

    4. Otherwise:

      1. Set chosen to the result of creating a new auxiliary browsing context with current.

      2. If sandboxingFlagSet's sandboxed navigation browsing context flag is set, then current must be set as chosen's one permitted sandboxed navigator.

    5. If sandboxingFlagSet's sandbox propagates to auxiliary browsing contexts flag is set, then all the flags that are set in sandboxingFlagSet must be set in chosen's popup sandboxing flag set.

    6. If name is not an ASCII case-insensitive match for "_blank", then set chosen's name to name.

    If the newly created browsing context is immediately navigated, then the navigation will be done with historyHandling set to "replace".

    If the user agent has been configured such that in this instance it will reuse current

    Set chosen to current.

    If the user agent has been configured such that in this instance it will not find a browsing context

    Do nothing.

    User agents are encouraged to provide a way for users to configure the user agent to always reuse current.

  9. Return chosen and windowType.

7.2 Window, WindowProxy, 和 Location 对象的安全基础设施

尽管通常不可以跨 访问对象, 但 Web 平台必须考虑遗留的那些例外情况。

7.2.1 Integration with IDL

When perform a security check is invoked, with a platformObject, identifier, and type, run these steps:

  1. If platformObject is not a Window or Location object, then return.

  2. For each e of ! CrossOriginProperties(platformObject):

    1. If SameValue(e.[[Property]], identifier) is true, then:

      1. If type is "method" and e has neither [[NeedsGet]] nor [[NeedsSet]], then return.

      2. Otherwise, if type is "getter" and e.[[NeedsGet]] is true, then return.

      3. Otherwise, if type is "setter" and e.[[NeedsSet]] is true, then return.

  3. If ! IsPlatformObjectSameOrigin(platformObject) is false, then throw a "SecurityError" DOMException.

7.2.2 Shared internal slot: [[CrossOriginPropertyDescriptorMap]]

Window and Location objects both have a [[CrossOriginPropertyDescriptorMap]] internal slot, whose value is initially an empty map.

The [[CrossOriginPropertyDescriptorMap]] internal slot contains a map with entries whose keys are (currentGlobal, objectGlobal, propertyKey)-tuples and values are property descriptors, as a memoization of what is visible to scripts when currentGlobal inspects a Window or Location object from objectGlobal. It is filled lazily by CrossOriginGetOwnPropertyHelper, which consults it on future lookups.

User agents should allow a value held in the map to be garbage collected along with its corresponding key when nothing holds a reference to any part of the value. That is, as long as garbage collection is not observable.

For example, with const href = Object.getOwnPropertyDescriptor(crossOriginLocation, "href").set the value and its corresponding key in the map cannot be garbage collected as that would be observable.

User agents may have an optimization whereby they remove key-value pairs from the map when document.domain is set. This is not observable as document.domain cannot revisit an earlier value.

For example, setting document.domain to "example.com" on www.example.com means user agents can remove all key-value pairs from the map where part of the key is www.example.com, as that can never be part of the origin again and therefore the corresponding value could never be retrieved from the map.

7.2.3 Shared abstract operations

7.2.3.1 CrossOriginProperties ( O )
  1. Assert: O is a Location or Window object.

  2. If O is a Location object, then return « { [[Property]]: "href", [[NeedsGet]]: false, [[NeedsSet]]: true }, { [[Property]]: "replace" } ».

  3. Return « { [[Property]]: "window", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "self", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "location", [[NeedsGet]]: true, [[NeedsSet]]: true }, { [[Property]]: "close" }, { [[Property]]: "closed", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "focus" }, { [[Property]]: "blur" }, { [[Property]]: "frames", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "length", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "top", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "opener", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "parent", [[NeedsGet]]: true, [[NeedsSet]]: false }, { [[Property]]: "postMessage" } ».

Indexed properties do not need to be safelisted as they are handled directly by the WindowProxy object.

7.2.3.2 CrossOriginPropertyFallback ( P )
  1. If P is "then", @@toStringTag, @@hasInstance, or @@isConcatSpreadable, then return PropertyDescriptor{ [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: true }.

  2. Throw a "SecurityError" DOMException.

7.2.3.3 IsPlatformObjectSameOrigin ( O )
  1. Return true if the current settings object's origin is same origin-domain with O's relevant settings object's origin, and false otherwise.

Here the current settings object roughly corresponds to the "caller", because this check occurs before the execution context for the getter/setter/method in question makes its way onto the JavaScript execution context stack. For example, in the code w.document, this step is invoked before the document getter is reached as part of the [[Get]] algorithm for the WindowProxy w.

7.2.3.4 CrossOriginGetOwnPropertyHelper ( O, P )

If this abstract operation returns undefined and there is no custom behavior, the caller needs to throw a "SecurityError" DOMException. In practice this is handled by the caller calling CrossOriginPropertyFallback.

  1. Let crossOriginKey be a tuple consisting of the current settings object, O's relevant settings object, and P.

  2. For each e of ! CrossOriginProperties(O):

    1. If SameValue(e.[[Property]], P) is true, then:

      1. If the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of O contains an entry whose key is crossOriginKey, then return that entry's value.

      2. Let originalDesc be OrdinaryGetOwnProperty(O, P).

      3. Let crossOriginDesc be undefined.

      4. If e.[[NeedsGet]] and e.[[NeedsSet]] are absent, then:

        1. Let value be originalDesc.[[Value]].

        2. If ! IsCallable(value) is true, then set value to an anonymous built-in function, created in the current Realm Record, that performs the same steps as the IDL operation P on object O.

        3. Set crossOriginDesc to PropertyDescriptor{ [[Value]]: value, [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }.

      5. Otherwise:

        1. Let crossOriginGet be undefined.

        2. If e.[[NeedsGet]] is true, then set crossOriginGet to an anonymous built-in function, created in the current Realm Record, that performs the same steps as the getter of the IDL attribute P on object O.

        3. Let crossOriginSet be undefined.

        4. If e.[[NeedsSet]] is true, then set crossOriginSet to an anonymous built-in function, created in the current Realm Record, that performs the same steps as the setter of the IDL attribute P on object O.

        5. Set crossOriginDesc to PropertyDescriptor{ [[Get]]: crossOriginGet, [[Set]]: crossOriginSet, [[Enumerable]]: false, [[Configurable]]: true }.

      6. Create an entry in the value of the [[CrossOriginPropertyDescriptorMap]] internal slot of O with key crossOriginKey and value crossOriginDesc.

      7. Return crossOriginDesc.

  3. Return undefined.

The reason that the property descriptors produced here are configurable is to preserve the invariants of the essential internal methods required by the JavaScript specification. In particular, since the value of the property can change as a consequence of navigation, it is required that the property be configurable. (However, see tc39/ecma262 issue #672 and references to it elsewhere in this specification for cases where we are not able to preserve these invariants, for compatibility with existing web content.) [JAVASCRIPT]

The reason the property descriptors are non-enumerable, despite this mismatching the same-origin behavior, is for compatibility with existing web content. See issue #3183 for details.

7.2.3.5 CrossOriginGet ( O, P, Receiver )
  1. Let desc be ? O.[[GetOwnProperty]](P).

  2. Assert: desc is not undefined.

  3. If ! IsDataDescriptor(desc) is true, then return desc.[[Value]].

  4. Assert: IsAccessorDescriptor(desc) is true.

  5. Let getter be desc.[[Get]].

  6. If getter is undefined, then throw a "SecurityError" DOMException.

  7. Return ? Call(getter, Receiver).

7.2.3.6 CrossOriginSet ( O, P, V, Receiver )
  1. Let desc be ? O.[[GetOwnProperty]](P).

  2. Assert: desc is not undefined.

  3. If desc.[[Set]] is present and its value is not undefined, then:

    1. Perform ? Call(setter, Receiver, «V»).

    2. Return true.

  4. Throw a "SecurityError" DOMException.

7.2.3.7 CrossOriginOwnPropertyKeys ( O )
  1. Let keys be a new empty List.

  2. For each e of ! CrossOriginProperties(O), append e.[[Property]] to keys.

  3. Return the concatenation of keys and « "then", @@toStringTag, @@hasInstance, @@isConcatSpreadable ».

7.3 The Window object

Window

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
[Global=Window,
 Exposed=Window,
 LegacyUnenumerableNamedProperties]
interface Window : EventTarget {
  // the current browsing context
  [LegacyUnforgeable] readonly attribute WindowProxy window;
  [Replaceable] readonly attribute WindowProxy self;
  [LegacyUnforgeable] readonly attribute Document document;
  attribute DOMString name; 
  [PutForwards=href, LegacyUnforgeable] readonly attribute Location location;
  readonly attribute History history;
  readonly attribute CustomElementRegistry customElements;
  [Replaceable] readonly attribute BarProp locationbar;
  [Replaceable] readonly attribute BarProp menubar;
  [Replaceable] readonly attribute BarProp personalbar;
  [Replaceable] readonly attribute BarProp scrollbars;
  [Replaceable] readonly attribute BarProp statusbar;
  [Replaceable] readonly attribute BarProp toolbar;
  attribute DOMString status;
  undefined close();
  readonly attribute boolean closed;
  undefined stop();
  undefined focus();
  undefined blur();

  // other browsing contexts
  [Replaceable] readonly attribute WindowProxy frames;
  [Replaceable] readonly attribute unsigned long length;
  [LegacyUnforgeable] readonly attribute WindowProxy? top;
  attribute any opener;
  [Replaceable] readonly attribute WindowProxy? parent;
  readonly attribute Element? frameElement;
  WindowProxy? open(optional USVString url = "", optional DOMString target = "_blank", optional [LegacyNullToEmptyString] DOMString features = "");
  getter object (DOMString name);
  // Since this is the global object, the IDL named getter adds a NamedPropertiesObject exotic
  // object on the prototype chain. Indeed, this does not make the global object an exotic object.
  // Indexed access is taken care of by the WindowProxy exotic object.

  // the user agent
  readonly attribute Navigator navigator; 
  [SecureContext] readonly attribute ApplicationCache applicationCache;
  readonly attribute boolean originIsolated;

  // user prompts
  undefined alert();
  undefined alert(DOMString message);
  boolean confirm(optional DOMString message = "");
  DOMString? prompt(optional DOMString message = "", optional DOMString default = "");
  undefined print();

  undefined postMessage(any message, USVString targetOrigin, optional sequence<object> transfer = []);
  undefined postMessage(any message, optional WindowPostMessageOptions options = {});

  // also has obsolete members
};
Window includes GlobalEventHandlers;
Window includes WindowEventHandlers;

dictionary WindowPostMessageOptions : PostMessageOptions {
  USVString targetOrigin = "/";
};
window . window

Window/window

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
window . frames

Window/frames

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
window . self

Window/self

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

These attributes all return window.

window . document

Window/document

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the Document associated with window.

document . defaultView

Document/defaultView

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the Window object of the active document.

The Window object has an associated Document, which is a Document object. It is set when the Window object is created, and only ever changed during navigation from the initial about:blank Document.

The Window object's browsing context is the Window object's associated Document's browsing context. It is either null or a browsing context.

The window, frames, and self attributes' getters must return this Window object's relevant Realm.[[GlobalEnv]]'s EnvironmentRecord's [[GlobalThisValue]].

The document IDL attribute, on getting, must return this Window object's associated Document.

The Document object associated with a Window object can change in exactly one case: when the navigate algorithm creates a new Document object for the first page loaded in a browsing context. In that specific case, the Window object of the original about:blank page is reused and gets a new Document object.

The defaultView attribute's getter, when invoked, must run these steps:

  1. If this Document object's browsing context is null, then return null.

  2. Return this Document object's browsing context's WindowProxy object.


HTMLDocument

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

For historical reasons, Window objects must also have a writable, configurable, non-enumerable property named HTMLDocument whose value is the Document interface object.

7.3.1 APIs for creating and navigating browsing contexts by name

window = window . open( [ url [, target [, features ] ] ] )

Window/open

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Opens a window to show url (defaults to about:blank), and returns it. The target argument gives the name of the new window. If a window exists with that name already, it is reused. The features argument can be used to influence the rendering of the new window.

window . name [ = value ]

Window/name

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the name of the window.

Can be set, to change the name.

window . close()

Window/close

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Closes the window.

window . closed

Window/closed

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns true if the window has been closed, false otherwise.

window . stop()

Window/stop

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Cancels the document load.

The window open steps, given a string url, a string target, and a string features, are as follows:

  1. If the event loop's termination nesting level is nonzero, return null.

  2. Let source browsing context be the entry global object's browsing context.

  3. If target is the empty string, then set target to "_blank".

  4. Let tokenizedFeatures be the result of tokenizing features.

  5. Let noopener and noreferrer be false.

  6. If tokenizedFeatures["noopener"] exists, then:

    1. Set noopener to the result of parsing tokenizedFeatures["noopener"] as a boolean feature.

    2. Remove tokenizedFeatures["noopener"].

  7. If tokenizedFeatures["noreferrer"] exists, then:

    1. Set noreferrer to the result of parsing tokenizedFeatures["noreferrer"] as a boolean feature.

    2. Remove tokenizedFeatures["noreferrer"].

  8. If noreferrer is true, then set noopener to true.

  9. Let target browsing context and windowType be the result of applying the rules for choosing a browsing context given target, source browsing context, and noopener.

    If there is a user agent that supports control-clicking a link to open it in a new tab, and the user control-clicks on an element whose onclick handler uses the window.open() API to open a page in an iframe element, the user agent could override the selection of the target browsing context to instead target a new tab.

  10. Let new be true if windowType is either "new and unrestricted" or "new with no opener", and false otherwise.

  11. If target browsing context is null, then return null.

  12. If new is true, then set up browsing context features for target browsing context given tokenizedFeatures. [CSSOMVIEW]

  13. Let urlRecord be the URL "about:blank".

  14. If url is not the empty string or new is true, then:

    1. If url is not the empty string, then parse url relative to the entry settings object, and set urlRecord to the resulting URL record, if any. If the parse a URL algorithm failed, then throw a "SyntaxError" DOMException.

    2. Let request be a new request whose URL is urlRecord.

    3. If noreferrer is true, then set request's referrer to "noreferrer".

    4. Let window be target browsing context's active window.

    5. If urlRecord is "about:blank" and new is true, then queue a global task on the networking task source given window to fire an event named load at window, with the legacy target override flag set.

    6. Otherwise:

      1. Let historyHandling be "replace" if new is true; otherwise "default".

      2. Navigate target browsing context to request, with exceptionsEnabled set to true, historyHandling set to historyHandling, and the source browsing context set to source browsing context.

  15. If noopener is true or windowType is "new with no opener", then return null.

  16. Otherwise, if new is false, set target browsing context's opener browsing context to source browsing context.

    If new is true this is done as part of creating a new auxiliary browsing context.

  17. Return target browsing context's WindowProxy object.

The open(url, target, features) method on Window objects provides a mechanism for navigating an existing browsing context or opening and navigating an auxiliary browsing context.

When the method is invoked, the user agent must run the window open steps with url, target, and features.


To tokenize the features argument:

  1. Let tokenizedFeatures be a new ordered map.

  2. Let position point at the first code point of features.

  3. While position is not past the end of features:

    1. Let name be the empty string.

    2. Let value be the empty string.

    3. Collect a sequence of code points that are feature separators from features given position. This skips past leading separators before the name.

    4. Collect a sequence of code points that are not feature separators from features given position. Set name to the collected characters, converted to ASCII lowercase.

    5. Set name to the result of normalizing the feature name name.

    6. While position is not past the end of features and the code point at position in features is not U+003D (=):

      1. If the code point at position in features is U+002C (,), or if it is not a feature separator, then break.

      2. Advance position by 1.

      This skips to the first U+003D (=) but does not skip past a U+002C (,) or a non-separator.

    7. If the code point at position in features is a feature separator:

      1. While position is not past the end of features and the code point at position in features is a feature separator:

        1. If the code point at position in features is U+002C (,), then break.

        2. Advance position by 1.

        This skips to the first non-separator but does not skip past a U+002C (,).

      2. Collect a sequence of code points that are not feature separators code points from features given position. Set value to the collected code points, converted to ASCII lowercase.

    8. If name is not the empty string, then set tokenizedFeatures[name] to value.

  4. Return tokenizedFeatures.

A code point is a feature separator if it is ASCII whitespace, U+003D (=), or U+002C (,).

For legacy reasons, there are some aliases of some feature names. To normalize a feature name name, switch on name:

"screenx"
Return "left".
"screeny"
Return "top".
"innerwidth"
Return "width".
"innerheight"
Return "height".
Anything else
Return name.

To parse a boolean feature given a string value:

  1. If value is the empty string, then return true.

  2. If value is "yes", then return true.

  3. Let parsed be the result of parsing value as an integer.

  4. If parsed is an error, then set it to 0.

  5. Return false if parsed is 0, and true otherwise.


The name attribute's getter must run these steps:

  1. If this Window object's browsing context is null, then return the empty string.

  2. Return this Window object's browsing context's name.

The name attribute's setter must run these steps:

  1. If this Window object's browsing context is null, then return.

  2. Set this Window object's browsing context's name to the given value.

The name gets reset when the browsing context is navigated to another origin.


The close() method must run these steps:

  1. Let current be this Window object's browsing context.

  2. If current is null or its is closing is true, then return.

  3. If all the following are true

    then:

    1. Set current's is closing to true.

    2. Queue a task on the DOM manipulation task source to close current.

A browsing context is script-closable if it is an auxiliary browsing context that was created by a script (as opposed to by an action of the user), or if it is a top-level browsing context whose session history contains only one Document.

The closed attribute's getter must return true if this Window object's browsing context is null or its is closing is true, and false otherwise.

The stop() method must stop document loading given this Window object's associated Document.

7.3.2 Accessing other browsing contexts

window . length

Window/length

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the number of document-tree child browsing contexts.

window[index]

Returns the indicated document-tree child browsing context.

The number of document-tree child browsing contexts of a Window object W is the result of running these steps:

  1. If W's browsing context is null, then return 0.

  2. Return the number of document-tree child browsing contexts of W's browsing context.

The length IDL attribute's getter must return the number of document-tree child browsing contexts of this Window object.

Indexed access to document-tree child browsing contexts is defined through the [[GetOwnProperty]] internal method of the WindowProxy object.

7.3.3 Named access on the Window object

window[name]

Returns the indicated element or collection of elements.

As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the web platform, for example. Instead of this, use document.getElementById() or document.querySelector().

The document-tree child browsing context name property set of a Window object window is the return value of running these steps:

  1. If window's browsing context is null, then return the empty list.

  2. Let childBrowsingContexts be all document-tree child browsing contexts of window's browsing context whose browsing context name is not the empty string, in order, and including only the first document-tree child browsing context with a given name if multiple document-tree child browsing contexts have the same one.

  3. Remove each browsing context from childBrowsingContexts whose active document's origin is not same origin with window's relevant settings object's origin and whose browsing context name does not match the name of its container's name content attribute value.

  4. Return the browsing context names of childBrowsingContexts, in the same order.

This means that in the following example, hosted on https://example.org/, assuming https://elsewhere.example/ sets window.name to "spices", evaluating window.spices after everything has loaded will yield undefined:

<iframe src=https://elsewhere.example.com/></iframe>
<iframe name=spices></iframe>

The Window object supports named properties. The supported property names of a Window object window at any moment consist of the following, in tree order according to the element that contributed them, ignoring later duplicates:

To determine the value of a named property name in a Window object window, the user agent must return the value obtained using the following steps:

  1. Let objects be the list of named objects of window with the name name.

    There will be at least one such object, by definition.

  2. If objects contains a browsing context, then return the WindowProxy object of the nested browsing context of the first browsing context container in tree order whose nested browsing context is in objects.

  3. Otherwise, if objects has only one element, return that element.

  4. Otherwise return an HTMLCollection rooted at window's associated Document, whose filter matches only named objects of window with the name name. (By definition, these will all be elements.)

Named objects of Window object window with the name name, for the purposes of the above algorithm, consist of the following:

7.3.4 Discarding browsing contexts

To discard a Document document:

  1. Set document's salvageable state to false.

  2. Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications.

  3. Abort document.

  4. Remove any tasks associated with document in any task source, without running those tasks.

  5. Discard all the child browsing contexts of document.

  6. For each session history entry entry whose document is equal to document, set entry's document to null.

  7. Set document's browsing context to null.

  8. Remove document from the owner set of each WorkerGlobalScope object whose set contains document.

  9. For each workletGlobalScope in document's worklet global scopes, terminate workletGlobalScope.

To discard a browsing context browsingContext, run these steps:

  1. Discard all Document objects for all the entries in browsingContext's session history.

  2. If browsingContext is a top-level browsing context, then remove browsingContext.

User agents may discard top-level browsing contexts at any time (typically, in response to user requests, e.g., when a user force-closes a window containing one or more top-level browsing contexts). Other browsing contexts must be discarded once their WindowProxy object is eligible for garbage collection, in addition to the other places where this specification requires them to be discarded.

7.3.5 Closing browsing contexts

To close a browsing context browsingContext, run these steps:

  1. Prompt to unload browsingContext's active document. If the user refused to allow the document to be unloaded, then return.

  2. Unload browsingContext's active document.

  3. Remove browsingContext from the user interface (e.g., close or hide its tab in a tabbed browser).

  4. Discard browsingContext.

User agents should offer users the ability to arbitrarily close any top-level browsing context.

7.3.6 Browser interface elements

To allow web pages to integrate with web browsers, certain web browser interface elements are exposed in a limited way to scripts in web pages.

Each interface element is represented by a BarProp object:

BarProp

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
[Exposed=Window]
interface BarProp {
  readonly attribute boolean visible;
};
window . locationbar . visible

Window/locationbar

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

Returns true if the location bar is visible; otherwise, returns false.

window . menubar . visible

Window/menubar

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

Returns true if the menu bar is visible; otherwise, returns false.

window . personalbar . visible

Window/personalbar

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns true if the personal bar is visible; otherwise, returns false.

window . scrollbars . visible

Window/scrollbars

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns true if the scrollbars are visible; otherwise, returns false.

window . statusbar . visible

Window/statusbar

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

Returns true if the status bar is visible; otherwise, returns false.

window . toolbar . visible

Window/toolbar

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

Returns true if the toolbar is visible; otherwise, returns false.

BarProp/visible

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+

The visible attribute's getter must run these steps:

  1. If this BarProp object's relevant global object's browsing context is null, then return false.

  2. If the user agent does not have a user interface element that the object represents, as described below, then return true.

  3. Return true or a value determined by the user agent to most accurately represent the visibility state of the user interface element that the object represents, as described below.

The following BarProp objects must exist for each Window object:

The location bar BarProp object
Represents the user interface element that contains a control that displays the URL of the active document, or some similar interface concept.
The menu bar BarProp object
Represents the user interface element that contains a list of commands in menu form, or some similar interface concept.
The personal bar BarProp object
Represents the user interface element that contains links to the user's favorite pages, or some similar interface concept.
The scrollbar BarProp object
Represents the user interface element that contains a scrolling mechanism, or some similar interface concept.
The status bar BarProp object
Represents a user interface element found immediately below or after the document, as appropriate for the user's media, which typically provides information about ongoing network activity or information about elements that the user's pointing device is current indicating. If the user agent has no such user interface element, then the object may act as if the corresponding user interface element was absent (i.e. its visible attribute may return false).
The toolbar BarProp object
Represents the user interface element found immediately above or before the document, as appropriate for the user's media, which typically provides session history traversal controls (back and forward buttons, reload buttons, etc). If the user agent has no such user interface element, then the object may act as if the corresponding user interface element was absent (i.e. its visible attribute may return false).

The locationbar attribute must return the location bar BarProp object.

The menubar attribute must return the menu bar BarProp object.

The personalbar attribute must return the personal bar BarProp object.

The scrollbars attribute must return the scrollbar BarProp object.

The statusbar attribute must return the status bar BarProp object.

The toolbar attribute must return the toolbar BarProp object.


For historical reasons, the status attribute on the Window object must, on getting, return the last string it was set to, and on setting, must set itself to the new value. When the Window object is created, the attribute must be set to the empty string. It does not do anything else.

7.3.7 Script settings for Window objects

To set up a window environment settings object, given a JavaScript execution context execution context, null or an environment reservedEnvironment, a URL topLevelCreationURL, and an origin topLevelOrigin, run these steps:

  1. Let realm be the value of execution context's Realm component.

  2. Let window be realm's global object.

  3. Let url be a copy of the URL of window's associated Document.

  4. Let settings object be a new environment settings object whose algorithms are defined as follows:

    The realm execution context

    Return execution context.

    The module map

    Return the module map of window's associated Document.

    The responsible document

    Return window's associated Document.

    The API URL character encoding

    Return the current character encoding of window's associated Document.

    The API base URL

    Return the current base URL of window's associated Document.

    The origin

    Return the origin of window's associated Document.

    The referrer policy
    1. Let document be window's associated Document.

    2. While document is an iframe srcdoc document and document's referrer policy is the empty string, set document to document's browsing context's container document.

    3. Return document's referrer policy.

    The embedder policy

    Return window's associated Document's embedder policy.

    The cross-origin isolated capability

    Return the logical conjunction of realm's agent cluster's cross-origin isolated and whether window's associated Document is allowed to use the "cross-origin-isolated" feature.

  5. If reservedEnvironment is non-null, then:

    1. Set settings object's id to reservedEnvironment's id, target browsing context to reservedEnvironment's target browsing context, and active service worker to reservedEnvironment's active service worker.

    2. Set reservedEnvironment's id to the empty string.

      The identity of the reserved environment is considered to be fully transferred to the created environment settings object. The reserved environment is not searchable by the environment’s id from this point on.

  6. Otherwise, set settings object's id to a new unique opaque string, settings object's target browsing context to null, and settings object's active service worker to null.

  7. Set settings object's creation URL to url, settings object's top-level creation URL to topLevelCreationURL, and settings object's top-level origin to topLevelOrigin.

  8. Set realm's [[HostDefined]] field to settings object.

  9. Return settings object.

7.4 The WindowProxy exotic object

A WindowProxy is an exotic object that wraps a Window ordinary object, indirecting most operations through to the wrapped object. Each browsing context has an associated WindowProxy object. When the browsing context is navigated, the Window object wrapped by the browsing context's associated WindowProxy object is changed.

The WindowProxy exotic object must use the ordinary internal methods except where it is explicitly specified otherwise below.

There is no WindowProxy interface object.

Every WindowProxy object has a [[Window]] internal slot representing the wrapped Window object.

Although WindowProxy is named as a "proxy", it does not do polymorphic dispatch on its target's internal methods as a real proxy would, due to a desire to reuse machinery between WindowProxy and Location objects. As long as the Window object remains an ordinary object this is unobservable and can be implemented either way.

7.4.1 [[GetPrototypeOf]] ( )

  1. Let W be the value of the [[Window]] internal slot of this.

  2. If ! IsPlatformObjectSameOrigin(W) is true, then return ! OrdinaryGetPrototypeOf(W).

  3. Return null.

7.4.2 [[SetPrototypeOf]] ( V )

  1. Return ! SetImmutablePrototype(this, V).

7.4.3 [[IsExtensible]] ( )

  1. Return true.

7.4.4 [[PreventExtensions]] ( )

  1. Return false.

7.4.5 [[GetOwnProperty]] ( P )

  1. Let W be the value of the [[Window]] internal slot of this.

  2. If P is an array index property name, then:

    1. Let index be ! ToUint32(P).

    2. Let maxProperties be the number of document-tree child browsing contexts of W.

    3. Let value be undefined.

    4. If maxProperties is greater than 0 and index is less than maxProperties, then set value to the WindowProxy object of the indexth document-tree child browsing context of W's browsing context, sorted in the order that their browsing context container elements were most recently inserted into W's associated Document, the WindowProxy object of the most recently inserted browsing context container's nested browsing context being last.

    5. If value is undefined, then:

      1. If ! IsPlatformObjectSameOrigin(W) is true, then return undefined.

      2. Throw a "SecurityError" DOMException.

    6. Return PropertyDescriptor{ [[Value]]: value, [[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: true }.

  3. If ! IsPlatformObjectSameOrigin(W) is true, then return ! OrdinaryGetOwnProperty(W, P).

    This is a willful violation of the JavaScript specification's invariants of the essential internal methods to maintain compatibility with existing web content. See tc39/ecma262 issue #672 for more information. [JAVASCRIPT]

  4. Let property be ! CrossOriginGetOwnPropertyHelper(W, P).

  5. If property is not undefined, then return property.

  6. If property is undefined and P is in W's document-tree child browsing context name property set, then:

    1. Let value be the WindowProxy object of the named object of W with the name P.

    2. Return PropertyDescriptor{ [[Value]]: value, [[Enumerable]]: false, [[Writable]]: false, [[Configurable]]: true }.

      The reason the property descriptors are non-enumerable, despite this mismatching the same-origin behavior, is for compatibility with existing web content. See issue #3183 for details.

  7. Return ? CrossOriginPropertyFallback(P).

7.4.6 [[DefineOwnProperty]] ( P, Desc )

  1. Let W be the value of the [[Window]] internal slot of this.

  2. If ! IsPlatformObjectSameOrigin(W) is true, then:

    1. If P is an array index property name, return false.

    2. Return ? OrdinaryDefineOwnProperty(W, P, Desc).

      This is a willful violation of the JavaScript specification's invariants of the essential internal methods to maintain compatibility with existing web content. See tc39/ecma262 issue #672 for more information. [JAVASCRIPT]

  3. Throw a "SecurityError" DOMException.

7.4.7 [[Get]] ( P, Receiver )

  1. Let W be the value of the [[Window]] internal slot of this.

  2. If ! IsPlatformObjectSameOrigin(W) is true, then return ? OrdinaryGet(this, P, Receiver).

  3. Return ? CrossOriginGet(this, P, Receiver).

this is passed rather than W as OrdinaryGet and CrossOriginGet will invoke the [[GetOwnProperty]] internal method.

7.4.8 [[Set]] ( P, V, Receiver )

  1. Let W be the value of the [[Window]] internal slot of this.

  2. If ! IsPlatformObjectSameOrigin(W) is true, then return ? OrdinarySet(this, P, V, Receiver).

  3. Return ? CrossOriginSet(this, P, V, Receiver).

this is passed rather than W as OrdinarySet and CrossOriginSet will invoke the [[GetOwnProperty]] internal method. OrdinarySet will also invoke the [[DefineOwnProperty]] internal method.

7.4.9 [[Delete]] ( P )

  1. Let W be the value of the [[Window]] internal slot of this.

  2. If ! IsPlatformObjectSameOrigin(W) is true, then:

    1. If P is an array index property name, then:

      1. Let desc be ! this.[[GetOwnProperty]](P).

      2. If desc is undefined, then return true.

      3. Return false.

    2. Return ? OrdinaryDelete(W, P).

  3. Throw a "SecurityError" DOMException.

7.4.10 [[OwnPropertyKeys]] ( )

  1. Let W be the value of the [[Window]] internal slot of this.

  2. Let keys be a new empty List.

  3. Let maxProperties be the number of document-tree child browsing contexts of W.

  4. Let index be 0.

  5. Repeat while index < maxProperties,

    1. Add ! ToString(index) as the last element of keys.

    2. Increment index by 1.

  6. If ! IsPlatformObjectSameOrigin(W) is true, then return the concatenation of keys and ! OrdinaryOwnPropertyKeys(W).

  7. Return the concatenation of keys and ! CrossOriginOwnPropertyKeys(W).

7.5 Origin

Origins are the fundamental currency of the web's security model. Two actors in the web platform that share an origin are assumed to trust each other and to have the same authority. Actors with differing origins are considered potentially hostile versus each other, and are isolated from each other to varying degrees.

For example, if Example Bank's web site, hosted at bank.example.com, tries to examine the DOM of Example Charity's web site, hosted at charity.example.org, a "SecurityError" DOMException will be raised.


An origin is one of the following:

An opaque origin

An internal value, with no serialization it can be recreated from (it is serialized as "null" per serialization of an origin), for which the only meaningful operation is testing for equality.

A tuple origin

A tuple consists of:

Origins can be shared, e.g., among multiple Document objects. Furthermore, origins are generally immutable. Only the domain of a tuple origin can be changed, and only through the document.domain API.

The effective domain of an origin origin is computed as follows:

  1. If origin is an opaque origin, then return null.

  2. If origin's domain is non-null, then return origin's domain.

  3. Return origin's host.

Various specification objects are defined to have an origin. These origins are determined as follows:

For Document objects

The create a new browsing context and navigation algorithms assign the origin at construction time. Otherwise, the default default behavior as defined in DOM applies. [DOM]

For images of img elements
If the image data is CORS-cross-origin

A unique opaque origin assigned when the image is created.

If the image data is CORS-same-origin

The img element's node document's origin.

For audio and video elements
If the media data is CORS-cross-origin

A unique opaque origin assigned when the media data is fetched.

If the media data is CORS-same-origin

The media element's node document's origin.

Other specifications can override the above definitions by themselves specifying the origin of a particular Document object, image, or media element.


The serialization of an origin is the string obtained by applying the following algorithm to the given origin origin:

  1. If origin is an opaque origin, then return "null".

  2. Otherwise, let result be origin's scheme.

  3. Append "://" to result.

  4. Append origin's host, serialized, to result.

  5. If origin's port is non-null, append a U+003A COLON character (:), and origin's port, serialized, to result.

  6. Return result.

The serialization of ("https", "xn--maraa-rta.example", null, null) is "https://xn--maraa-rta.example".

There used to also be a Unicode serialization of an origin. However, it was never widely adopted.


Two origins, A and B, are said to be same origin if the following algorithm returns true:

  1. If A and B are the same opaque origin, then return true.

  2. If A and B are both tuple origins and their schemes, hosts, and port are identical, then return true.

  3. Return false.

Two origins, A and B, are said to be same origin-domain if the following algorithm returns true:

  1. If A and B are the same opaque origin, then return true.

  2. If A and B are both tuple origins, run these substeps:

    1. If A and B's schemes are identical, and their domains are identical and non-null, then return true.

    2. Otherwise, if A and B are same origin and their domains are identical and null, then return true.

  3. Return false.

A B same origin same origin-domain
("https", "example.org", null, null) ("https", "example.org", null, null)
("https", "example.org", 314, null) ("https", "example.org", 420, null)
("https", "example.org", 314, "example.org") ("https", "example.org", 420, "example.org")
("https", "example.org", null, null) ("https", "example.org", null, "example.org")
("https", "example.org", null, "example.org") ("http", "example.org", null, "example.org")

7.5.1 Sites

A scheme-and-host is a tuple of a scheme and a host.

A site is an opaque origin or a scheme-and-host.

To obtain a site, given an origin origin, run these steps:

  1. If origin is an opaque origin, then return origin.

  2. If origin's host's registrable domain is null, then return (origin's scheme, origin's host).

  3. Return (origin's scheme, origin's host's registrable domain).

Two origins, A and B, are said to be schemelessly same site if the following algorithm returns true:

  1. If A and B are the same opaque origin, then return true.

  2. If A and B are both tuple origins, then:

    1. Let hostA be A's host, and let hostB be B's host.

    2. If hostA equals hostB and hostA's registrable domain is null, then return true.

    3. If hostA's registrable domain equals hostB's registrable domain and is non-null, then return true.

  3. Return false.

Two origins, A and B, are said to be same site if both of the following statements are true:

Unlike the same origin and same origin-domain concepts, for schemelessly same site and same site, the port and domain components are ignored.

For the reasons explained in URL, the same site and schemelessly same site concepts should be avoided when possible, in favor of same origin checks.

Given that wildlife.museum, museum, and com are public suffixes and that example.com is not:

A B schemelessly same site same site
("https", "example.com") ("https", "sub.example.com")
("https", "example.com") ("https", "sub.other.example.com")
("https", "example.com") ("http", "non-secure.example.com")
("https", "r.wildlife.museum") ("https", "sub.r.wildlife.museum")
("https", "r.wildlife.museum") ("https", "sub.other.r.wildlife.museum")
("https", "r.wildlife.museum") ("https", "other.wildlife.museum")
("https", "r.wildlife.museum") ("https", "wildlife.museum")
("https", "wildlife.museum") ("https", "wildlife.museum")

(Here we have omitted the port and domain components since they are not considered.)

7.5.2 Relaxing the same-origin restriction

Document/domain

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
document . domain [ = domain ]

Returns the current domain used for security checks.

Can be set to a value that removes subdomains, to change the origin's domain to allow pages on other subdomains of the same domain (if they do the same thing) to access each other. This enables pages on different hosts of a domain to synchronously access each other's DOMs.

In sandboxed iframes, Documents with opaque origins, Documents without a browsing context, and when the "document-domain" feature is disabled, the setter will throw a "SecurityError" exception. In cases where crossOriginIsolated or originIsolated return true, the setter will do nothing.

Avoid using the document.domain setter. It undermines the security protections provided by the same-origin policy. This is especially acute when using shared hosting; for example, if an untrusted third party is able to host an HTTP server at the same IP address but on a different port, then the same-origin protection that normally protects two different sites on the same host will fail, as the ports are ignored when comparing origins after the document.domain setter has been used.

Because of these security pitfalls, this feature is in the process of being removed from the web platform. (This is a long process that takes many years.)

Instead, use postMessage() or MessageChannel objects to communicate across origins in a safe manner.

The domain getter steps are:

  1. Let effectiveDomain be this's origin's effective domain.

  2. If effectiveDomain is null, then return the empty string.

  3. Return effectiveDomain, serialized.

The domain setter steps are:

  1. If this's browsing context is null, then throw a "SecurityError" DOMException.

  2. If this's active sandboxing flag set has its sandboxed document.domain browsing context flag set, then throw a "SecurityError" DOMException.

  3. If this is not allowed to use the "document-domain" feature, then throw a "SecurityError" DOMException.

  4. Let effectiveDomain be this's origin's effective domain.

  5. If effectiveDomain is null, then throw a "SecurityError" DOMException.

  6. If the given value is not a registrable domain suffix of and is not equal to effectiveDomain, then throw a "SecurityError" DOMException.

  7. If the surrounding agent's agent cluster's cross-origin isolated is true, then return.

  8. If the surrounding agent's agent cluster's origin-isolated is true, then return.

  9. Set this's origin's domain to the result of parsing the given value.

To determine if a string hostSuffixString is a registrable domain suffix of or is equal to a host originalHost, run these steps:

  1. If hostSuffixString is the empty string, then return false.

  2. Let host be the result of parsing hostSuffixString.

  3. If host is failure, then return false.

  4. If host does not equal originalHost, then:

    1. If host or originalHost is not a domain, then return false.

      This excludes hosts that are an IPv4 address or an IPv6 address.

    2. If host, prefixed by a U+002E FULL STOP (.), does not exactly match the end of originalHost, then return false.

    3. If host equals host's public suffix, then return false. [URL]

  5. Return true.

7.5.3 Origin isolation

window . originIsolated

Returns true if this Window is origin-isolated in the manner described in this section.

A Document delivered over a secure context can opt in to origin isolation, by using the `Origin-Isolation` HTTP response header. This header is a structured header whose value must be a boolean. [STRUCTURED-FIELDS]

Per the processing model in the create and initialize a new Document object, values that are not the structured header boolean true value (i.e., `?1`) will be ignored.

The consequences of using this header are that the resulting Document's agent cluster key is its origin, instead of the corresponding site. In terms of observable effects, this means that attempting to relax the same-origin restriction using document.domain will instead do nothing, and it will not be possible to send WebAssembly.Module objects to cross-origin Documents (even if they are same site). Behind the scenes, this isolation can allow user agents to allocate implementation-specific resources corresponding to agent clusters, such as processes or threads, more efficiently.

Note that within a browsing context group, the `Origin-Isolation` header can never cause same-origin Document objects to end up in different agent clusters, even if one sends the header and the other doesn't. This is prevented by means of the historical agent cluster key map.

This means that the originIsolated getter can return false, even if the header is set, if the header was omitted on a previously-loaded same-origin page in the same browsing context group. Similarly, it can return true even when the header is not set.

The originIsolated getter steps are to return the surrounding agent's agent cluster's origin-isolated.

Documents with an opaque origin can be considered unconditionally origin-isolated; for them the header has no effect.

Similarly, Documents in a cross-origin isolated agent cluster are automatically origin-isolated. The `Origin-Isolation` header might be useful as an additional hint to implementations about resource allocation, since the `Cross-Origin-Opener-Policy` and `Cross-Origin-Embedder-Policy` headers used to achieve cross-origin isolation are more about ensuring that everything in the same address space opts in to being there. But adding it would have no additional observable effects on author code.

7.6 Sandboxing

A sandboxing flag set is a set of zero or more of the following flags, which are used to restrict the abilities that potentially untrusted resources have:

The sandboxed navigation browsing context flag

This flag prevents content from navigating browsing contexts other than the sandboxed browsing context itself (or browsing contexts further nested inside it), auxiliary browsing contexts (which are protected by the sandboxed auxiliary navigation browsing context flag defined next), and the top-level browsing context (which is protected by the sandboxed top-level navigation without user activation browsing context flag and sandboxed top-level navigation with user activation browsing context flag defined below).

If the sandboxed auxiliary navigation browsing context flag is not set, then in certain cases the restrictions nonetheless allow popups (new top-level browsing contexts) to be opened. These browsing contexts always have one permitted sandboxed navigator, set when the browsing context is created, which allows the browsing context that created them to actually navigate them. (Otherwise, the sandboxed navigation browsing context flag would prevent them from being navigated even if they were opened.)

The sandboxed auxiliary navigation browsing context flag

This flag prevents content from creating new auxiliary browsing contexts, e.g. using the target attribute or the window.open() method.

The sandboxed top-level navigation without user activation browsing context flag

This flag prevents content from navigating their top-level browsing context and prevents content from closing their top-level browsing context. It is consulted only when the sandboxed browsing context's active window does not have transient activation.

When the sandboxed top-level navigation without user activation browsing context flag is not set, content can navigate its top-level browsing context, but other browsing contexts are still protected by the sandboxed navigation browsing context flag and possibly the sandboxed auxiliary navigation browsing context flag.

The sandboxed top-level navigation with user activation browsing context flag

This flag prevents content from navigating their top-level browsing context and prevents content from closing their top-level browsing context. It is consulted only when the sandboxed browsing context's active window has transient activation.

As with the sandboxed top-level navigation without user activation browsing context flag, this flag only affects the top-level browsing context; if it is not set, other browsing contexts might still be protected by other flags.

The sandboxed plugins browsing context flag

This flag prevents content from instantiating plugins, whether using the embed element, the object element, or through navigation of their nested browsing context, unless those plugins can be secured.

The sandboxed origin browsing context flag

This flag forces content into a unique origin, thus preventing it from accessing other content from the same origin.

This flag also prevents script from reading from or writing to the document.cookie IDL attribute, and blocks access to localStorage.

The sandboxed forms browsing context flag

This flag blocks form submission.

The sandboxed pointer lock browsing context flag

This flag disables the Pointer Lock API. [POINTERLOCK]

The sandboxed scripts browsing context flag

This flag blocks script execution.

The sandboxed automatic features browsing context flag

This flag blocks features that trigger automatically, such as automatically playing a video or automatically focusing a form control.

The sandboxed document.domain browsing context flag

This flag prevents content from using the document.domain setter.

The sandbox propagates to auxiliary browsing contexts flag

This flag prevents content from escaping the sandbox by ensuring that any auxiliary browsing context it creates inherits the content's active sandboxing flag set.

The sandboxed modals flag

This flag prevents content from using any of the following features to produce modal dialogs:

The sandboxed orientation lock browsing context flag

This flag disables the ability to lock the screen orientation. [SCREENORIENTATION]

The sandboxed presentation browsing context flag

This flag disables the Presentation API. [PRESENTATION]

The sandboxed downloads browsing context flag

This flag prevents content from initiating or instantiating downloads, whether through downloading hyperlinks or through navigation that gets handled as a download.

When the user agent is to parse a sandboxing directive, given a string input, a sandboxing flag set output, it must run the following steps:

  1. Split input on ASCII whitespace, to obtain tokens.

  2. Let output be empty.

  3. Add the following flags to output:


Every top-level browsing context has a popup sandboxing flag set, which is a sandboxing flag set. When a browsing context is created, its popup sandboxing flag set must be empty. It is populated by the rules for choosing a browsing context and the obtain a browsing context to use for a navigation response algorithm.

Every iframe element has an iframe sandboxing flag set, which is a sandboxing flag set. Which flags in an iframe sandboxing flag set are set at any particular time is determined by the iframe element's sandbox attribute.

Every Document has an active sandboxing flag set, which is a sandboxing flag set. When the Document is created, its active sandboxing flag set must be empty. It is populated by the navigation algorithm.

Every resource that is obtained by the navigation algorithm has a forced sandboxing flag set, which is a sandboxing flag set. A resource by default has no flags set in its forced sandboxing flag set, but other specifications can define that certain flags are set.

In particular, the forced sandboxing flag set is used by Content Security Policy. [CSP]


To determine the creation sandboxing flags for a browsing context browsing context, given null or an element embedder, return the union of the flags that are present in the following sandboxing flag sets:

After creation, the sandboxing flags for a browsing context browsing context are the result of determining the creation sandboxing flags given browsing context and browsing context's container.

7.7 Cross-origin opener policies

A cross-origin opener policy allows a document which is navigated to in a top-level browsing context to force the creation of a new top-level browsing context, and a corresponding group. It has one of the following values:

"unsafe-none"

This is the (current) default and means that the document will occupy the same top-level browsing context as its predecessor, unless that document specified a different cross-origin opener policy.

"same-origin-allow-popups"

This forces the creation of a new top-level browsing context for the document, unless its predecessor specified the same cross-origin opener policy and they are same origin.

"same-origin"

This behaves the same as "same-origin-allow-popups", with the addition that any auxiliary browsing context created needs to contain same origin documents that also have the same cross-origin opener policy or it will appear closed to the opener.

"same-origin-plus-COEP"

This behaves the same as "same-origin", with the addition that it sets the (new) top-level browsing context's group's cross-origin isolated to true.

"same-origin-plus-COEP" cannot be directly set via the `Cross-Origin-Opener-Policy` header, but results from a combination of setting both `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` together.

To match cross-origin opener policies, given a cross-origin opener policy A, an origin originA, a cross-origin opener policy B, and an origin originB:

  1. If A is "unsafe-none" and B is "unsafe-none", then return true.

  2. If A is "unsafe-none" or B is "unsafe-none", then return false.

  3. If A is B and originA is same origin with originB, then return true.

  4. Return false.

7.7.1 The `Cross-Origin-Opener-Policy` header

A Document's cross-origin opener policy is derived from the `Cross-Origin-Opener-Policy` HTTP response header. This header is a structured header whose value must be a token. [STRUCTURED-FIELDS]

The valid token values are "unsafe-none", "same-origin-allow-popups", and "same-origin".

Per the processing model described below, user agents will ignore this header if it contains an invalid value. Likewise, user agents will ignore this header if the value cannot be parsed as a token.


To obtain a cross-origin opener policy given a response response and an environment reservedEnvironment:

  1. If reservedEnvironment is a non-secure context, then return "unsafe-none".

  2. Let value be the result of getting a structured field value given `Cross-Origin-Opener-Policy` and "item" from response's header list.

  3. If value is null, then return "unsafe-none".

  4. If value[0] is not "same-origin" or "same-origin-allow-popups", then return "unsafe-none".

  5. If value[0] is "same-origin", then:

    1. Let coep be the result of obtaining an embedder policy from response.

    2. If coep's value is "require-corp", then return "same-origin-plus-COEP".

  6. Return value[0].

7.7.2 Browsing context group switches due to cross-origin opener policy

A cross-origin opener policy enforcement result is a struct with the following items:

To enforce a response's cross-origin opener policy, given a browsing context browsingContext, an origin responseOrigin, a cross-origin opener policy responseCOOP, and a cross-origin opener policy enforcement result currentCOOPEnforcementResult:

  1. Let newCOOPEnforcementResult be a new cross-origin opener policy enforcement result whose needs a browsing context group switch is currentCOOPEnforcementResult's needs a browsing context group switch, origin is responseOrigin, and cross-origin opener policy is responseCOOP.

  2. Let isInitialAboutBlank be false.

  3. If browsingContext's only entry in its session history is the about:blank Document that was added when browsingContext was created, then set isInitialAboutBlank to true.

  4. If the result of matching currentCOOPEnforcementResult's cross-origin opener policy, currentCOOPEnforcementResult's origin, responseCOOP, and responseOrigin is true, then return newCOOPEnforcementResult.

  5. If all of the following are true:

    then return newCOOPEnforcementResult.

  6. Set newCOOPEnforcementResult's needs a browsing context group switch to true.

  7. Return newCOOPEnforcementResult.

To obtain a browsing context to use for a navigation response, given a browsing context browsingContext, a sandboxing flag set sandboxFlags, and a cross-origin opener policy navigationCOOP:

  1. Assert: browsingContext is a top-level browsing context.

  2. Let newBrowsingContext be the result of creating a new top-level browsing context.

  3. If navigationCOOP is "same-origin-plus-COEP", then set newBrowsingContext's group's cross-origin isolated to true.

  4. If sandboxFlags is not empty, then:

    1. Assert: navigationCOOP is "unsafe-none".

    2. Assert: newBrowsingContext's popup sandboxing flag set is empty.

    3. Set newBrowsingContext's popup sandboxing flag set to a clone of sandboxFlags.

  5. Discard browsingContext.

    This has no effect on browsingContext's group, unless browsingContext was its sole top-level browsing context. In that case, the user agent might delete the browsing context group which no longer contains any browsing contexts.

  6. Return newBrowsingContext.

The impact of swapping browsing context groups following a navigation is not fully defined. It is currently under discussion in issue #5350.

7.8 Cross-origin embedder policies

Headers/Cross-Origin-Embedder-Policy

Support in all current engines.

Firefox79+Safari15.2+Chrome83+
Opera69+Edge83+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS15.2+Chrome Android83+WebView Android86+Samsung Internet13.0+Opera Android59+

An embedder policy value controls the fetching of cross-origin resources without explicit permission from resource owners. There are two such values:

"unsafe-none"

This is the default value. When this value is used, cross-origin resources can be fetched without giving explicit permission through the CORS protocol or the `Cross-Origin-Resource-Policy` header.

"require-corp"

When this value is used, fetching cross-origin resources requires the server's explicit permission through the CORS protocol or the `Cross-Origin-Resource-Policy` header.

An embedder policy consists of:

The "coep" report type is a report type whose value is "coep". It is visible to ReportingObservers.

7.8.1 The headers

The `Cross-Origin-Embedder-Policy` and `Cross-Origin-Embedder-Policy-Report-Only` HTTP response header fields allow a server to declare an embedder policy for an environment settings object. These headers are structured headers whose values must be token. [STRUCTURED-FIELDS]

The valid token values are the embedder policy values. The token may also have attached parameters; of these, the "report-to" parameter can have a valid URL string identifying an appropriate reporting endpoint. [REPORTING]

The processing model fails open (by defaulting to "unsafe-none") in the presence of a header that cannot be parsed as a token. This includes inadvertent lists created by combining multiple instances of the `Cross-Origin-Embedder-Policy` header present in a given response:

`Cross-Origin-Embedder-Policy`Final embedder policy value
No header delivered"unsafe-none"
`require-corp`"require-corp"
`unknown-value`"unsafe-none"
`require-corp, unknown-value`"unsafe-none"
`unknown-value, unknown-value`"unsafe-none"
`unknown-value, require-corp`"unsafe-none"
`require-corp, require-corp`"unsafe-none"

(The same applies to `Cross-Origin-Embedder-Policy-Report-Only`.)


To obtain an embedder policy from a response response:

  1. Let policy be a new embedder policy.

  2. Let parsedItem be the result of getting a structured field value with `Cross-Origin-Embedder-Policy` and "item" from response's header list.

  3. If parsedItem is non-null and parsedItem[0] is "require-corp":

    1. Set policy's value to "require-corp".

    2. If parsedItem[1]["report-to"] exists, then set policy's endpoint to parsedItem[1]["report-to"].

  4. Set parsedItem to the result of getting a structured field value with `Cross-Origin-Embedder-Policy-Report-Only` and "item" from response's header list.

  5. If parsedItem is non-null and parsedItem[0] is "require-corp":

    1. Set policy's report only value to "require-corp".

    2. If parsedItem[1]["report-to"] exists, then set policy's report only reporting endpoint to parsedItem[1]["report-to"].

  6. Return policy.

7.8.2 Embedder policy checks

To check a navigation response's adherence to its embedder policy given a response response and a browsing context target:

  1. If target is not a child browsing context, then return true.

  2. Let responsePolicy be the result of obtaining an embedder policy from response.

  3. Let parentPolicy be target's container document's embedder policy.

  4. If parentPolicy's report only value is "require-corp" and responsePolicy's value is "unsafe-none", then queue a cross-origin embedder policy inheritance violation with response, "navigation", parentPolicy's report only reporting endpoint, "reporting", and target's container document's relevant settings object.

  5. If parentPolicy's value is "unsafe-none" or responsePolicy's value is "require-corp", then return true.

  6. Queue a cross-origin embedder policy inheritance violation with response, "navigation", parentPolicy's reporting endpoint, "enforce", and target's container document's relevant settings object.

  7. Return false.

To check a global object's embedder policy given a WorkerGlobalScope workerGlobalScope, an environment settings object owner, and a response response:

  1. If workerGlobalScope is not a DedicatedWorkerGlobalScope object, then return true.

  2. Let policy be workerGlobalScope's embedder policy.

  3. Let ownerPolicy be owner's embedder policy.

  4. If ownerPolicy's report only value is "require-corp" and policy's value is "unsafe-none", then queue a cross-origin embedder policy inheritance violation with response, "worker initialization", owner's policy's report only reporting endpoint, "reporting", and owner.

  5. If ownerPolicy's value is "unsafe-none" or policy's value is "require-corp", then return true.

  6. Queue a cross-origin embedder policy inheritance violation with response, "worker initialization", owner's policy's reporting endpoint, "enforce", and owner.

  7. Return false.

To queue a cross-origin embedder policy inheritance violation given a response response, a string type, a string endpoint, a string disposition, and an environment settings object settings:

  1. Let serialized be the result of serializing a response URL for reporting with response.

  2. Let body be a new object containing the following properties:

    keyvalue
    typetype
    blockedURLserialized
    dispositiondisposition
  3. Queue body as the "coep" report type for endpoint on settings.

7.9 Session history and navigation

7.9.1 Browsing sessions

A browsing session is …. See whatwg/html issue #4782 and whatwg/html issue #5350 for defining browsing session. It is roughly analogous to a top-level browsing context except that it cannot be replaced due to a `Cross-Origin-Opener-Policy` header or navigation.

A top-level browsing context has an associated browsing session which is a browsing session.

The browsing session of an environment settings object environment is the result of running these steps:

  1. Assert: environment has a responsible document.

  2. Return environment's responsible document's browsing context's top-level browsing context's browsing session.

7.9.2 The session history of browsing contexts

The sequence of Documents in a browsing context is its session history. Each browsing context, including child browsing contexts, has a distinct session history. A browsing context's session history consists of a flat list of session history entries.

Each Document object in a browsing context's session history is associated with a unique History object which must all model the same underlying session history.

The history getter steps are to return this's associated Document's History instance.


A session history entry is a struct with the following items:

Serialized state is a serialization (via StructuredSerializeForStorage) of an object representing a user interface state. We sometimes informally refer to "state objects", which are the objects representing user interface state supplied by the author, or alternately the objects created by deserializing (via StructuredDeserialize) serialized state.

Pages can add serialized state to the session history. These are then deserialized and returned to the script when the user (or script) goes back in the history, thus enabling authors to use the "navigation" metaphor even in one-page applications.

Serialized state is intended to be used for two main purposes: first, storing a preparsed description of the state in the URL so that in the simple case an author doesn't have to do the parsing (though one would still need the parsing for handling URLs passed around by users, so it's only a minor optimization). Second, so that the author can store state that one wouldn't store in the URL because it only applies to the current Document instance and it would have to be reconstructed if a new Document were opened.

An example of the latter would be something like keeping track of the precise coordinate from which a popup div was made to animate, so that if the user goes back, it can be made to animate to the same location. Or alternatively, it could be used to keep a pointer into a cache of data that would be fetched from the server based on the information in the URL, so that when going back and forward, the information doesn't have to be fetched again.

A scroll restoration mode indicates whether the user agent should restore the persisted scroll position (if any) when traversing to an entry. A scroll restoration mode is one of the following:

"auto"
The user agent is responsible for restoring the scroll position upon navigation.
"manual"
The page is responsible for restoring the scroll position and the user agent does not attempt to do so automatically

Several contiguous entries in a session history can share the same document. This can occur when the initial entry is reached via normal navigation, and the following entry is added via history.pushState(). Or it can occur via navigation to a fragment.

All entries that share the same document (and that are therefore merely different states of one particular document) are contiguous by definition.

User agents may discard the documents of entries with non-null documents, as long as the following conditions are met:

Apart from these restrictions, this standard does not specify when user agents should discard an entry's document, versus keeping it cached.

Discarding a Document will set the corresponding document item of any session history entries to null. Subsequent navigations to those entries will result in the creation of a new Document object, and set the document item to it.


At any point, one of the entries in the session history is the current entry. This is the entry representing the active document of the browsing context. Which entry is the current entry is changed by the algorithms defined in this specification, e.g., during session history traversal.

The current entry is usually the initial entry created upon navigation. However, it can also be one of the contiguous entries that share the same document, as described above.

Each Document in a browsing context can also have a latest entry. This is the entry for that Document to which the browsing context's session history was most recently traversed. When a Document is created, it initially has no latest entry.

7.9.3 The History interface

History

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Window/history

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
enum ScrollRestoration { "auto", "manual" };

[Exposed=Window]
interface History {
  readonly attribute unsigned long length;
  attribute ScrollRestoration scrollRestoration;
  readonly attribute any state;
  undefined go(optional long delta = 0);
  undefined back();
  undefined forward();
  undefined pushState(any data, DOMString title, optional USVString? url = null);
  undefined replaceState(any data, DOMString title, optional USVString? url = null);
};
window . history . length

History/length

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the number of entries in the joint session history.

window . history . scrollRestoration [ = value ]

History/scrollRestoration

Support in all current engines.

Firefox46+Safari11+Chrome46+
Opera33+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android46+Safari iOS11+Chrome Android46+WebView Android46+Samsung Internet5.0+Opera Android33+

Returns the scroll restoration mode of the current entry in the session history.

Can be set, to change the scroll restoration mode of the current entry in the session history.

window . history . state

History/state

Support in all current engines.

Firefox4+Safari6+Chrome19+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS6+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android12.1+

Returns the current serialized state, deserialized into an object.

window . history . go( [ delta ] )

History/go

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Goes back or forward the specified number of steps in the joint session history.

A zero delta will reload the current page.

If the delta is out of range, does nothing.

window . history . back()

History/back

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Goes back one step in the joint session history.

If there is no previous page, does nothing.

window . history . forward()

History/forward

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Goes forward one step in the joint session history.

If there is no next page, does nothing.

window . history . pushState(data, title [, url ] )

History/pushState

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11.5+

Pushes the given data onto the session history, with the given title, and, if provided and not null, the given URL.

window . history . replaceState(data, title [, url ] )

History/replaceState

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11.5+

Updates the current entry in the session history to have the given data, title, and, if provided and not null, URL.

The joint session history of a top-level browsing context is the union of all the session histories of all browsing contexts of all the fully active Document objects that share that top-level browsing context, with all the entries that are current entries in their respective session histories removed except for the current entry of the joint session history.

The current entry of the joint session history is the entry that most recently became a current entry in its session history.

Entries in the joint session history are ordered chronologically by the time they were added to their respective session histories. Each entry has an index; the earliest entry has index 0, and the subsequent entries are numbered with consecutively increasing integers (1, 2, 3, etc).

Since each Document in a browsing context might have a different event loop, the actual state of the joint session history can be somewhat nebulous. For example, two sibling iframe elements could both traverse from one unique origin to another at the same time, so their precise order might not be well-defined; similarly, since they might only find out about each other later, they might disagree about the length of the joint session history.

Each History object has state, initially null.

The length getter steps are:

  1. If this's associated Document is not fully active, then throw a "SecurityError" DOMException.

  2. Return the number of entries in the top-level browsing context's joint session history.

The actual entries are not accessible from script.

The scrollRestoration getter steps are:

  1. If this's associated Document is not fully active, then throw a "SecurityError" DOMException.

  2. Return this's session history's current entry's scroll restoration mode.

The scrollRestoration setter steps are:

  1. If this's associated Document is not fully active, then throw a "SecurityError" DOMException.

  2. Set this's session history's current entry's scroll restoration mode to the given value.

The state getter steps are:

  1. If this's associated Document is not fully active, then throw a "SecurityError" DOMException.

  2. Return this's state.

The go(delta) method steps are:

  1. Let document be this's associated Document.

  2. If document is not fully active, then throw a "SecurityError" DOMException.

  3. If delta is 0, then act as if the location.reload() method was called, and return.

  4. Traverse the history by a delta with delta and document's browsing context.

The back() method steps are:

  1. Let document be this's associated Document.

  2. If document is not fully active, then throw a "SecurityError" DOMException.

  3. Traverse the history by a delta with −1 and document's browsing context.

The forward() method steps are:

  1. Let document be this's associated Document.

  2. If document is not fully active, then throw a "SecurityError" DOMException.

  3. Traverse the history by a delta with +1 and document's browsing context.


Each top-level browsing context has a session history traversal queue, initially empty, to which tasks can be added.

Each top-level browsing context, when created, must begin running the following algorithm, known as the session history event loop for that top-level browsing context, in parallel:

  1. Wait until this top-level browsing context's session history traversal queue is not empty.

  2. Pull the first task from this top-level browsing context's session history traversal queue, and execute it.

  3. Return to the first step of this algorithm.

The session history event loop helps coordinate cross-browsing-context transitions of the joint session history: since each browsing context might, at any particular time, have a different event loop (this can happen if the user navigates from example.com to shop.example), transitions would otherwise have to involve cross-event-loop synchronization.


To traverse the history by a delta given delta and browsing context source browsing context, the user agent must append a task to this top-level browsing context's session history traversal queue, the task consisting of running the following steps:

  1. If the index of the current entry of the joint session history plus delta is less than zero or greater than or equal to the number of items in the joint session history, then return.

  2. Let specified entry be the entry in the joint session history whose index is the sum of delta and the index of the current entry of the joint session history.

  3. Let specified browsing context be the browsing context of the specified entry.

  4. If source browsing context is not allowed to navigate specified browsing context, then return.

  5. If the specified browsing context's active document's unload a document algorithm is currently running, return.

  6. Queue a global task on the history traversal task source given specified browsing context's active window to perform the following steps:

    1. If there is an ongoing attempt to navigate specified browsing context that has not yet matured (i.e. it has not passed the point of making its Document the active document), then cancel that attempt to navigate the browsing context.

    2. If the specified browsing context's active document is not the same Document as the Document of the specified entry, then run these substeps:

      1. Prompt to unload the active document of the specified browsing context. If the user refused to allow the document to be unloaded, then return.

      2. Unload the active document of the specified browsing context.

    3. Traverse the history of the specified browsing context to the specified entry with explicitHistoryNavigation set to true.

When the user navigates through a browsing context, e.g. using a browser's back and forward buttons, the user agent must traverse the history by a delta with a delta equivalent to the action specified by the user and the browsing context being operated on.


The URL and history update steps, given a Document document, a URL newURL, an optional serialized state-or-null serializedData (default null), an optional string-or-null title (default null), and an optional boolean isPush (default false), are:

  1. Let browsingContext be document's browsing context.

  2. If isPush is true, then:

    1. Remove all the entries in browsingContext's session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

      This doesn't necessarily have to affect the user agent's user interface.

    2. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context's document family.

    3. Save persisted state to the current entry.

    4. Add a session history entry entry to browsingContext's session history, after the current entry, with

    5. Update the current entry to be this newly added entry.

  3. Otherwise:

    1. Let entry be browsingContext's session history's current entry.

    2. Set entry's URL to newURL.

    3. If serializedData is not null, then set entry's serialized state to serializedData.

    4. Set entry's title to title.

    5. Update entry so that it represents a GET request, if it currently represents a non-GET request (e.g. it was the result of a POST submission).

      What does this mean? This is not a part of the definition of session history entry.

  4. Set document's URL to newURL.

    Since this is neither a navigation of the browsing context nor a history traversal, it does not cause a hashchange event to be fired.

The pushState(data, title, url) method steps are to run the shared history push/replace state steps given this, data, title, url, and true.

The replaceState(data, title, url) method steps are to run the shared history push/replace state steps given this, data, title, url, and false.

The shared history push/replace state steps, given a History history, a value data, a string title, a scalar value string-or-null url, and a boolean isPush, are:

  1. Let document be history's associated Document.

  2. If document is not fully active, then throw a "SecurityError" DOMException.

  3. Optionally, return. (For example, the user agent might disallow calls to these methods that are invoked on a timer, or from event listeners that are not triggered in response to a clear user action, or that are invoked in rapid succession.)

  4. Let targetRealm be history's relevant Realm.

  5. Let serializedData be StructuredSerializeForStorage(data). Rethrow any exceptions.

  6. Let newURL be the session history's current entry's URL.

  7. If url is not null, then:

    1. Parse url, relative to the relevant settings object of history.

    2. If that fails, then throw a "SecurityError" DOMException.

    3. Set newURL to the resulting URL record.

    4. Compare newURL to document's URL. If any component of these two URL records differ other than the path, query, and fragment components, then throw a "SecurityError" DOMException.

    5. If the origin of newURL is not same origin with the origin of document, and either the path or query components of the two URL records compared in the previous step differ, throw a "SecurityError" DOMException. (This prevents sandboxed content from spoofing other pages on the same origin.)

  8. Run the URL and history update steps given document and newURL, with serializedData set to serializedData, title set to title, and isPush set to isPush.

  9. Let state be StructuredDeserialize(serializedData, targetRealm). If this throws an exception, catch it, ignore the exception, and set state to null.

  10. Set history's state to state.

  11. Set the current entry's document's latest entry to the current entry.

The title is purely advisory. User agents might use the title in the user interface.

User agents may limit the number of state objects added to the session history per page. If a page hits the implementation-defined limit, user agents must remove the entry immediately after the first entry for that Document object in the session history after having added the new entry. (Thus the state history acts as a FIFO buffer for eviction, but as a LIFO buffer for navigation.)

Consider a game where the user can navigate along a line, such that the user is always at some coordinate, and such that the user can bookmark the page corresponding to a particular coordinate, to return to it later.

A static page implementing the x=5 position in such a game could look like the following:

<!DOCTYPE HTML>
<!-- this is https://example.com/line?x=5 -->
<html lang="en">
<title>Line Game - 5</title>
<p>You are at coordinate 5 on the line.</p>
<p>
 <a href="?x=6">Advance to 6</a> or
 <a href="?x=4">retreat to 4</a>?
</p>

The problem with such a system is that each time the user clicks, the whole page has to be reloaded. Here instead is another way of doing it, using script:

<!DOCTYPE HTML>
<!-- this starts off as https://example.com/line?x=5 -->
<html lang="en">
<title>Line Game - 5</title>
<p>You are at coordinate <span id="coord">5</span> on the line.</p>
<p>
 <a href="?x=6" onclick="go(1); return false;">Advance to 6</a> or
 <a href="?x=4" onclick="go(-1); return false;">retreat to 4</a>?
</p>
<script>
 var currentPage = 5; // prefilled by server
 function go(d) {
   setupPage(currentPage + d);
   history.pushState(currentPage, document.title, '?x=' + currentPage);
 }
 onpopstate = function(event) {
   setupPage(event.state);
 }
 function setupPage(page) {
   currentPage = page;
   document.title = 'Line Game - ' + currentPage;
   document.getElementById('coord').textContent = currentPage;
   document.links[0].href = '?x=' + (currentPage+1);
   document.links[0].textContent = 'Advance to ' + (currentPage+1);
   document.links[1].href = '?x=' + (currentPage-1);
   document.links[1].textContent = 'retreat to ' + (currentPage-1);
 }
</script>

In systems without script, this still works like the previous example. However, users that do have script support can now navigate much faster, since there is no network access for the same experience. Furthermore, contrary to the experience the user would have with just a naïve script-based approach, bookmarking and navigating the session history still work.

In the example above, the data argument to the pushState() method is the same information as would be sent to the server, but in a more convenient form, so that the script doesn't have to parse the URL each time the user navigates.

Applications might not use the same title for a session history entry as the value of the document's title element at that time. For example, here is a simple page that shows a block in the title element. Clearly, when navigating backwards to a previous state the user does not go back in time, and therefore it would be inappropriate to put the time in the session history title.

<!DOCTYPE HTML>
<HTML LANG=EN>
<TITLE>Line</TITLE>
<SCRIPT>
 setInterval(function () { document.title = 'Line - ' + new Date(); }, 1000);
 var i = 1;
 function inc() {
   set(i+1);
   history.pushState(i, 'Line - ' + i);
 }
 function set(newI) {
   i = newI;
   document.forms.F.I.value = newI;
 }
</SCRIPT>
<BODY ONPOPSTATE="set(event.state)">
<FORM NAME=F>
State: <OUTPUT NAME=I>1</OUTPUT> <INPUT VALUE="Increment" TYPE=BUTTON ONCLICK="inc()">
</FORM>

Most applications want to use the same scroll restoration mode value for all of their history entries. To achieve this they can set the scrollRestoration attribute as soon as possible (e.g., in the first script element in the document's head element) to ensure that any entry added to the history session gets the desired scroll restoration mode.

<head>
  <script>
       if ('scrollRestoration' in history)
            history.scrollRestoration = 'manual';
  </script>
</head>
   

7.9.4 Implementation notes for session history

This section is non-normative.

The History interface is not meant to place restrictions on how implementations represent the session history to the user.

For example, session history could be implemented in a tree-like manner, with each page having multiple "forward" pages. This specification doesn't define how the linear list of pages in the history object are derived from the actual session history as seen from the user's perspective.

Similarly, a page containing two iframes has a history object distinct from the iframes' history objects, despite the fact that typical web browsers present the user with just one "Back" button, with a session history that interleaves the navigation of the two inner frames and the outer page.

Security: It is suggested that to avoid letting a page "hijack" the history navigation facilities of a UA by abusing pushState(), the UA provide the user with a way to jump back to the previous page (rather than just going back to the previous state). For example, the back button could have a drop down showing just the pages in the session history, and not showing any of the states. Similarly, an aural browser could have two "back" commands, one that goes back to the previous state, and one that jumps straight back to the previous page.

For both pushState() and replaceState(), user agents are encouraged to prevent abuse of these APIs via too-frequent calls or over-large state objects. As detailed above, the algorithm explicitly allows user agents to ignore any such calls when appropriate.

7.9.5 The Location interface

Document/location

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Location

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Window/location

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Each Window object is associated with a unique instance of a Location object, allocated when the Window object is created.

The Location exotic object is defined through a mishmash of IDL, invocation of JavaScript internal methods post-creation, and overridden JavaScript internal methods. Coupled with its scary security policy, please take extra care while implementing this excrescence.

To create a Location object, run these steps:

  1. Let location be a new Location platform object.

  2. Let valueOf be location's relevant Realm.[[Intrinsics]].[[%Object.prototype.valueOf%]].

  3. Perform ! location.[[DefineOwnProperty]]("valueOf", { [[Value]]: valueOf, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).

  4. Perform ! location.[[DefineOwnProperty]](@@toPrimitive, { [[Value]]: undefined, [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }).

  5. Set the value of the [[DefaultProperties]] internal slot of location to location.[[OwnPropertyKeys]]().

  6. Return location.

The addition of valueOf and @@toPrimitive own data properties, as well as the fact that all of Location's IDL attributes are marked [LegacyUnforgeable], is required by legacy code that consulted the Location interface, or stringified it, to determine the document URL, and then used it in a security-sensitive way. In particular, the valueOf, @@toPrimitive, and [LegacyUnforgeable] stringifier mitigations ensure that code such as foo[location] = bar or location + "" cannot be misdirected.

document . location [ = value ]
window . location [ = value ]

Returns a Location object with the current page's location.

Can be set, to navigate to another page.

The Document object's location attribute's getter must return this Document object's relevant global object's Location object, if this Document object is fully active, and null otherwise.

The Window object's location attribute's getter must return this Window object's Location object.

Location objects provide a representation of the URL of the active document of their Document's browsing context, and allow the current entry of the browsing context's session history to be changed, by adding or replacing entries in the history object.

[Exposed=Window]
interface Location { // but see also additional creation steps and overridden internal methods
  [LegacyUnforgeable] stringifier attribute USVString href;
  [LegacyUnforgeable] readonly attribute USVString origin;
  [LegacyUnforgeable] attribute USVString protocol;
  [LegacyUnforgeable] attribute USVString host;
  [LegacyUnforgeable] attribute USVString hostname;
  [LegacyUnforgeable] attribute USVString port;
  [LegacyUnforgeable] attribute USVString pathname;
  [LegacyUnforgeable] attribute USVString search;
  [LegacyUnforgeable] attribute USVString hash;

  [LegacyUnforgeable] undefined assign(USVString url);
  [LegacyUnforgeable] undefined replace(USVString url);
  [LegacyUnforgeable] undefined reload();

  [LegacyUnforgeable, SameObject] readonly attribute DOMStringList ancestorOrigins;
};
location . toString()
location . href

Location/href

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Location/toString

Support in all current engines.

Firefox22+Safari1+Chrome52+
Opera39+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android22+Safari iOS1+Chrome Android52+WebView Android52+Samsung Internet6.0+Opera Android41+

Returns the Location object's URL.

Can be set, to navigate to the given URL.

location . origin

Location/origin

Support in all current engines.

Firefox21+Safari5.1+Chrome8+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android21+Safari iOS5+Chrome Android18+WebView Android3+Samsung Internet1.0+Opera Android14+

Returns the Location object's URL's origin.

location . protocol

Location/protocol

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the Location object's URL's scheme.

Can be set, to navigate to the same URL with a changed scheme.

location . host

Location/host

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the Location object's URL's host and port (if different from the default port for the scheme).

Can be set, to navigate to the same URL with a changed host and port.

location . hostname

Location/hostname

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the Location object's URL's host.

Can be set, to navigate to the same URL with a changed host.

location . port

Location/port

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the Location object's URL's port.

Can be set, to navigate to the same URL with a changed port.

location . pathname

Location/pathname

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the Location object's URL's path.

Can be set, to navigate to the same URL with a changed path.

location . search

Location/search

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the Location object's URL's query (includes leading "?" if non-empty).

Can be set, to navigate to the same URL with a changed query (ignores leading "?").

location . hash

Location/hash

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer3+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the Location object's URL's fragment (includes leading "#" if non-empty).

Can be set, to navigate to the same URL with a changed fragment (ignores leading "#").

location . assign(url)

Location/assign

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Navigates to the given URL.

location . replace(url)

Location/replace

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Removes the current page from the session history and navigates to the given URL.

location . reload()

Location/reload

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Reloads the current page.

location . ancestorOrigins

Location/ancestorOrigins

FirefoxNoSafari6+Chrome20+
Opera15+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS6+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android14+

Returns a DOMStringList object listing the origins of the ancestor browsing contexts, from the parent browsing context to the top-level browsing context.

A Location object has an associated relevant Document, which is this Location object's relevant global object's browsing context's active document, if this Location object's relevant global object's browsing context is non-null, and null otherwise.

A Location object has an associated url, which is this Location object's relevant Document's URL, if this Location object's relevant Document is non-null, and about:blank otherwise.

A Location object has an associated ancestor origins list. When a Location object is created, its ancestor origins list must be set to a DOMStringList object whose associated list is the list of strings that the following steps would produce:

  1. Let output be a new list of strings.

  2. Let current be the browsing context of the Document with which this Location object is associated.

  3. Loop: If current has no parent browsing context, jump to the step labeled end.

  4. Let current be current's parent browsing context.

  5. Append the serialization of current's active document's origin to output.

  6. Return to the step labeled loop.

  7. End: Return output.

A Location object has an associated Location-object-setter navigate algorithm, which given a url, runs these steps:

  1. Let historyHandling be "replace".

  2. If any of the following conditions are met, then set historyHandling to "default":

  3. Location-object navigate, given url and historyHandling.

To Location-object navigate, given a url and historyHandling:

  1. Let browsingContext be the current global object's browsing context.

  2. Let sourceBrowsingContext be the incumbent global object's browsing context.

  3. If browsingContext's session history contains only one Document, and that was the about:blank Document created when the browsing context was created, then set historyHandling to "replace".

  4. Navigate browsingContext to url, with exceptionsEnabled set to true, historyHandling set to historyHandling, and the source browsing context set to sourceBrowsingContext.

The href attribute's getter must run these steps:

  1. If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. Return this Location object's url, serialized.

The href attribute's setter must run these steps:

  1. If this Location object's relevant Document is null, then return.

  2. Parse the given value relative to the entry settings object. If that failed, throw a TypeError exception.

  3. Location-object-setter navigate given the resulting URL record.

The href attribute setter intentionally has no security check.

The origin attribute's getter must run these steps:

  1. If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. Return the serialization of this Location object's url's origin.

The protocol attribute's getter must run these steps:

  1. If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. Return this Location object's url's scheme, followed by ":".

The protocol attribute's setter must run these steps:

  1. If this Location object's relevant Document is null, then return.

  2. If this Location object's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this Location object's url.

  4. Let possibleFailure be the result of basic URL parsing the given value, followed by ":", with copyURL as url and scheme start state as state override.

    Because the URL parser ignores multiple consecutive colons, providing a value of "https:" (or even "https::::") is the same as providing a value of "https".

  5. If possibleFailure is failure, then throw a "SyntaxError" DOMException.

  6. If copyURL's scheme is not an HTTP(S) scheme, then terminate these steps.

  7. Location-object-setter navigate to copyURL.

The host attribute's getter must run these steps:

  1. If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. Let url be this Location object's url.

  3. If url's host is null, return the empty string.

  4. If url's port is null, return url's host, serialized.

  5. Return url's host, serialized, followed by ":" and url's port, serialized.

The host attribute's setter must run these steps:

  1. If this Location object's relevant Document is null, then return.

  2. If this Location object's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this Location object's url.

  4. If copyURL's cannot-be-a-base-URL flag is set, terminate these steps.

  5. Basic URL parse the given value, with copyURL as url and host state as state override.

  6. Location-object-setter navigate to copyURL.

The hostname attribute's getter must run these steps:

  1. If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. If this Location object's url's host is null, return the empty string.

  3. Return this Location object's url's host, serialized.

The hostname attribute's setter must run these steps:

  1. If this Location object's relevant Document is null, then return.

  2. If this Location object's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this Location object's url.

  4. If copyURL's cannot-be-a-base-URL flag is set, terminate these steps.

  5. Basic URL parse the given value, with copyURL as url and hostname state as state override.

  6. Location-object-setter navigate to copyURL.

The port attribute's getter must run these steps:

  1. If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. If this Location object's url's port is null, return the empty string.

  3. Return this Location object's url's port, serialized.

The port attribute's setter must run these steps:

  1. If this Location object's relevant Document is null, then return.

  2. If this Location object's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this Location object's url.

  4. If copyURL cannot have a username/password/port, then return.

  5. If the given value is the empty string, then set copyURL's port to null.

  6. Otherwise, basic URL parse the given value, with copyURL as url and port state as state override.

  7. Location-object-setter navigate to copyURL.

The pathname attribute's getter must run these steps:

  1. If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. Let url be this Location object's url.

  3. If url's cannot-be-a-base-URL flag is set, return the first string in url's path.

  4. If url's path is empty, then return the empty string.

  5. Return "/", followed by the strings in url's path (including empty strings), separated from each other by "/".

The pathname attribute's setter must run these steps:

  1. If this Location object's relevant Document is null, then return.

  2. If this Location object's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this Location object's url.

  4. If copyURL's cannot-be-a-base-URL flag is set, terminate these steps.

  5. Set copyURL's path to the empty list.

  6. Basic URL parse the given value, with copyURL as url and path start state as state override.

  7. Location-object-setter navigate to copyURL.

The search attribute's getter must run these steps:

  1. If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. If this Location object's url's query is either null or the empty string, return the empty string.

  3. Return "?", followed by this Location object's url's query.

The search attribute's setter must run these steps:

  1. If this Location object's relevant Document is null, then return.

  2. If this Location object's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this Location object's url.

  4. If the given value is the empty string, set copyURL's query to null.

  5. Otherwise, run these substeps:

    1. Let input be the given value with a single leading "?" removed, if any.

    2. Set copyURL's query to the empty string.

    3. Basic URL parse input, with copyURL as url and query state as state override, and the relevant Document's document's character encoding as encoding override.

  6. Location-object-setter navigate to copyURL.

The hash attribute's getter must run these steps:

  1. If this Location object's relevant Document is non-null and its origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  2. If this Location object's url's fragment is either null or the empty string, return the empty string.

  3. Return "#", followed by this Location object's url's fragment.

The hash attribute's setter must run these steps:

  1. If this Location object's relevant Document is null, then return.

  2. If this Location object's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Let copyURL be a copy of this Location object's url.

  4. Let input be the given value with a single leading "#" removed, if any.

  5. Set copyURL's fragment to the empty string.

  6. Basic URL parse input, with copyURL as url and fragment state as state override.

  7. Location-object-setter navigate to copyURL.

Unlike the equivalent API for the a and area elements, the hash attribute's setter does not special case the empty string to remain compatible with deployed scripts.


When the assign(url) method is invoked, the user agent must run the following steps:

  1. If this Location object's relevant Document is null, then return.

  2. If this Location object's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Parse url relative to the entry settings object. If that failed, throw a "SyntaxError" DOMException.

  4. Location-object navigate given the resulting URL record and "default".

When the replace(url) method is invoked, the user agent must run the following steps:

  1. If this Location object's relevant Document is null, then return.

  2. Parse url relative to the entry settings object. If that failed, throw a "SyntaxError" DOMException.

  3. Location-object navigate given the resulting URL record and "replace".

The replace() method intentionally has no security check.

When the reload() method is invoked, the user agent must run the appropriate steps from the following list:

If this Location object's relevant Document is null

Return.

If this Location object's relevant Document's origin is not same origin-domain with the entry settings object's origin

Throw a "SecurityError" DOMException.

If the currently executing task is the dispatch of a resize event in response to the user resizing the browsing context

Repaint the browsing context and return.

If the browsing context's active document is an iframe srcdoc document

Reprocess the iframe attributes of the browsing context's container.

Otherwise

Navigate the browsing context to this Location object's relevant Document's URL, with exceptionsEnabled set to true, historyHandling set to "reload", and the source browsing context set to the browsing context being navigated.

When a user requests that the active document of a browsing context be reloaded through a user interface element, the user agent should navigate the browsing context to the same resource as that Document, with historyHandling set to "reload". In the case of non-idempotent methods (e.g., HTTP POST), the user agent should prompt the user to confirm the operation first, since otherwise transactions (e.g., purchases or database modifications) could be repeated. User agents may allow the user to explicitly override any caches when reloading.


The ancestorOrigins attribute's getter must run these steps:

  1. If this Location object's relevant Document is null, then return an empty list.

  2. If this Location object's relevant Document's origin is not same origin-domain with the entry settings object's origin, then throw a "SecurityError" DOMException.

  3. Otherwise, return this Location object's ancestor origins list.

The details of how the ancestorOrigins attribute works are still controversial and might change. See issue #1918 for more information.


As explained earlier, the Location exotic object requires additional logic beyond IDL for security purposes. The Location object must use the ordinary internal methods except where it is explicitly specified otherwise below.

Also, every Location object has a [[DefaultProperties]] internal slot representing its own properties at time of its creation.

7.9.5.1 [[GetPrototypeOf]] ( )
  1. If ! IsPlatformObjectSameOrigin(this) is true, then return ! OrdinaryGetPrototypeOf(this).

  2. Return null.

7.9.5.2 [[SetPrototypeOf]] ( V )
  1. Return ! SetImmutablePrototype(this, V).

7.9.5.3 [[IsExtensible]] ( )
  1. Return true.

7.9.5.4 [[PreventExtensions]] ( )
  1. Return false.

7.9.5.5 [[GetOwnProperty]] ( P )
  1. If ! IsPlatformObjectSameOrigin(this) is true, then:

    1. Let desc be ! OrdinaryGetOwnProperty(this, P).

    2. If the value of the [[DefaultProperties]] internal slot of this contains P, then set desc.[[Configurable]] to true.

    3. Return desc.

  2. Let property be ! CrossOriginGetOwnPropertyHelper(this, P).

  3. If property is not undefined, then return property.

  4. Return ? CrossOriginPropertyFallback(P).

7.9.5.6 [[DefineOwnProperty]] ( P, Desc )
  1. If ! IsPlatformObjectSameOrigin(this) is true, then:

    1. If the value of the [[DefaultProperties]] internal slot of this contains P, then return false.

    2. Return ? OrdinaryDefineOwnProperty(this, P, Desc).

  2. Throw a "SecurityError" DOMException.

7.9.5.7 [[Get]] ( P, Receiver )
  1. If ! IsPlatformObjectSameOrigin(this) is true, then return ? OrdinaryGet(this, P, Receiver).

  2. Return ? CrossOriginGet(this, P, Receiver).

7.9.5.8 [[Set]] ( P, V, Receiver )
  1. If ! IsPlatformObjectSameOrigin(this) is true, then return ? OrdinarySet(this, P, Receiver).

  2. Return ? CrossOriginSet(this, P, V, Receiver).

7.9.5.9 [[Delete]] ( P )
  1. If ! IsPlatformObjectSameOrigin(this) is true, then return ? OrdinaryDelete(this, P).

  2. Throw a "SecurityError" DOMException.

7.9.5.10 [[OwnPropertyKeys]] ( )
  1. If ! IsPlatformObjectSameOrigin(this) is true, then return ! OrdinaryOwnPropertyKeys(this).

  2. Return ! CrossOriginOwnPropertyKeys(this).

7.10 Browsing the web

Certain actions cause the browsing context to navigate to a new resource. A user agent may provide various ways for the user to explicitly cause a browsing context to navigate, in addition to those defined in this specification.

For example, following a hyperlink, form submission, and the window.open() and location.assign() methods can all cause a browsing context to navigate.

A resource has a URL, but that might not be the only information necessary to identify it. For example, a form submission that uses HTTP POST would also have the HTTP method and payload. Similarly, an iframe srcdoc document needs to know the data it is to use.

Much of the navigation process is concerned with determining how to create a new Document, which ultimately happens in the create and initialize a Document object algorithm. The parameters to this algorithm are tracked via a navigation params struct, which has the following items:

request
null or a request that started the navigation
response
a response that ultimately was navigated to (potentially a network error)
origin
an origin to use for the new Document
final sandboxing flag set
a sandboxing flag set to impose on the new Document
cross-origin opener policy
a cross-origin opener policy to use for the new Document
reserved environment
null or an environment reserved for the new Document
browsing context
the browsing context to be navigated (but see below)
browsing context switch needed
a boolean indicating whether or not the navigation should conclude by discarding the given browsing context and creating a new one
history handling
a history handling behavior

Once a navigation params struct is created, this standard does not mutate any of its items. They are only passed onward to other algorithms.

After Document creation, the session history gets updated. A history handling behavior is used to track the desired type of session history update throughout the navigation process. It is one of the following:

"default"
A regular navigation which adds a new entry to the session history.
"entry update"
A navigation to an existing session history entry to recreate that entry's document, which was previously discarded.
"reload"
A navigation intended to reload the current page and replace the current session history entry.
"replace"
A non-reload navigation that will replace the current session history entry.

Navigation always involves source browsing context, which is the browsing context which was responsible for starting the navigation.

As explained in issue #1130 the use of a browsing context as source might not be the correct architecture.

To navigate a browsing context browsingContext to a resource resource, with an optional boolean exceptionsEnabled (default false), an optional history handling behavior historyHandling (default "default"), and an optional string navigationType (default "other"):

  1. If resource is a URL, then set resource to a new request whose url is resource.

  2. If resource is a request and historyHandling is "reload", then set resource's reload-navigation flag.

  3. If there is a preexisting attempt to navigate browsingContext, and the source browsing context is the same as browsingContext, and that attempt is currently running the unload a document algorithm, then return without affecting the preexisting attempt to navigate browsingContext.

  4. If the prompt to unload algorithm is being run for the active document of browsingContext, then return without affecting the prompt to unload algorithm.

  5. Let activeDocumentNavigationOrigin be the origin of the active document of browsingContext.

  6. Let incumbentNavigationOrigin be the origin of the incumbent settings object, or if no script was involved, the origin of the node document of the element that initiated the navigation.

  7. Cancel any preexisting but not yet mature attempt to navigate browsingContext, including canceling any instances of the fetch algorithm started by those attempts. If one of those attempts has already created and initialized a new Document object, abort that Document also. (Navigation attempts that have matured already have session history entries, and are therefore handled during the update the session history with the new page algorithm, later.)

  8. Prompt to unload the active document of browsingContext. If the user refused to allow the document to be unloaded, then return.

    If this instance of the navigation algorithm gets canceled while this step is running, the prompt to unload algorithm must nonetheless be run to completion.

  9. Abort the active document of browsingContext.

  10. If browsingContext is a child browsing context, then put it in the delaying load events mode.

    The user agent must take this child browsing context out of the delaying load events mode when this navigation algorithm later matures, or when it terminates (whether due to having run all the steps, or being canceled, or being aborted), whichever happens first.

  11. Let sandboxFlags be the result of determining the creation sandboxing flags given browsingContext and browsingContext's container.

  12. Return to whatever algorithm invoked the navigation steps and continue running these steps in parallel.

  13. This is the step that attempts to obtain resource, if necessary. Jump to the first appropriate substep:

    If resource is a response
    1. Assert: browsingContext is not a top-level browsing context.

    2. Let finalSandboxFlags be the union of browsingContext's sandboxing flags and resource's forced sandboxing flag set.

    3. Let responseOrigin be the result of determining the origin given browsingContext, resource's url, finalSandboxFlags, incumbentNavigationOrigin, and activeDocumentNavigationOrigin.

    4. Let navigationParams be a new navigation params whose request is null, response is resource, origin is responseOrigin, final sandboxing flag set is finalSandboxFlags, cross-origin opener policy is "unsafe-none", reserved environment is null, browsing context is browsingContext, browsing context switch needed is false, and history handling is historyHandling.

    5. Run process a navigate response with navigationType, the source browsing context, and navigationParams.

    If resource is a request whose url's scheme is "javascript"

    Queue a global task on the DOM manipulation task source given browsingContext's active window to run these steps:

    1. Let response be the result of executing a javascript: URL request given resource, the source browsing context, and browsingContext.

    2. Let finalSandboxFlags be the union of browsingContext's sandboxing flags and response's forced sandboxing flag set.

    3. Let navigationParams be a new navigation params whose request is resource, response is response, origin is activeDocumentNavigationOrigin, final sandboxing flag set is finalSandboxFlags, cross-origin opener policy is browsingContext's active document's cross-origin opener policy, reserved environment is null, browsing context is browsingContext, browsing context switch needed is false, and history handling is historyHandling.

    4. Run process a navigate response with navigationType, the source browsing context, and navigationParams.

    So for example a javascript: URL in an href attribute of an a element would only be evaluated when the link was followed, while such a URL in the src attribute of an iframe element would be evaluated in the context of the iframe's nested browsing context when the iframe is being set up. Once evaluated, its return value (if it was a string) would replace that browsing context's active document, thus also changing the corresponding Window object.

    If resource is to be fetched using `GET`, and there are relevant application caches that are identified by a URL with the same origin as the URL in question, and that have this URL as one of their entries, excluding entries marked as foreign, and whose mode is fast, and the user agent is not in a mode where it will avoid using application caches

    Fetch resource from the most appropriate application cache of those that match.

    For example, imagine an HTML page with an associated application cache displaying an image and a form, where the image is also used by several other application caches. If the user right-clicks on the image and chooses "View Image", then the user agent could decide to show the image from any of those caches, but it is likely that the most useful cache for the user would be the one that was used for the aforementioned HTML page. On the other hand, if the user submits the form, and the form does a POST submission, then the user agent will not use an application cache at all; the submission will be made to the network.

    This still needs to be integrated with the Fetch standard. [FETCH]

    If resource is a request whose url's scheme is a fetch scheme

    Run process a navigate fetch given resource, the source browsing context, browsingContext, navigationType, sandboxFlags, incumbentNavigationOrigin, activeDocumentNavigationOrigin, and historyHandling.

    Otherwise, resource is a request whose url's scheme is neither "javascript" nor a fetch scheme

    Run process a navigate URL scheme given resource's url and browsingContext.

To process a navigate fetch, given a request request, two browsing contexts sourceBrowsingContext and browsingContext, a string navigationType, a sandboxing flag set sandboxFlags, two origins incumbentNavigationOrigin and activeDocumentNavigationOrigin, and a history handling behavior historyHandling:

  1. Let response be null.

  2. Set request's client to sourceBrowsingContext's active document's relevant settings object, destination to "document", mode to "navigate", credentials mode to "include", use-URL-credentials flag, redirect mode to "manual", and replaces client id to browsingContext's active document's relevant settings object's id.

  3. If browsingContext's container is non-null:

    1. If the browsingContext's container has a browsing context scope origin, then set request's origin to that browsing context scope origin.

    2. Set request's destination to browsingContext's container's local name.

  4. Let reservedEnvironment be null.

  5. Let responseOrigin be null.

  6. Let coopEnforcementResult be a new cross-origin opener policy enforcement result whose needs a browsing context group switch is false, origin is browsingContext's active document's origin, and cross-origin opener policy is browsingContext's active document's cross-origin opener policy.

  7. Let finalSandboxFlags be an empty sandboxing flag set.

  8. Let responseCOOP be "unsafe-none".

  9. While true:

    1. Let currentURL be response's location URL, if response is not null, and request's current URL otherwise.

    2. If reservedEnvironment is not null and currentURL's origin is not the same as reservedEnvironment's creation URL's origin, then:

      1. Run the environment discarding steps for reservedEnvironment.

      2. Set reservedEnvironment to null.

    3. If reservedEnvironment is null, then:

      1. Let topLevelCreationURL be currentURL.

      2. Let topLevelOrigin be null.

      3. If browsingContext is not a top-level browsing context, then:

        1. Let parentEnvironment be browsingContext's container's relevant settings object.

        2. Set topLevelCreationURL to parentEnvironment's top-level creation URL and topLevelOrigin to parentEnvironment's top-level origin.

      4. Set reservedEnvironment to a new environment whose id is a unique opaque string, target browsing context is browsingContext, creation URL is currentURL, top-level creation URL is topLevelCreationURL, and top-level origin is topLevelOrigin.

        The created environment's active service worker is set in the Handle Fetch algorithm during the fetch if the request URL matches a service worker registration. [SW]

    4. Set request's reserved client to reservedEnvironment.

    5. If the result of Should navigation request of type be blocked by Content Security Policy? given request and navigationType is "Blocked", then set response to a network error and break. [CSP]

    6. Otherwise:

      1. If response is null, fetch request.

      2. Otherwise, perform HTTP-redirect fetch using request and response.

      3. Wait for the task on the networking task source to process response and set response to the result.

      4. Set finalSandboxFlags to the union of browsingContext's sandboxing flags and response's forced sandboxing flag set.

      5. Set responseOrigin to the result of determining the origin given browsingContext, request's url, finalSandboxFlags, incumbentNavigationOrigin, and activeDocumentNavigationOrigin.

      6. If browsingContext is a top-level browsing context, then:

        1. Set responseCOOP to the result of obtaining a cross-origin opener policy given response and reservedEnvironment.

        2. If sandboxFlags is not empty and responseCOOP is not "unsafe-none", then set response to an appropriate network error and break.

          This results in a network error as one cannot simultaneously provide a clean slate to a response using cross-origin opener policy and sandbox the result of navigating to that response.

        3. Set coopEnforcementResult to the result of enforcing the response's cross-origin opener policy given browsingContext, responseOrigin, responseCOOP, and coopEnforcementResult.

      7. If response is not a network error, browsingContext is a child browsing context, and the result of performing a cross-origin resource policy check with browsingContext's container document's origin, browsingContext's container document's relevant settings object, request's destination, response, and true is blocked, then set response to a network error and break.

        Here we're running the cross-origin resource policy check against the parent browsing context rather than sourceBrowsingContext. This is because we care about the same-originness of the embedded content against the parent context, not the navigation source.

      8. If response does not have a location URL or the location URL is not a URL whose scheme is an HTTP(S) scheme, then break.

        Navigation handles redirects manually as navigation is the only place in the web platform that cares for redirects to mailto: URLs and such.

  10. If response has a location URL that is failure, then set response to a network error.

  11. Otherwise, if response has a location URL that is a URL whose scheme is "blob", "file", "filesystem", or "javascript", then set response to a network error.

  12. Otherwise, if response has a location URL that is a URL whose scheme is a fetch scheme, then run process a navigate fetch with a new request whose url is response's location URL, sourceBrowsingContext, browsingContext, navigationType, sandboxFlags, incumbentNavigationOrigin, activeDocumentNavigationOrigin, and historyHandling, and return.

  13. Otherwise, if response has a location URL that is a URL, run the process a navigate URL scheme given response's location URL and browsingContext, and return.

  14. Fallback in prefer-online mode: If response was not fetched from an application cache, and was to be fetched using `GET`, and there are relevant application caches that are identified by a URL with the same origin as the URL in question, and that have this URL as one of their entries, excluding entries marked as foreign, and whose mode is prefer-online, and the user didn't cancel the navigation attempt during the earlier step, and response is either a network error or its status is not an ok status, then:

    Let candidate be the response identified by the URL in question from the most appropriate application cache of those that match.

    If candidate is not marked as foreign, then the user agent must discard the failed load and instead continue along these steps using candidate as response. The user agent may indicate to the user that the original page load failed, and that the page used was a previously cached response.

  15. Fallback for fallback entries: If response was not fetched from an application cache, and was to be fetched using `GET`, and its URL matches the fallback namespace of one or more relevant application caches, and the most appropriate application cache of those that match does not have an entry in its online safelist that has the same origin as response's URL and that is a prefix match for response's URL, and the user didn't cancel the navigation attempt during the earlier step, and response is either a network error or its status is not an ok status, then:

    Let candidate be the fallback response specified for the fallback namespace in question. If multiple application caches match, the user agent must use the fallback of the most appropriate application cache of those that match.

    If candidate is not marked as foreign, then the user agent must discard the failed load and instead continue along these steps using candidate as response. The document's URL, if appropriate, will still be the originally requested URL, not the fallback URL, but the user agent may indicate to the user that the original page load failed, that the page used was a fallback response, and what the URL of the fallback response actually is.

  16. Let navigationParams be a new navigation params whose request is request, response is response, origin is responseOrigin, final sandboxing flag set is finalSandboxFlags, cross-origin opener policy is responseCOOP, reserved environment is reservedEnvironment, browsing context is browsingContext, browsing context switch needed is coopEnforcementResult's needs a browsing context group switch, and history handling is historyHandling.

  17. Run process a navigate response with navigationType, the source browsing context, and navigationParams.

To process a navigate response, given a string navigationType, a browsing context source, and a navigation params navigationParams:

  1. Let response be navigationParams's response.

  2. Let browsingContext be navigationParams's browsing context.

  3. Let failure be false.

  4. If response is a network error, then set failure to true.

    Otherwise, if the result of Should navigation response to navigation request of type in target be blocked by Content Security Policy? given navigationParams's request, response, navigationType, and browsingContext is "Blocked", then set failure to true. [CSP]

    Otherwise, if the result of checking a navigation response's adherence to its embedder policy given response and browsingContext is false, then set failure to true.

    Otherwise, if the result of checking a navigation response's adherence to `X-Frame-Options` given response, browsingContext, and navigationParams's origin is false, then set failure to true.

  5. If failure is true, then:

    1. Display the inline content with an appropriate error shown to the user given browsingContext.

    2. Run the environment discarding steps for navigationParams's reserved environment.

    3. Return.

    This is where the network errors defined and propagated by Fetch, such as DNS or TLS errors, end up being displayed to users. [FETCH]

  6. If response's status is 204 or 205, then return.

  7. If response has a `Content-Disposition` header specifying the attachment disposition type, then:

    1. If the result of running the allowed to download given source and browsingContext is true, then handle response as a download.

    2. Return.

  8. Let type be the computed type of response.

  9. If the user agent has been configured to process resources of the given type using some mechanism other than rendering the content in a browsing context, then skip this step. Otherwise, if the type is one of the following types, jump to the appropriate entry in the following list, and process response as described there:

    an HTML MIME type
    Follow the steps given in the HTML document section providing navigationParams. Once the steps have completed, return.
    an XML MIME type that is not an explicitly supported XML MIME type
    Follow the steps given in the XML document section providing navigationParams and type. Once the steps have completed, return.
    a JavaScript MIME type
    a JSON MIME type that is not an explicitly supported JSON MIME type
    "text/cache-manifest"
    "text/css"
    "text/plain"
    "text/vtt"
    Follow the steps given in the plain text file section providing navigationParams and type. Once the steps have completed, return.
    "multipart/x-mixed-replace"
    Follow the steps given in the multipart/x-mixed-replace section providing navigationParams. Once the steps have completed, return.
    A supported image, video, or audio type
    Follow the steps given in the media section providing navigationParams and type. Once the steps have completed, return.
    A type that will use an external application to render the content in browsingContext
    Follow the steps given in the plugin section providing navigationParams and type. Once the steps have completed, return.

    An explicitly supported XML MIME type is an XML MIME type for which the user agent is configured to use an external application to render the content (either a plugin rendering directly in browsingContext, or a separate application), or one for which the user agent has dedicated processing rules (e.g., a web browser with a built-in Atom feed viewer would be said to explicitly support the application/atom+xml MIME type), or one for which the user agent has a dedicated handler.

    An explicitly supported JSON MIME type is a JSON MIME type for which the user agent is configured to use an external application to render the content (either a plugin rendering directly in browsingContext, or a separate application), or one for which the user agent has dedicated processing rules, or one for which the user agent has a dedicated handler.

  10. Otherwise, the document's type is such that the resource will not affect browsingContext, e.g., because the resource is to be handed to an external application or because it is an unknown type that will be processed as a download. Process the resource appropriately.

To process a navigate URL scheme, given a URL url and browsing context browsingContext, run these steps:

  1. If url is to be handled using a mechanism that does not affect browsingContext, e.g., because url's scheme is handled externally, then proceed with that mechanism instead.

  2. Otherwise, url is to be handled by displaying some sort of inline content, e.g., an error message because the specified scheme is not one of the supported protocols, or an inline prompt to allow the user to select a registered handler for the given scheme. Display the inline content given browsingContext.

    In the case of a registered handler being used, navigate will be invoked with a new URL.

When a resource is handled by passing its URL or data to an external software package separate from the user agent (e.g. handing a mailto: URL to a mail client, or a Word document to a word processor), user agents should attempt to mitigate the risk that this is an attempt to exploit the target software, e.g. by prompting the user to confirm that the source browsing context's active document's origin is to be allowed to invoke the specified software. In particular, if the navigate algorithm was invoked when source browsing context's active window does not have transient activation, the user agent should not invoke the external software package without prior user confirmation.

For example, there could be a vulnerability in the target software's URL handler which a hostile page would attempt to exploit by tricking a user into clicking a link.

To execute a javascript: URL request, given a request request and two browsing contexts source and browsingContext, run these steps:

  1. Let response be a response whose status is 204.

  2. If both of the following are true:

    then:

    1. Let urlString be the result of running the URL serializer on request's url.

    2. Let encodedScriptSource be the result of removing the leading "javascript:" from urlString.

    3. Let scriptSource be the UTF-8 decoding of the percent-decoding of encodedScriptSource.

    4. Append browsingContext's active document's URL to request's URL list.

    5. Let settings be browsingContext's active document's relevant settings object.

    6. Let baseURL be settings's API base URL.

    7. Let script be the result of creating a classic script given scriptSource, settings, baseURL, and the default classic script fetch options.

    8. Let evaluationStatus be the result of running the classic script script.

    9. Let result be undefined if evaluationStatus is an abrupt completion or evaluationStatus.[[Value]] is empty, or evaluationStatus.[[Value]] otherwise.

    10. If Type(result) is String, then set response to a response whose header list consists of `Content-Type`/`text/html` and `Referrer-Policy`/settings's referrer policy, and whose body is result.

      The exact conversion between the string result and the bytes that comprise a response body is not yet specified, pending further investigation into user agent behavior. See issue #1129.

  3. Return response.

In addition to the specific issues linked above, javascript: URLs have a dedicated label on the issue tracker documenting various problems with their specification.


Some of the sections below, to which the above algorithm defers in certain cases, use the following steps to create and initialize a Document object, given a type type, content type contentType, and navigation params navigationParams:

  1. Let browsingContext be navigationParams's browsing context.

  2. If navigationParams's browsing context switch needed is true, then set browsingContext to the result of the obtain a browsing context to use for a navigation response algorithm, given browsingContext, navigationParams's final sandboxing flag set, and navigationParams's cross-origin opener policy.

  3. Let permissionsPolicy be the result of creating a permissions policy from a response given browsingContext, navigationParams's origin, and navigationParams's response. [PERMISSIONSPOLICY]

    The creating a permissions policy from a response algorithm makes use of the passed origin. If document.domain has been used for browsingContext's container document, then its origin cannot be same origin-domain with the passed origin, because these steps run before the document is created, so it cannot itself yet have used document.domain. Note that this means that Permissions Policy checks are less permissive compared to doing a same origin check instead.

    See below for some examples of this in action.

  4. Let creationURL be navigationParams's response's URL.

  5. If navigationParams's request is non-null, then set creationURL to navigationParams's request's current URL.

  6. If browsingContext's only entry in its session history is the initial about:blank Document that was added when that browsing context was created, and navigationParams's history handling is "replace", and that Document's origin is same origin-domain with navigationParams's origin, then do nothing.

  7. Otherwise:

    1. Let oiHeader be the result of getting a structured field value given `Origin-Isolation` and "item" from response's header list.

    2. Let requestsOI be true if oiHeader is not null and oiHeader[0] is the boolean true; otherwise false.

    3. If reservedEnvironment is a non-secure context, then set requestsOI to false.

    4. Let agent be the result of obtaining a similar-origin window agent given navigationParams's origin, browsingContext's group, and requestsOI.

    5. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:

      • For the global object, create a new Window object.

      • For the global this binding, use browsingContext's WindowProxy object.

    6. Let topLevelCreationURL be creationURL.

    7. Let topLevelOrigin be navigationParams's origin.

    8. If browsingContext is not a top-level browsing context, then:

      1. Let parentEnvironment be browsingContext's container's relevant settings object.

      2. Set topLevelCreationURL to parentEnvironment's top-level creation URL.

      3. Set topLevelOrigin to parentEnvironment's top-level origin.

    9. Set up a window environment settings object with realm execution context, navigationParams's reserved environment, topLevelCreationURL, and topLevelOrigin.

  8. Let document be a new Document, whose type is type, content type is contentType, origin is navigationParams's origin, permissions policy is permissionsPolicy, active sandboxing flag set is navigationParams's final sandboxing flag set, and cross-origin opener policy is navigationParams's cross-origin opener policy.

  9. Set document's URL to creationURL.

  10. Set document's referrer policy to the result of parsing the `Referrer-Policy` header of navigationParams's response. [REFERRERPOLICY]

  11. Set document's embedder policy to the result of obtaining an embedder policy from navigationParams's response.

  12. Initialize a Document's CSP list given document, navigationParams's response, and navigationParams's request. [CSP]

  13. If navigationParams's request is non-null, then:

    1. Set document's referrer to the empty string.

    2. Let referrer be navigationParams's request's referrer.

    3. If referrer is a URL record, then set document's referrer to the serialization of referrer.

      Per Fetch, referrer will be either a URL record or "no-referrer" at this point.

  14. If navigationParams's response has a `Refresh` header, then:

    1. Let value be the isomorphic decoding of the value of the header.

    2. Run the shared declarative refresh steps with document and value.

    We do not currently have a spec for how to handle multiple `Refresh` headers. This is tracked as issue #2900.

  15. Return document.

In this example, the child document is not allowed to use PaymentRequest, despite being same origin-domain at the time the child document tries to use it. At the time the child document is initialized, only the parent document has set document.domain, and the child document has not.

<!-- https://foo.example.com/a.html -->
<!doctype html>
<script>
document.domain = 'example.com';
</script>
<iframe src=b.html></iframe>
<!-- https://bar.example.com/b.html -->
<!doctype html>
<script>
document.domain = 'example.com'; // This happens after the document is initialized
new PaymentRequest(…); // Not allowed to use
</script>

In this example, the child document is allowed to use PaymentRequest, despite not being same origin-domain at the time the child document tries to use it. At the time the child document is initialized, none of the documents have set document.domain yet so same origin-domain falls back to a normal same origin check.

<!-- https://example.com/a.html -->
<!doctype html>
<iframe src=b.html></iframe>
<!-- The child document is now initialized, before the script below is run. -->
<script>
document.domain = 'example.com';
</script>
<!-- https://example.com/b.html -->
<!doctype html>
<script>
new PaymentRequest(…); // Allowed to use
</script>

Some of the sections below, to which the above algorithm defers in certain cases, require the user agent to update the session history with the new page, given some navigation params navigationParams. When a user agent is required to do this, it must queue a global task on the networking task source, given the relevant global object of the Document object of the current entry (not the new one), to run the following steps:

  1. Let newDocument be navigationParams's browsing context's active document.

  2. Unload the document of the current entry.

    If this instance of the navigation algorithm is canceled while this step is running the unload a document algorithm, then the unload a document algorithm must be allowed to run to completion, but this instance of the navigation algorithm must not run beyond this step. (In particular, for instance, the cancelation of this algorithm does not abort any event dispatch or script execution occurring as part of unloading the document or its descendants.)

  3. If navigationParams's history handling is "reload" or "entry update"
    1. Replace the document of the current entry, and any other entries that reference the same document as that entry, with newDocument.

    2. Traverse the history to the current entry.

    If the navigation was initiated with a URL that equals newDocument's URL
    1. Replace the current entry with a new session history entry whose URL is newDocument's URL and document is newDocument.

    2. Traverse the history to the current entry.

    Otherwise
    1. Remove all the entries in the session history after the current entry. If the current entry is the last entry in the session history, then no entries are removed.

      This doesn't necessarily have to affect the user agent's user interface.

    2. Append a new session history entry to the session history, whose URL is newDocument's URL and document is newDocument.

    3. Traverse the history to the new entry, with historyHandling set to navigationParams's history handling.

  4. The navigation algorithm has now matured.

  5. Try to scroll to the fragment for newDocument.

To try to scroll to the fragment for a Document document, perform the following steps in parallel:

  1. Wait for an implementation-defined amount of time. (This is intended to allow the user agent to optimize the user experience in the face of performance concerns.)

  2. Queue a global task on the networking task source given document's relevant global object to run these steps:

    1. If document has no parser, or its parser has stopped parsing, or the user agent has reason to believe the user is no longer interested in scrolling to the fragment, then abort these steps.

    2. Scroll to the fragment given in document's URL. If this does not find an indicated part of the document, then try to scroll to the fragment for document.

7.10.2 HTML 文件的页面加载处理模型

给定 导航参数 加载 HTML 文档 时, 用户代理必须在 网络任务源 入队一个任务

  1. document 为给定 "html","text/html" 和 navigationParams 创建和初始化 Document 对象 的结果。

  2. 创建一个 HTML 解析器 并把它关联到 document。 获取过程中 网络任务源任务队列 里加入的所有 任务 都必须把获取到的字节填充到解析器的 输入字节流 里,让 HTML 解析器 对输入流执行适当的处理。

    tokenizer输入字节流 转化为能用的字符。 这个过程部分依赖于资源的 Content-Type 元数据 里的字符编码信息; 计算得到的类型不用作这一用途。

当没有字节可以处理时,用户代理必须在 网络任务源 里, 用新创建的 Document相关全局对象 入队一个全局任务,让解析器处理隐含的 EOF 字符,最终让 load 事件触发。

创建 Document 对象后,但在任何脚本执行前, 当然也在解析器 停止 之前,用户代理必须给定 navigationParams用新的页面更新会话历史

在 HTML 解析中,会发生 应用缓存选择

7.10.3 XML 文件的页面加载处理模型

给定 导航参数 navigationParams 和字符串 type, 要显示内联 XML 文件时,用户代理必须遵循 XMLNamespaces in XML, XML Media Types, DOM 和其他相关规范, 使用 "xml",typenavigationParams 创建和初始化 Document 对象。也必须创建一个对应的 XML 解析器[XML] [XMLNS] [RFC7303] [DOM]

编写这篇文档时,XML 规范社区其实还没有真正说明 XML 和 DOM 如何交互。

必须使用实际的 HTTP 头部和其他元数据(而不是本标准中算法修改后的),根据上述规范来确定字符编码。 一旦建立了字符编码,必须把 文档的字符编码 设置为这个编码。

如果根据上述 XML 解析的 文档元素 是一个 有着manifest 属性值为非空字符串的 html 元素, 那么当该元素 插入到文档时, 用户代理必须相对于那个元素的 节点文档 解析 那个属性的值,如果解析成功,必须在 结果 URL 记录 上应用 URL 序列化算法, 期间设置 排除 fragment 标志, 来获得 manifest URL,然后以 manifest URL 为清单 URL 执行 应用缓存选择算法,传入新创建的 Document。 否则如果该属性不存在,值为空字符串,或值解析失败,则在 文档元素 插入 到文档中时,用户代理必须不参考清单,并传入 Document 来执行 应用缓存选择算法

由于 manifest 属性的解析只发生 在解析 文档元素 时,任何在 文档元素 之前的处理指令中引用的 URL (例如<?xml-stylesheet?> PI)将会从网络获取,不会被缓存。

然后用代理必须用新创建的 DocumentnavigationParams更新会话历史为新页面。 用户代理必须在任何脚本执行之前更新会话历史,可能在文档完成解析之前(所以才能实现 增量渲染)。

解析过程中的错误消息(例如 XML 命名空间良构性错误)可以通过修改 Document 来内联地报告。

7.10.4 文本文件的页面加载处理模型

给定 导航参数 navigationParams 和字符串 type 加载纯文本文档时, 用户代理必须在 网络任务源入队一个任务

  1. document 为给定 "html",typenavigationParams 创建和初始化 Document 对象 的结果。

  2. 创建一个 HTML 解析器 并把它关联到 document。 假装 tokenizer 输出了标签名为"pre" 的开始标签,紧接着一个 U+000A LINE FEED (LF) 字符, 然后把 HTML 解析器 的 tokenizer 切换到 PLAINTEXT 状态。 获取过程中 网络任务源任务队列 里加入的所有 任务 都必须把获取到的字节填充到解析器的 输入字节流 里,让 HTML 解析器 对输入流执行适当的处理。

如何将纯文本文档的字节转换为真正字符的规则, 以及真正渲染文字给用户的规则,定义在该资源 计算得到的 MIME 类型 (即 type)的规范中。

文档的字符编码 必须设置为解码文档时用的字符编码。

在创建 Document 对象时,用户代理必须不参考清单,并传入新创建的 Document 来执行 应用缓存选择算法

当没有字节可以处理时,用户代理必须在 网络任务源 里, 用新创建的 Document相关全局对象 入队一个全局任务,让解析器处理隐含的 EOF 字符,最终让 load 事件触发。

在创建 Document 对象后,页面完全结束加载之前, 用户代理必须给定 navigationParams用新的页面更新会话历史

用户代理可能会添加内容到 Documenthead 元素, 例如链接一个样式表,提供一个脚本,或者给文档一个 title

特别是如果用户代理支持 RFC 3676 的 Format=Flowed 特性,就需要应用额外的样式来使文字正确折行,以及处理引用特性。 这可以通过使用 CSS 扩展来完成。

7.10.5 multipart/x-mixed-replace 资源的媒体的页面加载处理模型

浏览上下文 加载一个 multipart/x-mixed-replace 类型的资源时, 用户代理必须使用 multipart 类型的规则解析资源。 [RFC2046]

该算法传入了 导航参数,但还不清楚如何使用。

对资源中的每个 body part,用户代理必须执行 处理导航响应算法, 执行时要使用新的 body 部分和同样的 浏览上下文, 如果同一资源中的上一个 body 部分产生了 创建和初始化 Document 对象, 就把 历史处理 设为 "replace", 否则使用跟最初调用这部分的 导航 时同样的配置。

为使得算法处理这些 body part 的表现与处理独立的资源一致, 在碰到边界时用户代理必须表现地就像没有更多字节一样。

因此, load 事件(以及 unload 事件)会为每个载入的 body part 触发。

7.10.6 媒体的页面加载处理模型

给定 导航参数 navigationParams 和字符串 type, 加载图片、视频或音频资源时用户代理应该:

  1. document 为给定 "html",typenavigationParams 创建和初始化 Document 对象 的结果。

  2. 加一个 html 元素到 document

  3. 加一个 head 元素到 html 元素。

  4. 加一个 body 元素到 html 元素。

  5. 为媒体加一个 host element(见下文)到 body 元素。

  6. host element 元素的适当属性(见下文)设为图片、视频或音频资源的地址。

要为媒体创建的 host element 元素由下表中每行的第二个单元格给出, 同行的第一个单元格是媒体的描述。 要设置的属性是同行的第三个单元格。

媒体类型 媒体元素 适当的属性
Image img src
Video video src
Audio audio src

然后,用户代理必须表现地像已经 停止解析 一样。

在创建 Document 对象时,用户代理必须不参考清单,并传入新创建的 Document 来执行 应用缓存选择算法

在创建 Document 对象后,页面完全结束加载之前, 用户代理必须用 navigationParams 更新会话历史到新页面

用户代理可能会添加内容到 Documenthead 元素, 或者添加属性到 host element 元素,例如链接一个样式表, 提供一个脚本,给文档一个 title,或者让媒体 自动播放

7.10.7 使用插件的内容的页面加载处理模型

给定 导航参数 navigationParams 和字符串 type, 加载一个需要渲染外部资源的资源时用户代理应该:

  1. document 为给定 "html",typenavigationParams 创建和初始化 Document 对象 的结果。

  2. document 标记为 插件文档

  3. 加一个 html 元素到 document

  4. 加一个 head 元素到 html 元素。

  5. 加一个 body 元素到 html 元素。

  6. 加一个 embed 元素到 body 元素。

  7. 设置 embed 元素的 src 属性为资源地址。

插件文档 这个术语用于 Content Security Policy 作为确保 iframe 不能被用于逃脱 plugin-types 指令机制的一部分。 [CSP]

然后,用户代理必须表现地像已经 停止解析 一样。

在创建 Document 对象时,用户代理必须不参考清单,并传入新创建的 Document 来执行 应用缓存选择算法

在创建 Document 对象后,页面完全结束加载之前, 用户代理必须给定 navigationParams用新的页面更新会话历史

用户代理可能会添加内容到 Documenthead 元素, 或者添加属性到 embed 元素,例如链接一个样式表或者给文档一个 title

如果 Document激活沙盒标识沙盒插件浏览上下文标识 处于已设置状态, 如果相关 插件 不够 安全 的话, 合成的 embed 元素将会 渲染内容失败

7.10.8 没有 DOM 的内联内容的页面加载处理模型

给定 浏览上下文 browsingContext, 用户代理显示内联的用户代理页面时应该:

  1. navigationParams 为新的 导航参数,其 request 为 null,response 为 null,origin 为新的 不透明源final sandboxing flag set 为空集合,跨域 opener 策略 为 "unsafe-none",保留环境 为 null,浏览上下文browsingContext需要切换浏览上下文 为 false。

    下一步调用的算法无法处理空的 响应。可能我们需要构造一个。

  2. document 为给定 "html","text/html" 和 navigationParams 创建和初始化 Document 对象 的结果。

  3. 或者把 document 关联到不使用正常 Document 渲染规则的自定义的渲染, 或者把 document 改成用户代理想要渲染的内容。

一旦页面已经建立,用户代理必须表现地像已经 停止解析 一样。

在创建 Document 对象时,用户代理必须不参考清单,并传入新创建的 Document 来执行 应用缓存选择算法

在创建 Document 对象后,页面结束完全建立之前, 用户代理必须给定 navigationParams用新的页面更新会话历史

7.10.9 Navigating to a fragment

To navigate to a fragment given a browsing context browsingContext, a URL url, and a history handling behavior historyHandling:

  1. If historyHandling is not "replace", then remove all the entries in browsingContext's session history after the current entry. (If the current entry is the last entry in the session history, then no entries are removed.)

    This doesn't necessarily have to affect the user agent's user interface.

  2. Remove any tasks queued by the history traversal task source that are associated with any Document objects in browsingContext's top-level browsing context's document family.

  3. Append a new session history entry to the session history whose URL is url, document is the current entry's document, and scroll restoration mode is the current entry's scroll restoration mode.

  4. Traverse the history to the new entry, with historyHandling set to historyHandling and with nonBlockingEvents set to true. This will scroll to the fragment given in what is now the document's URL.

If the scrolling fails because the relevant ID has not yet been parsed, then the original navigation algorithm will take care of the scrolling instead, as the last few steps of its update the session history with the new page algorithm.


When the user agent is required to scroll to the fragment and the indicated part of the document, if any, is being rendered, the user agent must either change the scrolling position of the document using the following algorithm, or perform some other action such that the indicated part of the document is brought to the user's attention. If there is no indicated part, or if the indicated part is not being rendered, then the user agent must do nothing. The aforementioned algorithm is as follows:

  1. If there is no indicated part of the document, set the Document's target element to null.

  2. If the indicated part of the document is the top of the document, then:

    1. Set the Document's target element to null.

    2. Scroll to the beginning of the document for the Document. [CSSOMVIEW]

  3. Otherwise:

    1. Let target be element that is the indicated part of the document.

    2. Set the Document's target element to target.

    3. Scroll target into view, with behavior set to "auto", block set to "start", and inline set to "nearest". [CSSOMVIEW]

    4. Run the focusing steps for target, with the Document's viewport as the fallback target.

    5. Move the sequential focus navigation starting point to target.

The indicated part of the document is the one that the fragment, if any, identifies. The semantics of the fragment in terms of mapping it to a node is defined by the specification that defines the MIME type used by the Document (for example, the processing of fragments for XML MIME types is the responsibility of RFC7303). [RFC7303]

There is also a target element for each Document, which is used in defining the :target pseudo-class and is updated by the above algorithm. It is initially null.

For HTML documents (and HTML MIME types), the following processing model must be followed to determine what the indicated part of the document is.

  1. Let fragment be the document's URL's fragment.

  2. If fragment is the empty string, then the indicated part of the document is the top of the document; return.

  3. If find a potential indicated element with fragment returns non-null, then the return value is the indicated part of the document; return.

  4. Let fragmentBytes be the result of percent-decoding fragment.

  5. Let decodedFragment be the result of running UTF-8 decode without BOM on fragmentBytes.

  6. If find a potential indicated element with decodedFragment returns non-null, then the return value is the indicated part of the document; return.

  7. If decodedFragment is an ASCII case-insensitive match for the string top, then the indicated part of the document is the top of the document; return.

  8. There is no indicated part of the document.

To find a potential indicated element given a string fragment, run these steps:

  1. If there is an element in the document tree that has an ID equal to fragment, then return the first such element in tree order.

  2. If there is an a element in the document tree that has a name attribute whose value is equal to fragment, then return the first such element in tree order.

  3. Return null.

7.10.10 History traversal

To traverse the history to a session history entry entry, with an optional history handling behavior historyHandling (default "default"), an optional boolean nonBlockingEvents (default false), and an optional boolean explicitHistoryNavigation (default false):

This algorithm is not just invoked when explicitly going back or forwards in the session history — it is also invoked in other situations, for example when navigating a browsing context, as part of updating the session history with the new page.

  1. If entry's document is null, then:

    1. Let request be a new request whose url is entry's URL.

    2. If explicitHistoryNavigation is true, then set request's history-navigation flag.

    3. Assert: historyHandling is not "replace".

    4. Navigate the browsing context to request with historyHandling set to "entry update". The navigation must be done using the same source browsing context as was used the first time entry was created.

      The "navigate" algorithm reinvokes this "traverse" algorithm to complete the traversal, at which point entry's document is non-null.

      If the resource was obtained using a non-idempotent action, for example a POST form submission, or if the resource is no longer available, for example because the computer is now offline and the page wasn't cached, navigating to it again might not be possible. In this case, the navigation will result in a different page than previously; for example, it might be an error message explaining the problem or offering to resubmit the form.

    5. Return.

  2. If the current entry's title is null, then set its title to the value returned by the document.title IDL attribute.

  3. Save persisted state to the current entry.

  4. Let newDocument be entry's document.

  5. If newDocument is different than the current entry's document, then:

    1. Remove any tasks queued by the history traversal task source that are associated with any Document objects in the top-level browsing context's document family.

    2. If newDocument's origin is not same origin with the current entry's document's origin, then:

      1. Let entriesToUpdate be all entries in the session history whose document's origin is same origin as the active document and that are contiguous with the current entry.

      2. For each entryToUpdate of entriesToUpdate, set entryToUpdate's browsing context name to the current browsing context name.

      3. If the browsing context is a top-level browsing context, but not an auxiliary browsing context, then set the browsing context's name to the empty string.

    3. Set the active document of the browsing context to newDocument.

    4. If entry's browsing context name is not null, then:

      1. Set the browsing context's name to entry's browsing context name.

      2. Let entriesToUpdate be all entries in the session history whose document's origin is same origin as the new active document and that are contiguous with entry.

      3. For each entryToUpdate of entriesToUpdate, set entryToUpdate's browsing context name to null.

    5. If newDocument has any form controls whose autofill field name is "off", invoke the reset algorithm of each of those elements.

    6. If newDocument's current document readiness "complete", then queue a global task on the DOM manipulation task source given newDocument's relevant global object to run the following steps:

      1. If newDocument's page showing flag is true, then abort these steps.

      2. Set newDocument's page showing flag to true.

      3. Run any session history document visibility change steps for newDocument that are defined by other applicable specifications.

        This is specifically intended for use by Page Visibility. [PAGEVIS]

      4. Fire an event named pageshow at newDocument's relevant global object, using PageTransitionEvent, with the persisted attribute initialized to true, and legacy target override flag set.

  6. Set newDocument's URL to entry's URL.

  7. Let hashChanged be false, and let oldURL and newURL be null.

  8. If entry's URL's fragment is not identical to the current entry's URL's fragment, and entry's document equals the current entry's document, then set hashChanged to true, set oldURL to the current entry's URL, and set newURL to entry's URL.

  9. If historyHandling is "replace", then remove the entry immediately before entry in the session history.

  10. If entry's persisted user state is null, and its URL's fragment is non-null, then scroll to the fragment.

  11. Set the current entry to entry.

  12. Let targetRealm be the current Realm Record.

  13. Let state be null.

  14. If entry's serialized state is not null, then set state to StructuredDeserialize(entry's serialized state, targetRealm). If this throws an exception, catch it and ignore the exception.

  15. Set newDocument's History object's state to state.

  16. Let stateChanged be true if newDocument has a latest entry, and that entry is not entry; otherwise let it be false.

  17. Set newDocument's latest entry to entry.

  18. If nonBlockingEvents is false, then run the following steps immediately. Otherwise, queue a global task on the DOM manipulation task source given newDocument's relevant global object to run the following steps instead.

    1. If stateChanged is true, then fire an event named popstate at newDocument's relevant global object, using PopStateEvent, with the state attribute initialized to state.

    2. Restore persisted state from entry.

    3. If hashChanged is true, then fire an event named hashchange at the browsing context's active window, using HashChangeEvent, with the oldURL attribute initialized to oldURL and the newURL attribute initialized to newURL.

7.10.10.1 Persisted history entry state

To save persisted state to a session history entry entry:

  1. Set the scroll position data of entry to contain the scroll positions for all of entry's document's restorable scrollable regions.

  2. Optionally, update entry's persisted user state to reflect any state that the user agent wishes to persist, such as the values of form fields.

To restore persisted state from a session history entry entry:

  1. If entry's scroll restoration mode is "auto", then the user agent may use entry's scroll position data to restore the scroll positions of entry's document's restorable scrollable regions.

    The user agent not restoring scroll positions does not imply that scroll positions will be left at any particular value (e.g., (0,0)). The actual scroll position depends on the navigation type and the user agent's particular caching strategy. So web applications cannot assume any particular scroll position but rather are urged to set it to what they want it to be.

  2. Optionally, update other aspects of entry's document and its rendering, for instance values of form fields, that the user agent had previously recorded in entry's persisted user state.

    This can even include updating the dir attribute of textarea elements or input elements whose type attribute is in either the Text state or the Search state, if the persisted state includes the directionality of user input in such controls.


The restorable scrollable regions of a Document document are document's viewport, and all of document's scrollable regions excepting any child browsing contexts of document.

Child browsing context scroll restoration is handled by the history entry for those browsing contexts' Documents.

7.10.10.2 The PopStateEvent interface

PopStateEvent

Support in all current engines.

Firefox4+Safari6+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+
[Exposed=Window]
interface PopStateEvent : Event {
  constructor(DOMString type, optional PopStateEventInit eventInitDict = {});

  readonly attribute any state;
};

dictionary PopStateEventInit : EventInit {
  any state = null;
};
event . state

Returns a copy of the information that was provided to pushState() or replaceState().

The state attribute must return the value it was initialized to. It represents the context information for the event, or null, if the state represented is the initial state of the Document.

7.10.10.3 The HashChangeEvent interface

HashChangeEvent

Support in all current engines.

Firefox3.6+Safari5+Chrome8+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
[Exposed=Window]
interface HashChangeEvent : Event {
  constructor(DOMString type, optional HashChangeEventInit eventInitDict = {});

  readonly attribute USVString oldURL;
  readonly attribute USVString newURL;
};

dictionary HashChangeEventInit : EventInit {
  USVString oldURL = "";
  USVString newURL = "";
};
event . oldURL

HashChangeEvent/oldURL

Support in all current engines.

Firefox6+Safari5.1+Chrome8+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android6+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

Returns the URL of the session history entry that was previously current.

event . newURL

HashChangeEvent/newURL

Support in all current engines.

Firefox6+Safari5.1+Chrome8+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android6+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

Returns the URL of the session history entry that is now current.

The oldURL attribute must return the value it was initialized to. It represents context information for the event, specifically the URL of the session history entry that was traversed from.

The newURL attribute must return the value it was initialized to. It represents context information for the event, specifically the URL of the session history entry that was traversed to.

7.10.10.4 The PageTransitionEvent interface

PageTransitionEvent

Support in all current engines.

Firefox1.5+Safari5+Chrome4+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android4+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
[Exposed=Window]
interface PageTransitionEvent : Event {
  constructor(DOMString type, optional PageTransitionEventInit eventInitDict = {});

  readonly attribute boolean persisted;
};

dictionary PageTransitionEventInit : EventInit {
  boolean persisted = false;
};
event . persisted

PageTransitionEvent/persisted

Support in all current engines.

Firefox11+Safari5+Chrome4+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android14+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+

For the pageshow event, returns false if the page is newly being loaded (and the load event will fire). Otherwise, returns true.

For the pagehide event, returns false if the page is going away for the last time. Otherwise, returns true, meaning that (if nothing conspires to make the page unsalvageable) the page might be reused if the user navigates back to this page.

Things that can cause the page to be unsalvageable include:

The persisted attribute must return the value it was initialized to. It represents the context information for the event.

7.10.11 Loading documents

A Document has a completely loaded time (a time or null), which is initially null.

A Document is considered completely loaded if its completely loaded time is non-null.

To completely finish loading a Document document:

  1. Assert: document's browsing context is non-null.

  2. Set document's completely loaded time to the current time.

  3. Let container be document's browsing context's container.

  4. If container is an iframe element, then queue an element task on the DOM manipulation task source given container to run the iframe load event steps given container.

  5. Otherwise, if container is non-null, then queue an element task on the DOM manipulation task source given container to fire an event named load at container.

7.10.12 Unloading documents

A Document has a salvageable state, which must initially be true, and a page showing flag, which must initially be false. The page showing flag is used to ensure that scripts receive pageshow and pagehide events in a consistent manner (e.g. that they never receive two pagehide events in a row without an intervening pageshow, or vice versa).

Event loops have a termination nesting level counter, which must initially be 0.

To prompt to unload, given a Document object document and optionally a recursiveFlag, run these steps:

  1. Increase the event loop's termination nesting level by 1.

  2. Increase the document's ignore-opens-during-unload counter by 1.

  3. Let event be the result of creating an event using BeforeUnloadEvent.

  4. Initialize event's type attribute to beforeunload and its cancelable attribute true.

  5. Dispatch: Dispatch event at document's relevant global object.

  6. Decrease the event loop's termination nesting level by 1.

  7. If document's active sandboxing flag set does not have its sandboxed modals flag set, and the returnValue attribute of the event object is not the empty string, or if the event was canceled, then the user agent may ask the user to confirm that they wish to unload the document.

    The message shown to the user is not customizable, but instead determined by the user agent. In particular, the actual value of the returnValue attribute is ignored.

    The user agent is encouraged to avoid asking the user for confirmation if it judges that doing so would be annoying, deceptive, or pointless. A simple heuristic might be that if the user has not interacted with the document, the user agent would not ask for confirmation before unloading it.

    If the user agent asks the user for confirmation, it must pause while waiting for the user's response.

    If the user did not confirm the page navigation, then the user agent refused to allow the document to be unloaded.

  8. If the recursiveFlag is not set, then:

    1. Let descendants be the list of the descendant browsing contexts of document.

    2. For each browsingContext in descendants:

      1. Prompt to unload browsingContext's active document with the recursiveFlag set.

      2. If the user refused to allow the document to be unloaded, then the user implicitly also refused to allow document to be unloaded; break.

  9. Decrease the document's ignore-opens-during-unload counter by 1.

To unload a Document document, optionally given a recursiveFlag:

  1. Increase the event loop's termination nesting level by one.

  2. Increase document's ignore-opens-during-unload counter by one.

  3. If document's page showing flag is false, then jump to the step labeled unload event below (i.e. skip firing the pagehide event and don't rerun the unloading document visibility change steps).

  4. Set document's page showing flag to false.

  5. If the user agent does not intend to keep document alive in a session history entry (such that it can be reused later on history traversal), set document's salvageable state to false.

  6. Fire an event named pagehide at document's relevant global object, using PageTransitionEvent, with the persisted attribute initialized to true if document's salvageable state is true, and false otherwise, and legacy target override flag set.

  7. Run any unloading document visibility change steps for document that are defined by other applicable specifications.

    This is specifically intended for use by Page Visibility. [PAGEVIS]

  8. Unload event: If document's salvageable state is false, then fire an event named unload at document's relevant global object, with legacy target override flag set.

  9. Decrease the event loop's termination nesting level by one.

  10. Run any unloading document cleanup steps for document that are defined by this specification and other applicable specifications.

  11. If the recursiveFlag is not set, then:

    1. Let descendants be the list of the descendant browsing contexts of document.

    2. For each browsingContext in descendants:

      1. Unload the active document of browsingContext with the recursiveFlag set.

      2. If the salvageable state of the active document of browsingContext is false, then set the salvageable state of document to false also.

    3. If document's salvageable state is false, then discarddocument.

  12. Decrease document's ignore-opens-during-unload counter by one.

This specification defines the following unloading document cleanup steps. Other specifications can define more. Given a Document document:

  1. Let window be document's relevant global object.

  2. For each WebSocket object webSocket whose relevant global object is window, make disappear webSocket.

    If this affected any WebSocket objects, then set document's salvageable state to false.

  3. If document's salvageable state is false, then:

    1. For each EventSource object eventSource whose relevant global object is equal to window, forcibly close eventSource.

    2. Empty window's list of active timers.

7.10.12.1 The BeforeUnloadEvent interface

BeforeUnloadEvent

Support in all current engines.

Firefox1.5+Safari7+Chrome30+
Opera17+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS7+Chrome Android30+WebView Android37+Samsung Internet3.0+Opera Android18+
[Exposed=Window]
interface BeforeUnloadEvent : Event {
  attribute DOMString returnValue;
};

There are no BeforeUnloadEvent-specific initialization methods.

The BeforeUnloadEvent interface is a legacy interface which allows prompting to unload to be controlled not only by canceling the event, but by setting the returnValue attribute to a value besides the empty string. Authors should use the preventDefault() method, or other means of canceling events, instead of using returnValue.

The returnValue attribute controls the process of prompting to unload. When the event is created, the attribute must be set to the empty string. On getting, it must return the last value it was set to. On setting, the attribute must be set to the new value.

This attribute is a DOMString only for historical reasons. Any value besides the empty string will be treated as a request to ask the user for confirmation.

7.10.13 Aborting a document load

To abort a Document document:

  1. Abort the active documents of every child browsing context. If this results in any of those Document objects having their salvageable state set to false, then set document's salvageable state to false also.

  2. Cancel any instances of the fetch algorithm in the context of document, discarding any tasks queued for them, and discarding any further data received from the network for them. If this resulted in any instances of the fetch algorithm being canceled or any queued tasks or any network data getting discarded, then set document's salvageable state to false.

  3. If document has an active parser, then:

    1. Set document's active parser was aborted to true.

    2. Abort that parser.

    3. Set document's salvageable state to false.

User agents may allow users to explicitly invoke the abort a document algorithm for a Document. If the user does so, then, if that Document is an active document, the user agent should queue a task to fire an event named abort at that Document object's relevant global object before invoking the abort algorithm.

To stop document loading given a Document object document, run these steps:

  1. If document is not an active document, then return.

  2. Let browsingContext be document's browsing context.

  3. If there is an existing attempt to navigate browsingContext and that attempt is not currently running the unload a document algorithm, then cancel that navigation.

  4. Abort document.

7.10.14 The `X-Frame-Options` header

The `X-Frame-Options` HTTP response header is a legacy way of controlling whether and how a Document may be loaded inside of a child browsing context. It is obsoleted by the frame-ancestors CSP directive, which provides more granular control over the same situations. It was originally defined in HTTP Header Field X-Frame-Options, but the definition and processing model here supersedes that document. [CSP] [RFC7034]

In particular, HTTP Header Field X-Frame-Options specified an `ALLOW-FROM` variant of the header, but that is not to be implemented.

Per the below processing model, if both a CSP frame-ancestors directive and an `X-Frame-Options` header are used in the same response, then `X-Frame-Options` is ignored.

For web developers and conformance checkers, its value ABNF is:

X-Frame-Options = "DENY" / "SAMEORIGIN"

To check a navigation response's adherence to `X-Frame-Options`, given a response response, a browsing context browsingContext, and an origin destinationOrigin:

  1. If browsingContext is not a child browsing context, then return true.

  2. For each policy of response's CSP list:

    1. If policy's disposition is not "enforce", then continue.

    2. If policy's directive set contains a frame-ancestors directive, then return true.

  3. Let rawXFrameOptions be the result of getting, decoding, and splitting `X-Frame-Options` from response's header list.

  4. Let xFrameOptions be a new set.

  5. For each value of rawXFrameOptions, append value, converted to ASCII lowercase, to xFrameOptions.

  6. If xFrameOptions's size is greater than 1, and xFrameOptions contains any of "deny", "allowall", or "sameorigin", then return false.

    The intention here is to block any attempts at applying `X-Frame-Options` which were trying to do something valid, but appear confused.

    This is the only impact of the legacy `ALLOWALL` value on the processing model.

  7. If xFrameOptions's size is greater than 1, then return true.

    This means it contains multiple invalid values, which we treat the same way as if the header was omitted entirely.

  8. If xFrameOptions[0] is "deny", then return false.

  9. If xFrameOptions[0] is "sameorigin", then:

    1. Let containerDocument be browsingContext's container document.

    2. While containerDocument is not null:

      1. If containerDocument's origin is not same origin with destinationOrigin, then return false.

      2. Let containerBC be containerDocument's browsing context.

      3. Set containerDocument to containerBC's container document, if containerBC is non-null; otherwise, null.

  10. Return true.

    If we've reached this point then we have a lone invalid value (which could potentially be one the legacy `ALLOWALL` or `ALLOW-FROM` forms). These are treated as if the header were omitted entirely.


The following table illustrates the processing of various values for the header, including non-conformant ones:

`X-Frame-Options`ValidResult
`DENY`embedding disallowed
`SAMEORIGIN`same-origin embedding allowed
`INVALID`embedding allowed
`ALLOWALL`embedding allowed
`ALLOW-FROM=https://example.com/`embedding allowed (from anywhere)

The following table illustrates how various non-conformant cases involving multiple values are processed:

`X-Frame-Options`Result
`SAMEORIGIN, SAMEORIGIN`same-origin embedding allowed
`SAMEORIGIN, DENY`embedding disallowed
`SAMEORIGIN,`embedding disallowed
`SAMEORIGIN, ALLOWALL`embedding disallowed
`SAMEORIGIN, INVALID`embedding disallowed
`ALLOWALL, INVALID`embedding disallowed
`ALLOWALL,`embedding disallowed
`INVALID, INVALID`embedding allowed

The same results are obtained whether the values are delivered in a single header whose value is comma-delimited, or in multiple headers.

7.11 Offline web applications

This feature is in the process of being removed from the web platform. (This is a long process that takes many years.) Using any of the offline web application features at this time is highly discouraged. Use service workers instead. [SW]

7.11.1 概述

This section is non-normative.

为了使用户在网络连接不可用时,仍然继续与 Web 应用和文档交互 — 例如, 因为他们在其 ISP 覆盖外旅行时 — 作者可以提供一个清单,列出 Web 应用离线工作需要的文件列表, 用户的浏览器保存一份文件拷贝来供离线使用。

举个例子,考虑一个简单的时钟应用包括一个,HTML 页面 "clock1.html", 一个 CSS 样式表 "clock.css",和一个 JavaScript 脚本 "clock.js"。

在添加清单之前,这些文件可能看起来像这样:

<!-- clock1.html -->
<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Clock</title>
  <script src="clock.js"></script>
  <link rel="stylesheet" href="clock.css">
 </head>
 <body>
  <p>The time is: <output id="clock"></output></p>
 </body>
</html>
/* clock.css */
output { font: 2em sans-serif; }
/* clock.js */
setInterval(function () {
    document.getElementById('clock').value = new Date();
}, 1000);

如果用户在离线时尝试打开 "clock1.html" 页面, 用户代理(除非恰好它仍然在本地缓存里)将会失败。

作者可以提供一个这3个文件的清单,比如叫 "clock.appcache":

CACHE MANIFEST
clock2.html
clock.css
clock.js

稍微改动一下 HTML 文件,把清单(作为 text/cache-manifest 服务) 链接到应用:

<!-- clock2.html -->
<!DOCTYPE HTML>
<html lang="en" manifest="clock.appcache">
 <head>
  <meta charset="utf-8">
  <title>Clock</title>
  <script src="clock.js"></script>
  <link rel="stylesheet" href="clock.css">
 </head>
 <body>
  <p>The time is: <output id="clock"></output></p>
 </body>
</html>

现在,如果用户进入这个页面,浏览器会缓存这些文件并让它们在用户离线时仍然可用。

鼓励作者在清单文件中包含一个主页面,但实践中引用清单文件的页面会被自动缓存, 即使没有显式地提到它。

除了 "no-store" 指令之外,HTTP 缓存头和 TLS(加密的,使用 https:) 上的页面缓存限制都会被清单覆盖。 因此从应用缓存来的页面在用户代理更新它之前不会过期,即使是 TLS 下的应用也可以离线工作。

在线查看该示例

7.11.1.1 支持遗留应用的离线缓存

This section is non-normative.

应用缓存特性的最佳使用状态是应用逻辑与应用和用户数据分离,逻辑(HTML、脚本、样式、图片等) 列在清单里存储到应用缓存,应用的静态 HTML 页面数目是有限的。 应用和用户数据存储在 Web Storage 或客户端 Indexed Database 中,通过 Web Socket、XMLHttpRequest、服务器发送的事件、或其他类似机制动态更新。

利用这一模型可以为用户提供快速的体验:应用瞬间加载(并显示旧数据),网络允许时获取最新数据。

然而历史应用的设计倾向于把用户数据和逻辑混合在 HTML 中,每个操作会从服务器加载整个 HTML 页面。

例如,考虑一个新闻应用。不使用应用缓存特性时,这样的应用典型的架构是, 用户获取主页面,服务器返回一个动态产生的页面,其中混合了当前的头条和用户界面逻辑。

但是为应用缓存特性设计的新闻应用会让主页面只包含逻辑, 在主页面中(比如使用XMLHttpRequest)独立地从服务器获取数据。

混合内容模型不适用于应用程序缓存功能:由于内容被缓存,因此用户总是会看到上次更新缓存时的旧数据。

虽然没办法让遗留的模型与分离模型一样快,但至少 可以 通过 prefer-online 应用缓存模式 让它支持离线使用。 为此,在 拥有缓存清单 中列出 HTML 页面中你希望离线使用的所有静态资源, 在 HTML 文件中通过 manifest 属性来选择清单文件,然后添加下列行到清单底部:

SETTINGS:
prefer-online
NETWORK:
*

这会使 应用缓存 在用户离线时只用于 主入口, 使得应用缓存可以用作原子性的 HTTP 缓存(只对清单中列出的资源有效), 同时其余没列出的资源当用户在线时可正常访问。

7.11.1.2 Events summary

This section is non-normative.

When the user visits a page that declares a manifest, the browser will try to update the cache. It does this by fetching a copy of the manifest and, if the manifest has changed since the user agent last saw it, redownloading all the resources it mentions and caching them anew.

As this is going on, a number of events get fired on the ApplicationCache object to keep the script updated as to the state of the cache update, so that the user can be notified appropriately. The events are as follows:

Event name Interface Fired when... Next events
checking Event The user agent is checking for an update, or attempting to download the manifest for the first time. This is always the first event in the sequence. noupdate, downloading, obsolete, error
noupdate Event The manifest hadn't changed. Last event in sequence.
downloading Event The user agent has found an update and is fetching it, or is downloading the resources listed by the manifest for the first time. progress, error, cached, updateready
progress ProgressEvent The user agent is downloading resources listed by the manifest. The event object's total attribute returns the total number of files to be downloaded. The event object's loaded attribute returns the number of files processed so far. progress, error, cached, updateready
cached Event The resources listed in the manifest have been downloaded, and the application is now cached. Last event in sequence.
updateready Event The resources listed in the manifest have been newly redownloaded, and the script can use swapCache() to switch to the new cache. Last event in sequence.
obsolete Event The manifest was found to have become a 404 or 410 page, so the application cache is being deleted. Last event in sequence.
error Event The manifest was a 404 or 410 page, so the attempt to cache the application has been aborted. Last event in sequence.
The manifest hadn't changed, but the page referencing the manifest failed to download properly.
A fatal error occurred while fetching the resources listed in the manifest.
The manifest changed while the update was being run. The user agent will try fetching the files again momentarily.

These events are cancelable; their default action is for the user agent to show download progress information. If the page shows its own update UI, canceling the events will prevent the user agent from showing redundant progress information.

7.11.2 Application caches

An application cache is a set of cached resources consisting of:

Each application cache has a completeness flag, which is either complete or incomplete.


An application cache group is a group of application caches, identified by the absolute URL of a resource manifest which is used to populate the caches in the group.

An application cache is newer than another if it was created after the other (in other words, application caches in an application cache group have a chronological order).

Only the newest application cache in an application cache group can have its completeness flag set to incomplete; the others are always all complete.

Each application cache group has an update status, which is one of the following: idle, checking, downloading.

A relevant application cache is an application cache that is the newest in its group to be complete.

Each application cache group has a list of pending primary entries. Each entry in this list consists of a resource and a corresponding Document object. It is used during the application cache download process to ensure that new primary entries are cached even if the application cache download process was already running for their application cache group when they were loaded.

An application cache group can be marked as obsolete, meaning that it must be ignored when looking at what application cache groups exist.


A cache host is a Document object.

Each cache host has an associated ApplicationCache object.

Each cache host initially is not associated with an application cache, but can become associated with one early during the page load process, when steps in the parser and in the navigation sections cause cache selection to occur.


Multiple application caches in different application cache groups can contain the same resource, e.g. if the manifests all reference that resource. If the user agent is to select an application cache from a list of relevant application caches that contain a resource, the user agent must use the application cache that the user most likely wants to see the resource from, taking into account the following:


A URL matches a fallback namespace if there exists a relevant application cache whose manifest's URL has the same origin as the URL in question, and that has a fallback namespace that is a prefix match for the URL being examined. If multiple fallback namespaces match the same URL, the longest one is the one that matches. A URL looking for a fallback namespace can match more than one application cache at a time, but only matches one namespace in each cache.

If a manifest https://example.com/app1/manifest declares that https://example.com/resources/images is a fallback namespace, and the user navigates to https://example.com:80/resources/images/cat.png, then the user agent will decide that the application cache identified by https://example.com/app1/manifest contains a namespace with a match for that URL.

7.11.3 缓存清单语法

7.11.3.1 一些示例清单

This section is non-normative.

这个示例清单要求缓存两个图片和一个样式表,并把一个 CGI 脚本加入安全列表。

CACHE MANIFEST
# the above line is required

# this is a comment
# there can be as many of these anywhere in the file
# they are all ignored
  # comments can have spaces before them
  # but must be alone on the line

# blank lines are ignored too

# these are files that need to be cached they can either be listed
# first, or a "CACHE:" header could be put before them, as is done
# lower down.
images/sound-icon.png
images/background.png
# note that each file has to be put on its own line

# here is a file for the online safelist -- it isn't cached, and
# references to this file will bypass the cache, always hitting the
# network (or trying to, if the user is offline).
NETWORK:
comm.cgi

# here is another set of files to cache, this time just the CSS file.
CACHE:
style/default.css

下列写法是等效的:

CACHE MANIFEST
NETWORK:
comm.cgi
CACHE:
style/default.css
images/sound-icon.png
images/background.png

离线应用缓存清单可以使用绝对路径,甚至绝对 URL:

CACHE MANIFEST

/main/home
/main/app.js
/settings/home
/settings/app.js
https://img.example.com/logo.png
https://img.example.com/check.png
https://img.example.com/cross.png

以下清单定义了一个捕获所有错误的页面,用户离线时用于所有页面的显示。 还指定了在线安全列表通配标志open,意味着不会阻止对外站资源的访问。 (由于捕获所有错误的 fallback 命名空间,站内资源的访问也不会被阻止)

只要站点的所有页面都引用这个清单,它们被获取后就会缓存到本地, 后续访问同一页面时就会立即从缓存加载。 除非清单发生了变化,那些页面不会再从服务器获取。 当清单改变时,所有文件都会重新下载。

但是子资源(比如样式表、图片等)只会使用普通的 HTTP 缓存语义进行缓存。

CACHE MANIFEST
FALLBACK:
/ /offline.html
NETWORK:
*
7.11.3.2 Writing cache manifests

Manifests must be served using the text/cache-manifest MIME type. All resources served using the text/cache-manifest MIME type must follow the syntax of application cache manifests, as described in this section.

An application cache manifest is a text file, whose text is encoded using UTF-8. Data in application cache manifests is line-based. Newlines must be represented by U+000A LINE FEED (LF) characters, U+000D CARRIAGE RETURN (CR) characters, or U+000D CARRIAGE RETURN (CR) U+000A LINE FEED (LF) pairs. [ENCODING]

This is a willful violation of RFC 2046, which requires all text/* types to only allow CRLF line breaks. This requirement, however, is outdated; the use of CR, LF, and CRLF line breaks is commonly supported and indeed sometimes CRLF is not supported by text editors. [RFC2046]

The first line of an application cache manifest must consist of the string "CACHE", a single U+0020 SPACE character, the string "MANIFEST", and either a U+0020 SPACE character, a U+0009 CHARACTER TABULATION (tab) character, a U+000A LINE FEED (LF) character, or a U+000D CARRIAGE RETURN (CR) character. The first line may optionally be preceded by a U+FEFF BYTE ORDER MARK (BOM) character. If any other text is found on the first line, it is ignored.

Subsequent lines, if any, must all be one of the following:

A blank line

Blank lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters only.

A comment

Comment lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, followed by a single U+0023 NUMBER SIGN character (#), followed by zero or more characters other than U+000A LINE FEED (LF) and U+000D CARRIAGE RETURN (CR) characters.

Comments need to be on a line on their own. If they were to be included on a line with a URL, the "#" would be mistaken for part of a fragment.

A section header

Section headers change the current section. There are four possible section headers:

CACHE:
Switches to the explicit section.
FALLBACK:
Switches to the fallback section.
NETWORK:
Switches to the online safelist section.
SETTINGS:
Switches to the settings section.

Section header lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, followed by one of the names above (including the U+003A COLON character (:)) followed by zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters.

Ironically, by default, the current section is the explicit section.

Data for the current section

The format that data lines must take depends on the current section.

When the current section is the explicit section, data lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, a valid URL string identifying a resource other than the manifest itself, and then zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters.

When the current section is the fallback section, data lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, a valid URL string identifying a resource other than the manifest itself, one or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, another valid URL string identifying a resource other than the manifest itself, and then zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters.

When the current section is the online safelist section, data lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, either a single U+002A ASTERISK character (*) or a valid URL string identifying a resource other than the manifest itself, and then zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters.

When the current section is the settings section, data lines must consist of zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters, a setting, and then zero or more U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters.

Currently only one setting is defined:

The cache mode setting
This consists of the string "prefer-online". It sets the cache mode to prefer-online. (The cache mode defaults to fast.)

Within a settings section, each setting must occur no more than once.

Manifests may contain sections more than once. Sections may be empty.

URLs that are to be fallback pages associated with fallback namespaces, and those namespaces themselves, must be given in fallback sections, with the namespace being the first URL of the data line, and the corresponding fallback page being the second URL. All the other pages to be cached must be listed in explicit sections.

Fallback namespaces and fallback entries must have the same origin as the manifest itself. Fallback namespaces must also be in the same path as the manifest's URL.

A fallback namespace must not be listed more than once.

Namespaces that the user agent is to put into the online safelist must all be specified in online safelist sections. (This is needed for any URL that the page is intending to use to communicate back to the server.) To specify that all URLs are automatically safelisted in this way, a U+002A ASTERISK character (*) may be specified as one of the URLs.

Authors should not include namespaces in the online safelist for which another namespace in the online safelist is a prefix match.

Relative URLs must be given relative to the manifest's own URL. All URLs in the manifest must have the same scheme as the manifest itself (either explicitly or implicitly, through the use of relative URLs). [URL]

URLs in manifests must not have fragments (i.e. the U+0023 NUMBER SIGN character isn't allowed in URLs in manifests).

Fallback namespaces and namespaces in the online safelist are matched by prefix match.

7.11.3.3 Parsing cache manifests

When a user agent is to parse a manifest, it means that the user agent must run the following steps:

  1. UTF-8 decode the byte stream corresponding with the manifest to be parsed.

    The UTF-8 decode algorithm strips a leading BOM, if any.

  2. Let base URL be the absolute URL representing the manifest.

  3. Apply the URL parser to base URL, and let manifest path be the path component thus obtained.

  4. Remove all the characters in manifest path after the last U+002F SOLIDUS character (/), if any. (The first character and the last character in manifest path after this step will both be slashes, the URL path separator character.)

  5. Apply the URL parser steps to the base URL, so that the components from its URL record can be used by the subsequent steps of this algorithm.

  6. Let explicit URLs be an initially empty list of absolute URLs for explicit entries.

  7. Let fallback URLs be an initially empty mapping of fallback namespaces to absolute URLs for fallback entries.

  8. Let online safelist namespaces be an initially empty list of absolute URLs for an online safelist.

  9. Let online safelist wildcard flag be blocking.

  10. Let cache mode flag be fast.

  11. Let input be the decoded text of the manifest's byte stream.

  12. Let position be a pointer into input, initially pointing at the first character.

  13. If the characters starting from position are "CACHE", followed by a U+0020 SPACE character, followed by "MANIFEST", then advance position to the next character after those. Otherwise, this isn't a cache manifest; return with a failure while checking for the magic signature.

  14. If the character at position is neither a U+0020 SPACE character, a U+0009 CHARACTER TABULATION (tab) character, U+000A LINE FEED (LF) character, nor a U+000D CARRIAGE RETURN (CR) character, then this isn't a cache manifest; return with a failure while checking for the magic signature.

  15. This is a cache manifest. The algorithm cannot fail beyond this point (though bogus lines can get ignored).

  16. Collect a sequence of code points that are not U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters from input given position, and ignore those characters. (Extra text on the first line, after the signature, is ignored.)

  17. Let mode be "explicit".

  18. Start of line: If position is past the end of input, then jump to the last step. Otherwise, collect a sequence of code points that are U+000A LINE FEED (LF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, or U+0009 CHARACTER TABULATION (tab) characters from input given position.

  19. Now, collect a sequence of code points that are not U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters from input given position, and let the result be line.

  20. Drop any trailing U+0020 SPACE and U+0009 CHARACTER TABULATION (tab) characters at the end of line.

  21. If line is the empty string, then jump back to the step labeled start of line.

  22. If the first character in line is a U+0023 NUMBER SIGN character (#), then jump back to the step labeled start of line.

  23. If line equals "CACHE:" (the word "CACHE" followed by a U+003A COLON character (:)), then set mode to "explicit" and jump back to the step labeled start of line.

  24. If line equals "FALLBACK:" (the word "FALLBACK" followed by a U+003A COLON character (:)), then set mode to "fallback" and jump back to the step labeled start of line.

  25. If line equals "NETWORK:" (the word "NETWORK" followed by a U+003A COLON character (:)), then set mode to "online safelist" and jump back to the step labeled start of line.

  26. If line equals "SETTINGS:" (the word "SETTINGS" followed by a U+003A COLON character (:)), then set mode to "settings" and jump back to the step labeled start of line.

  27. If line ends with a U+003A COLON character (:), then set mode to "unknown" and jump back to the step labeled start of line.

  28. This is either a data line or it is syntactically incorrect.

  29. Let position be a pointer into line, initially pointing at the start of the string.

  30. Let tokens be a list of strings, initially empty.

  31. While position doesn't point past the end of line:

    1. Let current token be an empty string.

    2. While position doesn't point past the end of line and the character at position is neither a U+0020 SPACE nor a U+0009 CHARACTER TABULATION (tab) character, add the character at position to current token and advance position to the next character in input.

    3. Add current token to the tokens list.

    4. While position doesn't point past the end of line and the character at position is either a U+0020 SPACE or a U+0009 CHARACTER TABULATION (tab) character, advance position to the next character in input.

  32. Process tokens as follows:

    If mode is "explicit"

    Let urlRecord be the result of parsing the first item in tokens with base URL; ignore the rest.

    If urlRecord is failure, then jump back to the step labeled start of line.

    If urlRecord has a different scheme component than base URL (the manifest's URL), then jump back to the step labeled start of line.

    Let new URL be the result of applying the URL serializer algorithm to urlRecord, with the exclude fragment flag set.

    Add new URL to the explicit URLs.

    If mode is "fallback"

    Let part one be the first token in tokens, and let part two be the second token in tokens.

    Let urlRecordOne be the result of parsing part one with base URL.

    Let urlRecordTwo be the result of parsing part two with base URL.

    If either urlRecordOne or urlRecordTwo are failure, then jump back to the step labeled start of line.

    If the origin of either urlRecordOne or urlRecordTwo is not same origin with the manifest's URL origin, then jump back to the step labeled start of line.

    Let part one path be the path component of urlRecordOne.

    If manifest path is not a prefix match for part one path, then jump back to the step labeled start of line.

    Let part one be the result of applying the URL serializer algorithm to urlRecordOne, with the exclude fragment flag set.

    Let part two be the result of applying the URL serializer algorithm to urlRecordTwo, with the exclude fragment flag set.

    If part one is already in the fallback URLs mapping as a fallback namespace, then jump back to the step labeled start of line.

    Otherwise, add part one to the fallback URLs mapping as a fallback namespace, mapped to part two as the fallback entry.

    If mode is "online safelist"

    If the first item in tokens is a U+002A ASTERISK character (*), then set online safelist wildcard flag to open and jump back to the step labeled start of line.

    Otherwise, let urlRecord be the result of parsing the first item in tokens with base URL.

    If urlRecord is failure, then jump back to the step labeled start of line.

    If urlRecord has a different scheme component than base URL (the manifest's URL), then jump back to the step labeled start of line.

    Let new URL be the result of applying the URL serializer algorithm to urlRecord, with the exclude fragment flag set.

    Add new URL to the online safelist namespaces.

    If mode is "settings"

    If tokens contains a single token, and that token is "prefer-online", then set cache mode flag to prefer-online and jump back to the step labeled start of line.

    Otherwise, the line is an unsupported setting: do nothing; the line is ignored.

    If mode is "unknown"

    Do nothing. The line is ignored.

  33. Jump back to the step labeled start of line. (That step jumps to the next, and last, step when the end of the file is reached.)

  34. Return the explicit URLs list, the fallback URLs mapping, the online safelist namespaces, the online safelist wildcard flag, and the cache mode flag.

The resource that declares the manifest (with the manifest attribute) will always get taken from the cache, whether it is listed in the cache or not, even if it is listed in an online safelist namespace.

If a resource is listed in the explicit section or as a fallback entry in the fallback section, the resource will always be taken from the cache, regardless of any other matching entries in the fallback namespaces or online safelist namespaces.

When a fallback namespace and an online safelist namespace overlap, the online safelist namespace has priority.

The online safelist wildcard flag is applied last, only for URLs that match neither the online safelist namespace nor the fallback namespace and that are not listed in the explicit section.

7.11.4 Downloading or updating an application cache

When the user agent is required (by other parts of this specification) to start the application cache download process for an absolute URL purported to identify a manifest, or for an application cache group, potentially given a particular cache host, and potentially given a primary resource, the user agent must run the steps below. These steps are always run in parallel with the event loop tasks.

Some of these steps have requirements that only apply if the user agent shows caching progress. Support for this is optional. Caching progress UI could consist of a progress bar or message panel in the user agent's interface, or an overlay, or something else. Certain events fired during the application cache download process allow the script to override the display of such an interface. (Such events are delayed until after the load event has fired.) The goal of this is to allow web applications to provide more seamless update mechanisms, hiding from the user the mechanics of the application cache mechanism. User agents may display user interfaces independent of this, but are encouraged to not show prominent update progress notifications for applications that cancel the relevant events.

The application cache download process steps are as follows:

  1. Optionally, wait until the permission to start the application cache download process has been obtained from the user and until the user agent is confident that the network is available. This could include doing nothing until the user explicitly opts-in to caching the site, or could involve prompting the user for permission. The algorithm might never get past this point. (This step is particularly intended to be used by user agents running on severely space-constrained devices or in highly privacy-sensitive environments).

  2. Atomically, so as to avoid race conditions, perform the following substeps:

    1. Pick the appropriate substeps:

      If these steps were invoked with an absolute URL purported to identify a manifest

      Let manifest URL be that absolute URL.

      If there is no application cache group identified by manifest URL, then create a new application cache group identified by manifest URL. Initially, it has no application caches. One will be created later in this algorithm.

      If these steps were invoked with an application cache group

      Let manifest URL be the absolute URL of the manifest used to identify the application cache group to be updated.

      If that application cache group is obsolete, then abort this instance of the application cache download process. This can happen if another instance of this algorithm found the manifest to be 404 or 410 while this algorithm was waiting in the first step above.

    2. Let cache group be the application cache group identified by manifest URL.

    3. If these steps were invoked with a primary resource, then add the resource, along with the resource's Document, to cache group's list of pending primary entries.

    4. If these steps were invoked with a cache host, and the status of cache group is checking or downloading, then queue a post-load task to run these steps:

      1. Let showProgress be the result of firing an event named checking at the ApplicationCache singleton of that cache host, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent is checking to see if it can download the application.

    5. If these steps were invoked with a cache host, and the status of cache group is downloading, then also queue a post-load task to run these steps:

      1. Let showProgress be the result of firing an event named downloading at the ApplicationCache singleton of that cache host, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user the application is being downloaded.

    6. If the status of the cache group is either checking or downloading, then abort this instance of the application cache download process, as an update is already in progress.

    7. Set the status of cache group to checking.

    8. For each cache host associated with an application cache in cache group, queue a post-load task run these steps:

      1. Let showProgress be the result of firing an event named checking at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent is checking for the availability of updates.

    The remainder of the steps run in parallel.

    If cache group already has an application cache in it, then this is an upgrade attempt. Otherwise, this is a cache attempt.

  3. If this is a cache attempt, then this algorithm was invoked with a cache host; queue a post-load task to run these steps:

    1. Let showProgress be the result of firing an event named checking at the ApplicationCache singleton of that cache host, with the cancelable attribute initialized to true.

    2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent is checking for the availability of updates.

  4. Let request be a new request whose url is manifest URL, client is null, destination is the empty string, referrer is "no-referrer", synchronous flag is set, credentials mode is "include", and whose use-URL-credentials flag is set.

  5. Fetching the manifest: Let manifest be the result of fetching request. HTTP caching semantics should be honored for this request.

    Parse manifest's body according to the rules for parsing manifests, obtaining a list of explicit entries, fallback entries and the fallback namespaces that map to them, entries for the online safelist, and values for the online safelist wildcard flag and the cache mode flag.

    The MIME type of the resource is ignored — it is assumed to be text/cache-manifest. In the future, if new manifest formats are supported, the different types will probably be distinguished on the basis of the file signatures (for the current format, that is the "CACHE MANIFEST" string at the top of the file).

  6. If fetching the manifest fails due to a 404 or 410 response status, then run these substeps:

    1. Mark cache group as obsolete. This cache group no longer exists for any purpose other than the processing of Document objects already associated with an application cache in the cache group.

    2. Let task list be an empty list of tasks.

    3. For each cache host associated with an application cache in cache group, create a task to run these steps and append it to task list:

      1. Let showProgress be the result of firing an event named obsolete at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the application is no longer available for offline use.

    4. For each entry in cache group's list of pending primary entries, create a task to run these steps and append it to task list:

      1. Let showProgress be the result of firing an event named error (not obsolete!) at the ApplicationCache singleton of the Document for this entry, if there still is one, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent failed to save the application for offline use.

    5. If cache group has an application cache whose completeness flag is incomplete, then discard that application cache.

    6. If appropriate, remove any user interface indicating that an update for this cache is in progress.

    7. Let the status of cache group be idle.

    8. For each task in task list, queue that task as a post-load task.

    9. Abort the application cache download process.

  7. Otherwise, if fetching the manifest fails in some other way (e.g. the server returns another 4xx or 5xx response, or there is a DNS error, or the connection times out, or the user cancels the download, or the parser for manifests fails when checking the magic signature), or if the server returned a redirect, then run the cache failure steps. [HTTP]

  8. If this is an upgrade attempt and the newly downloaded manifest is byte-for-byte identical to the manifest found in the newest application cache in cache group, or the response status is 304, then run these substeps:

    1. Let cache be the newest application cache in cache group.

    2. Let task list be an empty list of tasks.

    3. For each entry in cache group's list of pending primary entries, wait for the resource for this entry to have either completely downloaded or failed.

      If the download failed (e.g. the server returns a 4xx or 5xx response, or there is a DNS error, the connection times out, or the user cancels the download), or if the resource is labeled with the "no-store" cache directive, then create a task to run these steps and append it to task list:

      1. Let showProgress be the result of firing an event named error at the ApplicationCache singleton of the Document for this entry, if there still is one, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent failed to save the application for offline use.

      Otherwise, associate the Document for this entry with cache; store the resource for this entry in cache, if it isn't already there, and categorize its entry as a primary entry. If applying the URL parser algorithm to the resource's URL results in a URL record that has a non-null fragment component, the URL used for the entry in cache must instead be the absolute URL obtained from applying the URL serializer algorithm to the URL record with the exclude fragment flag set (application caches never include fragments).

    4. For each cache host associated with an application cache in cache group, create a task to run these steps and append it to task list:

      1. Let showProgress be the result of firing an event named noupdate at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the application is up to date.

    5. Empty cache group's list of pending primary entries.

    6. If appropriate, remove any user interface indicating that an update for this cache is in progress.

    7. Let the status of cache group be idle.

    8. For each task in task list, queue that task as a post-load task.

    9. Abort the application cache download process.

  9. Let new cache be a newly created application cache in cache group. Set its completeness flag to incomplete.

  10. For each entry in cache group's list of pending primary entries, associate the Document for this entry with new cache.

  11. Set the status of cache group to downloading.

  12. For each cache host associated with an application cache in cache group, queue a post-load task to run these steps:

    1. Let showProgress be the result of firing an event named downloading at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

    2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that a new version is being downloaded.

  13. Let file list be an empty list of URLs with flags.

  14. Add all the URLs in the list of explicit entries obtained by parsing manifest to file list, each flagged with "explicit entry".

  15. Add all the URLs in the list of fallback entries obtained by parsing manifest to file list, each flagged with "fallback entry".

  16. If this is an upgrade attempt, then add all the URLs of primary entries in the newest application cache in cache group whose completeness flag is complete to file list, each flagged with "primary entry".

  17. If any URL is in file list more than once, then merge the entries into one entry for that URL, that entry having all the flags that the original entries had.

  18. For each URL in file list, run the following steps. These steps may be run in parallel for two or more of the URLs at a time. If, while running these steps, the ApplicationCache object's abort() method sends a signal to this instance of the application cache download process algorithm, then run the cache failure steps instead.

    1. If the resource URL being processed was flagged as neither an "explicit entry" nor or a "fallback entry", then the user agent may skip this URL.

      This is intended to allow user agents to expire resources not listed in the manifest from the cache. Generally, implementers are urged to use an approach that expires lesser-used resources first.

    2. For each cache host associated with an application cache in cache group, queue a progress post-load task to run these steps:

      1. Let showProgress be the result of firing an event named progress at the ApplicationCache singleton of the cache host, using ProgressEvent, with the cancelable attribute initialized to true, the lengthComputable attribute initialized to true, the total attribute initialized to the number of files in file list, and the loaded attribute initialized to the number of files in file list that have been either downloaded or skipped so far. [XHR]

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that a file is being downloaded in preparation for updating the application.

    3. Let request be a new request whose url is URL, client is null, destination is the empty string, origin is manifest URL's origin, referrer is "no-referrer", synchronous flag is set, credentials mode is "include", use-URL-credentials flag is set, and redirect mode is "manual".

    4. Fetch request. If this is an upgrade attempt, then use the newest application cache in cache group as an HTTP cache, and honor HTTP caching semantics (such as expiration, ETags, and so forth) with respect to that cache. User agents may also have other caches in place that are also honored.

    5. If the previous step fails (e.g. the server returns a 4xx or 5xx response, or there is a DNS error, or the connection times out, or the user cancels the download), or if the server returned a redirect, or if the resource is labeled with the "no-store" cache directive, then run the first appropriate step from the following list: [HTTP]

      If the URL being processed was flagged as an "explicit entry" or a "fallback entry"

      If these steps are being run in parallel for any other URLs in file list, then abort this algorithm for those other URLs. Run the cache failure steps.

      Redirects are fatal because they are either indicative of a network problem (e.g. a captive portal); or would allow resources to be added to the cache under URLs that differ from any URL that the networking model will allow access to, leaving orphan entries; or would allow resources to be stored under URLs different than their true URLs. All of these situations are bad.

      If the error was a 404 or 410 HTTP response
      If the resource was labeled with the "no-store" cache directive

      Skip this resource. It is dropped from the cache.

      Otherwise

      Copy the resource and its metadata from the newest application cache in cache group whose completeness flag is complete, and act as if that was the fetched resource, ignoring the resource obtained from the network.

      User agents may warn the user of these errors as an aid to development.

      These rules make errors for resources listed in the manifest fatal, while making it possible for other resources to be removed from caches when they are removed from the server, without errors, and making non-manifest resources survive server-side errors.

      Except for the "no-store" directive, HTTP caching rules that would cause a file to be expired or otherwise not cached are ignored for the purposes of the application cache download process.

    6. Otherwise, the fetching succeeded. Store the resource in the new cache.

      If the user agent is not able to store the resource (e.g. because of quota restrictions), the user agent may prompt the user or try to resolve the problem in some other manner (e.g. automatically pruning content in other caches). If the problem cannot be resolved, the user agent must run the cache failure steps.

    7. If the URL being processed was flagged as an "explicit entry" in file list, then categorize the entry as an explicit entry.

    8. If the URL being processed was flagged as a "fallback entry" in file list, then categorize the entry as a fallback entry.

    9. If the URL being processed was flagged as a "primary entry" in file list, then categorize the entry as a primary entry.

    10. As an optimization, if the resource is an HTML or XML file whose document element is an html element with a manifest attribute whose value doesn't match the manifest URL of the application cache being processed, then the user agent should mark the entry as being foreign.

  19. For each cache host associated with an application cache in cache group, queue a progress post-load task to run these steps:

    1. Let showProgress be the result of firing an event named progress at the ApplicationCache singleton of the cache host, using ProgressEvent, with the cancelable attribute initialized to true, the lengthComputable attribute initialized to true, and the total and loaded attributes initialized to the number of files in file list. [XHR]

    2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that all the files have been downloaded.

  20. Store the list of fallback namespaces, and the URLs of the fallback entries that they map to, in new cache.

  21. Store the URLs that form the new online safelist in new cache.

  22. Store the value of the new online safelist wildcard flag in new cache.

  23. Store the value of the new cache mode flag in new cache.

  24. For each entry in cache group's list of pending primary entries, wait for the resource for this entry to have either completely downloaded or failed.

    If the download failed (e.g. the server returns a 4xx or 5xx response, or there is a DNS error, the connection times out, or the user cancels the download), or if the resource is labeled with the "no-store" cache directive, then run these substeps:

    1. Unassociate the Document for this entry from new cache.

    2. Queue a post-load task to run these steps:

      1. Let showProgress be the result of firing an event named error at the ApplicationCache singleton of the Document for this entry, if there still is one, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent failed to save the application for offline use.

    3. If this is a cache attempt and this entry is the last entry in cache group's list of pending primary entries, then run these further substeps:

      1. Discard cache group and its only application cache, new cache.

      2. If appropriate, remove any user interface indicating that an update for this cache is in progress.

      3. Abort the application cache download process.

    4. Otherwise, remove this entry from cache group's list of pending primary entries.

    Otherwise, store the resource for this entry in new cache, if it isn't already there, and categorize its entry as a primary entry.

  25. Let request be a new request whose url is manifest URL, client is null, destination is the empty string, referrer is "no-referrer", synchronous flag is set, credentials mode is "include", and whose use-URL-credentials flag is set.

  26. Let second manifest be the result of fetching request. HTTP caching semantics should again be honored for this request.

    Since caching can be honored, authors are encouraged to avoid setting the cache headers on the manifest in such a way that the user agent would simply not contact the network for this second request; otherwise, the user agent would not notice if the cache had changed during the cache update process.

  27. If the previous step failed for any reason, or if the fetching attempt involved a redirect, or if second manifest and manifest are not byte-for-byte identical, then schedule a rerun of the entire algorithm with the same parameters after a short delay, and run the cache failure steps.

  28. Otherwise, store manifest in new cache, if it's not there already, and categorize its entry as the manifest.

  29. Set the completeness flag of new cache to complete.

  30. Let task list be an empty list of tasks.

  31. If this is a cache attempt, then for each cache host associated with an application cache in cache group, create a task to run these steps and append it to task list:

    1. Let showProgress be the result of firing an event named cached at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

    2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the application has been cached and that they can now use it offline.

    Otherwise, it is an upgrade attempt. For each cache host associated with an application cache in cache group, create a task to run these steps and append it to task list:

    1. Let showProgress be the result of firing an event named updateready at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

    2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that a new version is available and that they can activate it by reloading the page.

  32. If appropriate, remove any user interface indicating that an update for this cache is in progress.

  33. Set the update status of cache group to idle.

  34. For each task in task list, queue that task as a post-load task.

The cache failure steps are as follows:

  1. Let task list be an empty list of tasks.

  2. For each entry in cache group's list of pending primary entries, run the following further substeps. These steps may be run in parallel for two or more entries at a time.

    1. Wait for the resource for this entry to have either completely downloaded or failed.

    2. Unassociate the Document for this entry from its application cache, if it has one.

    3. Create a task to run these steps and append it to task list:

      1. Let showProgress be the result of firing an event named error at the ApplicationCache singleton of the Document for this entry, if there still is one, with the cancelable attribute initialized to true.

      2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent failed to save the application for offline use.

  3. For each cache host still associated with an application cache in cache group, create a task to run these steps and append it to task list:

    1. Let showProgress be the result of firing an event named error at the ApplicationCache singleton of the cache host, with the cancelable attribute initialized to true.

    2. If showProgress is true and the user agent shows caching progress, then display some sort of user interface indicating to the user that the user agent failed to save the application for offline use.

  4. Empty cache group's list of pending primary entries.

  5. If cache group has an application cache whose completeness flag is incomplete, then discard that application cache.

  6. If appropriate, remove any user interface indicating that an update for this cache is in progress.

  7. Let the status of cache group be idle.

  8. If this was a cache attempt, discard cache group altogether.

  9. For each task in task list, queue that task as a post-load task.

  10. Abort the application cache download process.

Attempts to fetch resources as part of the application cache download process may be done with cache-defeating semantics, to avoid problems with stale or inconsistent intermediary caches.


User agents may invoke the application cache download process, in the background, for any application cache group, at any time (with no cache host). This allows user agents to keep caches primed and to update caches even before the user visits a site.


Each Document has a list of pending application cache download process tasks that is used to delay events fired by the algorithm above until the document's load event has fired. When the Document is created, the list must be empty.

When the steps above say to queue a post-load task task, where task is a task that dispatches an event on a target ApplicationCache object target, the user agent must run the appropriate steps from the following list:

If target's node document is ready for post-load tasks

Queue the task task.

Otherwise

Add task to target's node document's list of pending application cache download process tasks.

When the steps above say to queue a progress post-load task task, where task is a task that dispatches an event on a target ApplicationCache object target, the user agent must run the following steps:

  1. If there is a task in target's node document's list of pending application cache download process tasks that is labeled as a progress task, then remove that task from the list.

  2. Label task as a progress task.

  3. Queue a post-load task task.

The task source for these tasks is the networking task source.

7.11.5 应用缓存选择算法

当使用 Document document 和可选的清单 URL manifest URL 调用 应用缓存选择算法时, 用户代理必须执行如下列表中第一套适当的步骤:

如果有一个 manifest URL,并且 document 是从一个 应用缓存 加载的,并且该缓存的 应用缓存组清单 的 URL 与 manifest URL 不同

在加载 document应用缓存 中, 标记获取 document 的资源入口为 foreign

导航算法 的头部重启当前导航, 撤销在初次加载过程中的任何改动,(只要确保 使用新的页面更新会话历史 步骤只在该 应用缓存选择算法 执行 之后 完成,就可以避免改动,但不要求这样做)。

导航将会导致加载不同的资源,因为在导航时不会选择 "foreign" 入口。

用户代理可以提示用户缓存清单和文档元数据之间的不一致,来帮助也要开发。

如果 document 是从 应用缓存 加载的, 并且那个 应用缓存 仍然存在 (它现在不是 废弃 状态) )

document 与加载它的 应用缓存 关联。 为那个 应用缓存应用缓存组 在后台调用 应用缓存下载过程, 使用 document 作为 缓存 Host

如果 document 是使用 `GET` 加载的, 且存在一个 manifest URL,且 manifest URLdocument
同源

manifest URL 在后台调用 应用缓存下载过程 使用 document 作为 cache host 使用解析 document 的资源作为 资源。

如果存在由 document 同源的 入口 URL 标识的 相关的应用缓存, 排除掉标记为 foreign 的入口, 然后在加载任何子资源时,用户代理应使用匹配为 HTTP 缓存的 最合适的应用缓存。 用户代理也可能有其他缓存,这些缓存也可以用。

其他情况

Document 没有与任何 应用缓存 关联。

如果存在一个 manifest URL,用户代理可以报告用户它已经被忽略,来帮助应用开发。

7.11.6 Changes to the networking model

If "AppCache" is not removed as a feature this section needs to be integrated into the Fetch standard.

When a cache host is associated with an application cache whose completeness flag is complete, any and all loads for resources related to that cache host other than those for child browsing contexts must go through the following steps instead of immediately invoking the mechanisms appropriate to that resource's scheme:

  1. If the resource is not to be fetched using the GET method, or if applying the URL parser algorithm to both its URL and the application cache's manifest's URL results in two URL records with different scheme components, then fetch the resource normally and return.

  2. If the resource's URL is a primary entry, the manifest, an explicit entry, or a fallback entry in the application cache, then get the resource from the cache (instead of fetching it), and return.

  3. If there is an entry in the application cache's online safelist that has the same origin as the resource's URL and that is a prefix match for the resource's URL, then fetch the resource normally and return.

  4. If the resource's URL has the same origin as the manifest's URL, and there is a fallback namespace f in the application cache that is a prefix match for the resource's URL, then:

    Fetch the resource normally. If this results in a redirect to a resource with another origin (indicative of a captive portal), or a 4xx or 5xx status code, or if there were network errors (but not if the user canceled the download), then instead get, from the cache, the resource of the fallback entry corresponding to the fallback namespace f. Return.

  5. If the application cache's online safelist wildcard flag is open, then fetch the resource normally and return.

  6. Fail the resource load as if there had been a generic network error.

The above algorithm ensures that so long as the online safelist wildcard flag is blocking, resources that are not present in the manifest will always fail to load (at least, after the application cache has been primed the first time), making the testing of offline applications simpler.

7.11.7 应用缓存过期

作为通用的规则,用户代理不应该将应用缓存过期,除非受到用户的请求, 或者在很久时间内没有用到。

应用缓存和 Cookie 在隐私方面有同样的意义(例如,如果站点在提供缓存时可以识别用户, 就可以在缓存中存储数据用于 Cookie 恢复)。 因此鼓励实现方以类似 HTTP cookie 的方式暴露应用缓存, 使得缓存可以和 Cookie 等其他域相关的数据一起清除。

例如,一个用户代理可以有一个 "删除站点相关数据" 功能来立即清除 一个域下所有的所有的 Cookie、应用缓存、本地存储、数据库等等。

7.11.8 磁盘空间

用户代理应该考虑对 应用缓存 的磁盘用量加以约束, 小心确保这些约束不会被子域名轻易绕过。

用户代理应该允许用户看到每个域名使用的空间大小,也可以为用户提供删除指定 应用缓存 的能力。

为了可预见性,应该根据未压缩的数据大小来进行配额。

如何为用户显示配额不在本规范中定义。 鼓励用户代理提供类似允许用户信任某些站点以使用多于默认的配额,例如在缓存更新时显示一个非模态 UI, 或者在用户代理的配置接口中显示一个安全列表。

7.11.9 离线应用缓存的安全问题

This section is non-normative.

离线应用程序缓存引入的主要风险是注入攻击可以提升为持久的站点范围页面替换。 这种攻击涉及使用注入漏洞将两个文件上传到受害者站点。 第一个文件是一个应用程序缓存清单,其中只包含指向第二个文件的 Fallback 入口,该文件是一个HTML 页面,其清单声明为第一个文件。 一旦用户被定向到第二个文件,当用户或站点处于离线状态时,对给定 Fallback 命名空间内的任何文件的所有后续访问都将显示该第二个文件。 针对性的 DoS 攻击或 Cookie 炸弹攻击(客户端发送足够多的 Cookie 来导致服务器拒绝处理该请求)可用于确保该网站显示为脱机。

为了缓解这种情况,清单只能指定与清单本身位于相同路径的 Fallback。这意味着服务器上特定目录中的内容注入上传漏洞只能升级为接管该目录及其子目录。 如果无法将文件注入到根目录,那么就无法接管整个站点。

如果某个站点遭到这种方式的攻击,则只需删除恶意的清单就可以最终解决问题,因为下次更新清单时,将会得到 404 错误,然后用户代理就会清除缓存。然而,这里的“最终”是关键词。在对用户或服务器的攻击正在进行时,从受影响的用户到受影响的站点的连接已经被阻止,用户代理将简单地假定用户处于离线状态并将继续使用恶意的清单。不幸的是,如果还使用了 Cookie 炸弹攻击,那么仅仅删除清单是不够的;此外,服务器还得配置为返回 404 或 410 响应,而不是 413 “请求实体太大”响应。

TLS 本身不会保护网站免受此攻击,因为攻击依赖于服务器本身提供的内容。 不使用应用程序缓存也不能阻止这种攻击,因为攻击依赖于攻击者提供的清单。

7.11.10 Application cache API

[SecureContext,
 Exposed=Window]
interface ApplicationCache : EventTarget {

  // update status
  const unsigned short UNCACHED = 0;
  const unsigned short IDLE = 1;
  const unsigned short CHECKING = 2;
  const unsigned short DOWNLOADING = 3;
  const unsigned short UPDATEREADY = 4;
  const unsigned short OBSOLETE = 5;
  readonly attribute unsigned short status;

  // updates
  undefined update();
  undefined abort();
  undefined swapCache();

  // events
  attribute EventHandler onchecking;
  attribute EventHandler onerror;
  attribute EventHandler onnoupdate;
  attribute EventHandler ondownloading;
  attribute EventHandler onprogress;
  attribute EventHandler onupdateready;
  attribute EventHandler oncached;
  attribute EventHandler onobsolete;
};
cache = window . applicationCache

Returns the ApplicationCache object that applies to the active document of that Window.

cache . status

Returns the current status of the application cache, as given by the constants defined below.

cache . update()

Invokes the application cache download process.

Throws an "InvalidStateError" DOMException if there is no application cache to update.

Calling this method is not usually necessary, as user agents will generally take care of updating application caches automatically.

The method can be useful in situations such as long-lived applications. For example, a web mail application might stay open in a browser tab for weeks at a time. Such an application could want to test for updates each day.

cache . abort()

Cancels the application cache download process.

This method is intended to be used by web application showing their own caching progress UI, in case the user wants to stop the update (e.g. because bandwidth is limited).

cache . swapCache()

Switches to the most recent application cache, if there is a newer one. If there isn't, throws an "InvalidStateError" DOMException.

This does not cause previously-loaded resources to be reloaded; for example, images do not suddenly get reloaded and style sheets and scripts do not get reparsed or reevaluated. The only change is that subsequent requests for cached resources will obtain the newer copies.

The updateready event will fire before this method can be called. Once it fires, the web application can, at its leisure, call this method to switch the underlying cache to the one with the more recent updates. To make proper use of this, applications have to be able to bring the new features into play; for example, reloading scripts to enable new features.

An easier alternative to swapCache() is just to reload the entire page at a time suitable for the user, using location.reload().

There is a one-to-one mapping from cache hosts to ApplicationCache objects. The applicationCache attribute on Window objects must return the ApplicationCache object associated with the Window object's active document.

A Document has an associated ApplicationCache object even if that cache host has no actual application cache.


The status attribute, on getting, must return the current state of the application cache that the ApplicationCache object's cache host is associated with, if any. This must be the appropriate value from the following list:

UNCACHED (numeric value 0)

The ApplicationCache object's cache host is not associated with an application cache at this time.

IDLE (numeric value 1)

The ApplicationCache object's cache host is associated with an application cache whose application cache group's update status is idle, and that application cache is the newest cache in its application cache group, and the application cache group is not marked as obsolete.

CHECKING (numeric value 2)

The ApplicationCache object's cache host is associated with an application cache whose application cache group's update status is checking.

DOWNLOADING (numeric value 3)

The ApplicationCache object's cache host is associated with an application cache whose application cache group's update status is downloading.

UPDATEREADY (numeric value 4)

The ApplicationCache object's cache host is associated with an application cache whose application cache group's update status is idle, and whose application cache group is not marked as obsolete, but that application cache is not the newest cache in its group.

OBSOLETE (numeric value 5)

The ApplicationCache object's cache host is associated with an application cache whose application cache group is marked as obsolete.


If the update() method is invoked, the user agent must invoke the application cache download process, in the background, for the application cache group of the application cache with which the ApplicationCache object's cache host is associated, but without giving that cache host to the algorithm. If there is no such application cache, or if its application cache group is marked as obsolete, then the method must throw an "InvalidStateError" DOMException instead.

If the abort() method is invoked, the user agent must send a signal to the current application cache download process for the application cache group of the application cache with which the ApplicationCache object's cache host is associated, if any. If there is no such application cache, or it does not have a current application cache download process, then do nothing.

If the swapCache() method is invoked, the user agent must run the following steps:

  1. Check that ApplicationCache object's cache host is associated with an application cache. If it is not, then throw an "InvalidStateError" DOMException.

  2. Let cache be the application cache with which the ApplicationCache object's cache host is associated. (By definition, this is the same as the one that was found in the previous step.)

  3. If cache's application cache group is marked as obsolete, then unassociate the ApplicationCache object's cache host from cache and return. (Resources will now load from the network instead of the cache.)

  4. Check that there is an application cache in the same application cache group as cache whose completeness flag is complete and that is newer than cache. If there is not, then throw an "InvalidStateError" DOMException exception.

  5. Let new cache be the newest application cache in the same application cache group as cache whose completeness flag is complete.

  6. Unassociate the ApplicationCache object's cache host from cache and instead associate it with new cache.

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the ApplicationCache interface:

Event handler Event handler event type
onchecking checking
onerror error
onnoupdate noupdate
ondownloading downloading
onprogress progress
onupdateready updateready
oncached cached
onobsolete obsolete
interface mixin NavigatorOnLine {
  readonly attribute boolean onLine;
};
self . navigator . onLine

Navigator/onLine

Support in all current engines.

Firefox1.5+Safari4+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android🔰 37+Samsung Internet1.0+Opera Android10.1+

WorkerNavigator/onLine

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android🔰 4.4+Samsung Internet1.0+Opera Android11+

Returns false if the user agent is definitely offline (disconnected from the network). Returns true if the user agent might be online.

The events online and offline are fired when the value of this attribute changes.

The navigator.onLine attribute must return false if the user agent will not contact the network when the user follows links or when a script requests a remote page (or knows that such an attempt would fail), and must return true otherwise.

When the value that would be returned by the navigator.onLine attribute of a Window or WorkerGlobalScope global changes from true to false, the user agent must queue a global task on the networking task source given global to fire an event named offline at global.

On the other hand, when the value that would be returned by the navigator.onLine attribute of a Window or WorkerGlobalScope global changes from false to true, the user agent must queue a global task on the networking task source given global to fire an event named online at the Window or WorkerGlobalScope object.

This attribute is inherently unreliable. A computer can be connected to a network without having Internet access.

In this example, an indicator is updated as the browser goes online and offline.

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <title>Online status</title>
  <script>
   function updateIndicator() {
     document.getElementById('indicator').textContent = navigator.onLine ? 'online' : 'offline';
   }
  </script>
 </head>
 <body onload="updateIndicator()" ononline="updateIndicator()" onoffline="updateIndicator()">
  <p>The network is: <span id="indicator">(state unknown)</span>
 </body>
</html>

8 Web 应用 API

8.1 脚本

8.1.1 概述

有很多机制可以让作者提供的可执行代码在文档的上下文中运行。这些机制包括但不限于:

8.1.2 Agents and agent clusters

8.1.2.1 Integration with the JavaScript agent formalism

JavaScript defines the concept of an agent. This section gives the mapping of that language-level concept on to the web platform.

Conceptually, the agent concept is an architecture-independent, idealized "thread" in which JavaScript code runs. Such code can involve multiple globals/realms that can synchronously access each other, and thus needs to run in a single execution thread.

Two Window objects having the same agent does not indicate they can directly access all objects created in each other's realms. They would have to be same origin-domain; see IsPlatformObjectSameOrigin.

The following types of agents exist on the web platform:

Similar-origin window agent

Contains various Window objects which can potentially reach each other, either directly or by using document.domain.

If the encompassing agent cluster's cross-origin isolated is true, then all the Window objects will be same origin, can reach each other directly, and document.domain will no-op.

Two Window objects that are same origin can be in different similar-origin window agents, for instance if they are each in their own browsing context group.

Dedicated worker agent

Contains a single DedicatedWorkerGlobalScope.

Shared worker agent

Contains a single SharedWorkerGlobalScope.

Service worker agent

Contains a single ServiceWorkerGlobalScope.

Worklet agent

Contains a single WorkletGlobalScope object.

Although a given worklet can have multiple realms, each such realm needs its own agent, as each realm can be executing code independently and at the same time as the others.

Only shared and dedicated worker agents allow the use of JavaScript Atomics APIs to potentially block.

To create an agent, given a boolean canBlock:

  1. Let signifier be a new unique internal value.

  2. Let candidateExecution be a new candidate execution.

  3. Let agent be a new agent whose [[CanBlock]] is canBlock, [[Signifier]] is signifier, [[CandidateExecution]] is candidateExecution, and [[IsLockFree1]], [[IsLockFree2]], and [[LittleEndian]] are set at the implementation's discretion.

  4. Set agent's event loop to a new event loop.

  5. Return agent.

The relevant agent for a platform object platformObject is platformObject's relevant Realm's agent. This pointer is not yet defined in the JavaScript specification; see tc39/ecma262#1357.

The agent equivalent of the current Realm Record is the surrounding agent.

8.1.2.2 Integration with the JavaScript agent cluster formalism

JavaScript also defines the concept of an agent cluster, which this standard maps to the web platform by placing agents appropriately when they are created using the obtain a similar-origin window agent or obtain a worker/worklet agent algorithms.

The agent cluster concept is crucial for defining the JavaScript memory model, and in particular among which agents the backing data of SharedArrayBuffer objects can be shared.

Conceptually, the agent cluster concept is an architecture-independent, idealized "process boundary" that groups together multiple "threads" (agents). The agent clusters defined by the specification are generally more restrictive than the actual process boundaries implemented in user agents. By enforcing these idealized divisions at the specification level, we ensure that web developers see interoperable behavior with regard to shared memory, even in the face of varying and changing user agent process models.

An agent cluster has an associated cross-origin isolated (a boolean), which is initially false.

An agent cluster has an associated origin-isolated (a boolean), which is initially false.


The following defines the allocation of the agent clusters of similar-origin window agents.

An agent cluster key is a site or tuple origin. Without web developer action to achieve origin isolation, it will be a site.

An equivalent formulation is that an agent cluster key can be a scheme-and-host or an origin.

To obtain a similar-origin window agent, given an origin origin, a browsing context group group, and a boolean requestsOI, run these steps:

  1. Let site be the result of obtaining a site with origin.

  2. Let key be site.

  3. If group's cross-origin isolated is true, then set key to origin.

  4. Otherwise, if group's historical agent cluster key map[origin] exists, then set key to group's historical agent cluster key map[origin].

  5. Otherwise:

    1. If requestsOI is true, then set key to origin.

    2. Set group's historical agent cluster key map[origin] to key.

  6. If group's agent cluster map[key] does not exist, then:

    1. Let agentCluster be a new agent cluster.

    2. Set agentCluster's cross-origin isolated to group's cross-origin isolated.

    3. Set agentCluster's origin-isolated to true if key equals origin; otherwise false.

    4. Add the result of creating an agent, given false, to agentCluster.

    5. Set group's agent cluster map[key] to agentCluster.

  7. Return the single similar-origin window agent contained in group's agent cluster map[key].

This means that there is only one similar-origin window agent per browsing context agent cluster. (However, dedicated worker and worklet agents might be in the same cluster.)


The following defines the allocation of the agent clusters of all other types of agents.

To obtain a worker/worklet agent, given an environment settings object or null outside settings, a boolean isTopLevel, and a boolean canBlock, run these steps:

  1. Let agentCluster be null.

  2. If isTopLevel is true, then:

    1. Set agentCluster to a new agent cluster.

    2. Set agentCluster's origin-isolated to true.

      These workers can be considered to be origin-isolated. However, this is not exposed through any APIs (in the way that originIsolated exposes the origin-isolation state for windows).

  3. Otherwise:

    1. Assert: outside settings is not null.

    2. Let ownerAgent be outside settings's Realm's agent.

    3. Set agentCluster to the agent cluster which contains ownerAgent.

  4. Let agent be the result of creating an agent given canBlock.

  5. Add agent to agentCluster.

  6. Return agent.

To obtain a dedicated/shared worker agent, given an environment settings object outside settings and a boolean isShared, return the result of obtaining a worker/worklet agent given outside settings, isShared, and true.

To obtain a worklet agent, given an environment settings object outside settings, return the result of obtaining a worker/worklet agent given outside settings, false, and false.

To obtain a service worker agent, return the result of obtaining a worker/worklet agent given null, true, and false.


The following pairs of global objects are each within the same agent cluster, and thus can use SharedArrayBuffer instances to share memory with each other:

The following pairs of global objects are not within the same agent cluster, and thus cannot share memory:

8.1.3 Realms and their counterparts

The JavaScript specification introduces the realm concept, representing a global environment in which script is run. Each realm comes with an implementation-defined global object; much of this specification is devoted to defining that global object and its properties.

For web specifications, it is often useful to associate values or algorithms with a realm/global object pair. When the values are specific to a particular type of realm, they are associated directly with the global object in question, e.g., in the definition of the Window or WorkerGlobalScope interfaces. When the values have utility across multiple realms, we use the environment settings object concept.

Finally, in some cases it is necessary to track associated values before a realm/global object/environment settings object even comes into existence (for example, during navigation). These values are tracked in the environment concept.

8.1.3.1 Environments

An environment is an object that identifies the settings of a current or potential execution environment. An environment has the following fields:

An id

An opaque string that uniquely identifies this environment.

A creation URL

A URL that represents the location of the resource with which this environment is associated.

In the case of an environment settings object, this URL might be distinct from the environment settings object's responsible document's URL, due to mechanisms such as history.pushState().

A top-level creation URL

Null or a URL that represents the creation URL of the "top-level" environment. It is null for workers and worklets.

A top-level origin

A for now implementation-defined value, null, or an origin. For a "top-level" potential execution environment it is null (i.e., when there is no response yet); otherwise it is the "top-level" environment's origin. For a dedicated worker or worklet it is the top-level origin of its creator. For a shared or service worker it is an implementation-defined value.

This is distinct from the top-level creation URL's origin when sandboxing, workers, and worklets are involved.

A target browsing context

Null or a target browsing context for a navigation request.

An active service worker

Null or a service worker that controls the environment.

An execution ready flag

A flag that indicates whether the environment setup is done. It is initially unset.

Specifications may define environment discarding steps for environments. The steps take an environment as input.

The environment discarding steps are run for only a select few environments: the ones that will never become execution ready because, for example, they failed to load.

8.1.3.2 Environment settings objects

An environment settings object is an environment that additionally specifies algorithms for:

A realm execution context

A JavaScript execution context shared by all scripts that use this settings object, i.e. all scripts in a given JavaScript realm. When we run a classic script or run a module script, this execution context becomes the top of the JavaScript execution context stack, on top of which another execution context specific to the script in question is pushed. (This setup ensures ParseScript and Source Text Module Record's Evaluate know which Realm to use.)

A module map

A module map that is used when importing JavaScript modules.

A responsible document

A Document that is assigned responsibility for actions taken by the scripts that use this environment settings object.

For example, the URL of the responsible document is used to set the URL of the Document after it has been reset using document.open().

If the responsible event loop is not a window event loop, then the environment settings object has no responsible document.

An API URL character encoding

A character encoding used to encode URLs by APIs called by scripts that use this environment settings object.

An API base URL

A URL used by APIs called by scripts that use this environment settings object to parse URLs.

An origin

An origin used in security checks.

A referrer policy

The default referrer policy for fetches performed using this environment settings object as a request client. [REFERRERPOLICY]

An embedder policy

An embedder policy used by cross-origin resource policy checks for fetches performed using this environment settings object as a request client.

A cross-origin isolated capability

A boolean representing whether scripts that use this environment settings object are allowed to use APIs that require cross-origin isolation.

An environment settings object also has an outstanding rejected promises weak set and an about-to-be-notified rejected promises list, used to track unhandled promise rejections. The outstanding rejected promises weak set must not create strong references to any of its members, and implementations are free to limit its size, e.g. by removing old entries from it when new ones are added.

An environment settings object's responsible event loop is its global object's relevant agent's event loop.

8.1.3.3 Realms, settings objects, and global objects

A global object is a JavaScript object that is the [[GlobalObject]] field of a JavaScript realm.

In this specification, all JavaScript realms are created with global objects that are either Window or WorkerGlobalScope objects.

There is always a 1-to-1-to-1 mapping between JavaScript realms, global objects, and environment settings objects:

To create a new JavaScript realm in an agent agent, optionally with instructions to create a global object or a global this binding (or both), the following steps are taken:

  1. Perform InitializeHostDefinedRealm() with the provided customizations for creating the global object and the global this binding.

  2. Let realm execution context be the running JavaScript execution context.

    This is the JavaScript execution context created in the previous step.

  3. Remove realm execution context from the JavaScript execution context stack.

  4. Let realm be realm execution context's Realm component.

  5. Set realm's agent to agent. This pointer is not yet defined in the JavaScript specification; see tc39/ecma262#1357.

  6. If agent's agent cluster's cross-origin isolated is false, then:

    1. Let global be realm's global object.

    2. Let status be ! global.[[Delete]]("SharedArrayBuffer").

    3. Assert: status is true.

    This is done for compatibility with web content and there is some hope that this can be removed in the future. Web developers can still get at the constructor through new WebAssembly.Memory({ shared:true, initial:0, maximum:0 }).buffer.constructor.

  7. Return realm execution context.


When defining algorithm steps throughout this specification, it is often important to indicate what JavaScript realm is to be used—or, equivalently, what global object or environment settings object is to be used. In general, there are at least four possibilities:

Entry
This corresponds to the script that initiated the currently running script action: i.e., the function or script that the user agent called into when it called into author code.
Incumbent
This corresponds to the most-recently-entered author function or script on the stack, or the author function or script that originally scheduled the currently-running callback.
Current
This corresponds to the currently-running function object, including built-in user-agent functions which might not be implemented as JavaScript. (It is derived from the current JavaScript realm.)
Relevant
Every platform object has a relevant Realm, which is roughly the JavaScript realm in which it was created. When writing algorithms, the most prominent platform object whose relevant Realm might be important is the this value of the currently-running function object. In some cases, there can be other important relevant Realms, such as those of any arguments.

Note how the entry, incumbent, and current concepts are usable without qualification, whereas the relevant concept must be applied to a particular platform object.

The incumbent and entry concepts should not be used by new specifications, as they are excessively complicated and unintuitive to work with. We are working to remove almost all existing uses from the platform: see issue #1430 for incumbent, and issue #1431 for entry.

In general, web platform specifications should use the relevant concept, applied to the object being operated on (usually the this value of the current method). This mismatches the JavaScript specification, where current is generally used as the default (e.g. in determining the JavaScript realm whose Array constructor should be used to construct the result in Array.prototype.map). But this inconsistency is so embedded in the platform that we have to accept it going forward.

Consider the following pages, with a.html being loaded in a browser window, b.html being loaded in an iframe as shown, and c.html and d.html omitted (they can simply be empty documents):

<!-- a.html -->
<!DOCTYPE html>
<html lang="en">
<title>Entry page</title>

<iframe src="b.html"></iframe>
<button onclick="frames[0].hello()">Hello</button>

<!--b.html -->
<!DOCTYPE html>
<html lang="en">
<title>Incumbent page</title>

<iframe src="c.html" id="c"></iframe>
<iframe src="d.html" id="d"></iframe>

<script>
  const c = document.querySelector("#c").contentWindow;
  const d = document.querySelector("#d").contentWindow;

  window.hello = () => {
    c.print.call(d);
  };
</script>

Each page has its own browsing context, and thus its own JavaScript realm, global object, and environment settings object.

When the print() method is called in response to pressing the button in a.html, then:

One reason why the relevant concept is generally a better default choice than the current concept is that it is more suitable for creating an object that is to be persisted and returned multiple times. For example, the navigator.getBattery() method creates promises in the relevant Realm for the Navigator object on which it is invoked. This has the following impact: [BATTERY]

<!-- outer.html -->
<!DOCTYPE html>
<html lang="en">
<title>Relevant Realm demo: outer page</title>
<script>
  function doTest() {
    const promise = navigator.getBattery.call(frames[0].navigator);

    console.log(promise instanceof Promise);           // logs false
    console.log(promise instanceof frames[0].Promise); // logs true

    frames[0].hello();
  }
</script>
<iframe src="inner.html" onload="doTest()"></iframe>

<!-- inner.html -->
<!DOCTYPE html>
<html lang="en">
<title>Relevant Realm demo: inner page</title>
<script>
  function hello() {
    const promise = navigator.getBattery();

    console.log(promise instanceof Promise);        // logs true
    console.log(promise instanceof parent.Promise); // logs false
  }
</script>

If the algorithm for the getBattery() method had instead used the current Realm, all the results would be reversed. That is, after the first call to getBattery() in outer.html, the Navigator object in inner.html would be permanently storing a Promise object created in outer.html's JavaScript realm, and calls like that inside the hello() function would thus return a promise from the "wrong" realm. Since this is undesirable, the algorithm instead uses the relevant Realm, giving the sensible results indicated in the comments above.


The rest of this section deals with formally defining the entry, incumbent, current, and relevant concepts.

8.1.3.3.1 Entry

The process of calling scripts will push or pop realm execution contexts onto the JavaScript execution context stack, interspersed with other execution contexts.

With this in hand, we define the entry execution context to be the most recently pushed item in the JavaScript execution context stack that is a realm execution context. The entry Realm is the entry execution context's Realm component.

Then, the entry settings object is the environment settings object of the entry Realm.

Similarly, the entry global object is the global object of the entry Realm.

8.1.3.3.2 Incumbent

All JavaScript execution contexts must contain, as part of their code evaluation state, a skip-when-determining-incumbent counter value, which is initially zero. In the process of preparing to run a callback and cleaning up after running a callback, this value will be incremented and decremented.

Every event loop has an associated backup incumbent settings object stack, initially empty. Roughly speaking, it is used to determine the incumbent settings object when no author code is on the stack, but author code is responsible for the current algorithm having been run in some way. The process of preparing to run a callback and cleaning up after running a callback manipulate this stack. [WEBIDL]

When Web IDL is used to invoke author code, or when HostEnqueuePromiseJob invokes a promise job, they use the following algorithms to track relevant data for determining the incumbent settings object:

To prepare to run a callback with an environment settings object settings:

  1. Push settings onto the backup incumbent settings object stack.

  2. Let context be the topmost script-having execution context.

  3. If context is not null, increment context's skip-when-determining-incumbent counter.

To clean up after running a callback with an environment settings object settings:

  1. Let context be the topmost script-having execution context.

    This will be the same as the topmost script-having execution context inside the corresponding invocation of prepare to run a callback.

  2. If context is not null, decrement context's skip-when-determining-incumbent counter.

  3. Assert: the topmost entry of the backup incumbent settings object stack is settings.

  4. Remove settings from the backup incumbent settings object stack.

Here, the topmost script-having execution context is the topmost entry of the JavaScript execution context stack that has a non-null ScriptOrModule component, or null if there is no such entry in the JavaScript execution context stack.

With all this in place, the incumbent settings object is determined as follows:

  1. Let context be the topmost script-having execution context.

  2. If context is null, or if context's skip-when-determining-incumbent counter is greater than zero, then:

    1. Assert: the backup incumbent settings object stack is not empty.

      This assert would fail if you try to obtain the incumbent settings object from inside an algorithm that was triggered neither by calling scripts nor by Web IDL invoking a callback. For example, it would trigger if you tried to obtain the incumbent settings object inside an algorithm that ran periodically as part of the event loop, with no involvement of author code. In such cases the incumbent concept cannot be used.

    2. Return the topmost entry of the backup incumbent settings object stack.

  3. Return context's Realm component's settings object.

Then, the incumbent Realm is the Realm of the incumbent settings object.

Similarly, the incumbent global object is the global object of the incumbent settings object.


The following series of examples is intended to make it clear how all of the different mechanisms contribute to the definition of the incumbent concept:

Consider the following starter example:

<!DOCTYPE html>
<iframe></iframe>
<script>
  frames[0].postMessage("some data", "*");
</script>

There are two interesting environment settings objects here: that of window, and that of frames[0]. Our concern is: what is the incumbent settings object at the time that the algorithm for postMessage() executes?

It should be that of window, to capture the intuitive notion that the author script responsible for causing the algorithm to happen is executing in window, not frames[0]. This makes sense: the window post message steps use the incumbent settings object to determine the source property of the resulting MessageEvent, and in this case window is definitely the source of the message.

Let us now explain how the steps given above give us our intuitively-desired result of window's relevant settings object.

When the window post message steps look up the incumbent settings object, the topmost script-having execution context will be that corresponding to the script element: it was pushed onto the JavaScript execution context stack as part of ScriptEvaluation during the run a classic script algorithm. Since there are no Web IDL callback invocations involved, the context's skip-when-determining-incumbent counter is zero, so it is used to determine the incumbent settings object; the result is the environment settings object of window.

(Note how the environment settings object of frames[0] is the relevant settings object of this at the time the postMessage() method is called, and thus is involved in determining the target of the message. Whereas the incumbent is used to determine the source.)

Consider the following more complicated example:

<!DOCTYPE html>
<iframe></iframe>
<script>
  const bound = frames[0].postMessage.bind(frames[0], "some data", "*");
  window.setTimeout(bound);
</script>

This example is very similar to the previous one, but with an extra indirection through Function.prototype.bind as well as setTimeout(). But, the answer should be the same: invoking algorithms asynchronously should not change the incumbent concept.

This time, the result involves more complicated mechanisms:

When bound is converted to a Web IDL callback type, the incumbent settings object is that corresponding to window (in the same manner as in our starter example above). Web IDL stores this as the resulting callback value's callback context.

When the task posted by setTimeout() executes, the algorithm for that task uses Web IDL to invoke the stored callback value. Web IDL in turn calls the above prepare to run a callback algorithm. This pushes the stored callback context onto the backup incumbent settings object stack. At this time (inside the timer task) there is no author code on the stack, so the topmost script-having execution context is null, and nothing gets its skip-when-determining-incumbent counter incremented.

Invoking the callback then calls bound, which in turn calls the postMessage() method of frames[0]. When the postMessage() algorithm looks up the incumbent settings object, there is still no author code on the stack, since the bound function just directly calls the built-in method. So the topmost script-having execution context will be null: the JavaScript execution context stack only contains an execution context corresponding to postMessage(), with no ScriptEvaluation context or similar below it.

This is where we fall back to the backup incumbent settings object stack. As noted above, it will contain as its topmost entry the relevant settings object of window. So that is what is used as the incumbent settings object while executing the postMessage() algorithm.

Consider this final, even more convoluted example:

<!-- a.html -->
<!DOCTYPE html>
<button>click me</button>
<iframe></iframe>
<script>
const bound = frames[0].location.assign.bind(frames[0].location, "https://example.com/");
document.querySelector("button").addEventListener("click", bound);
</script>
<!-- b.html -->
<!DOCTYPE html>
<iframe src="a.html"></iframe>
<script>
  const iframe = document.querySelector("iframe");
  iframe.onload = function onLoad() {
    iframe.contentWindow.document.querySelector("button").click();
  };
</script>

Again there are two interesting environment settings objects in play: that of a.html, and that of b.html. When the location.assign() method triggers the Location-object navigate algorithm, what will be the incumbent settings object? As before, it should intuitively be that of a.html: the click listener was originally scheduled by a.html, so even if something involving b.html causes the listener to fire, the incumbent responsible is that of a.html.

The callback setup is similar to the previous example: when bound is converted to a Web IDL callback type, the incumbent settings object is that corresponding to a.html, which is stored as the callback's callback context.

When the click() method is called inside b.html, it dispatches a click event on the button that is inside a.html. This time, when the prepare to run a callback algorithm executes as part of event dispatch, there is author code on the stack; the topmost script-having execution context is that of the onLoad function, whose skip-when-determining-incumbent counter gets incremented. Additionally, a.html's environment settings object (stored as the EventHandler's callback context) is pushed onto the backup incumbent settings object stack.

Now, when the Location-object navigate algorithm looks up the incumbent settings object, the topmost script-having execution context is still that of the onLoad function (due to the fact we are using a bound function as the callback). Its skip-when-determining-incumbent counter value is one, however, so we fall back to the backup incumbent settings object stack. This gives us the environment settings object of a.html, as expected.

Note that this means that even though it is the iframe inside a.html that navigates, it is a.html itself that is used as the source browsing context, which determines among other things the request client. This is perhaps the only justifiable use of the incumbent concept on the web platform; in all other cases the consequences of using it are simply confusing and we hope to one day switch them to use current or relevant as appropriate.

8.1.3.3.3 Current

The JavaScript specification defines the current Realm Record, sometimes abbreviated to the "current Realm". [JAVASCRIPT]

Then, the current settings object is the environment settings object of the current Realm Record.

Similarly, the current global object is the global object of the current Realm Record.

8.1.3.3.4 Relevant

平台对象相关 Realm它的 [[Realm]] 字段 的值。

平台对象 o相关设置对象o相关 Realm环境设置对象

类似地,平台对象 o相关全局对象orelevant Realm全局对象

8.1.3.4 Enabling and disabling scripting

Scripting is enabled for an environment settings object settings when all of the following conditions are true:

Scripting is disabled for an environment settings object when scripting is not enabled for it, i.e., when any of the above conditions are false.


Scripting is enabled for a node node if node's node document's browsing context is non-null, and scripting is enabled for node's relevant settings object.

Scripting is disabled for a node when scripting is not enabled, i.e., when its node document's browsing context is null or when scripting is disabled for its relevant settings object.

8.1.3.5 Secure contexts

An environment environment is a secure context if the following algorithm returns true:

  1. If environment is an environment settings object, then:

    1. Let global be environment's global object.

    2. If global is a WorkerGlobalScope, then:

      1. If global's owner set[0]'s relevant settings object is a secure context, then return true.

        We only need to check the 0th item since they will necessarily all be consistent.

      2. Return false.

    3. If global is a WorkletGlobalScope, then return true.

      Worklets can only be created in secure contexts.

  2. If the result of Is url potentially trustworthy? given environment's top-level creation URL is "Potentially Trustworthy", then return true.

  3. Return false.

An environment is a non-secure context if it is not a secure context.

8.1.4 Script processing model

8.1.4.1 Scripts

A script is one of two possible structs. All scripts have:

A settings object

An environment settings object, containing various settings that are shared with other scripts in the same context.

A record

Either a Script Record, for classic scripts; a Source Text Module Record, for module scripts; or null. In the former two cases, it represents a parsed script; null represents a failure parsing.

A parse error

A JavaScript value, which has meaning only if the record is null, indicating that the corresponding script source text could not be parsed.

This value is used for internal tracking of immediate parse errors when creating scripts, and is not to be used directly. Instead, consult the error to rethrow when determining "what went wrong" for this script.

An error to rethrow

A JavaScript value representing an error that will prevent evaluation from succeeding. It will be re-thrown by any attempts to run the script.

This could be the script's parse error, but in the case of a module script it could instead be the parse error from one of its dependencies, or an error from resolve a module specifier.

Since this exception value is provided by the JavaScript specification, we know that it is never null, so we use null to signal that no error has occurred.

Fetch options
A script fetch options, containing various options related to fetching this script or module scripts that it imports.
A base URL

A base URL used for resolving module specifiers. This will either be the URL from which the script was obtained, for external scripts, or the document base URL of the containing document, for inline scripts.

A classic script is a type of script that has the following additional item:

A muted errors boolean

A boolean which, if true, means that error information will not be provided for errors in this script. This is used to mute errors for cross-origin scripts, since that can leak private information.

A module script is another type of script. It has no additional items.

The active script is determined by the following algorithm:

  1. Let record be GetActiveScriptOrModule().

  2. If record is null, return null.

  3. Return record.[[HostDefined]].

The active script concept is so far only used by the import() feature, to determine the base URL to use for resolving relative module specifiers.

8.1.4.2 Fetching scripts

This section introduces a number of algorithms for fetching scripts, taking various necessary inputs and resulting in classic or module scripts.


Script fetch options is a struct with the following items:

cryptographic nonce

The cryptographic nonce metadata used for the initial fetch and for fetching any imported modules

integrity metadata

The integrity metadata used for the initial fetch

parser metadata

The parser metadata used for the initial fetch and for fetching any imported modules

credentials mode

The credentials mode used for the initial fetch (for module scripts) and for fetching any imported modules (for both module scripts and classic scripts)

referrer policy

The referrer policy used for the initial fetch and for fetching any imported modules

Recall that via the import() feature, classic scripts can import module scripts.

The default classic script fetch options are a script fetch options whose cryptographic nonce is the empty string, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is "same-origin", and referrer policy is the empty string.

Given a request request and a script fetch options options, we define:

set up the classic script request

Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's integrity metadata, its parser metadata to options's parser metadata, and its referrer policy to options's referrer policy.

set up the module script request

Set request's cryptographic nonce metadata to options's cryptographic nonce, its integrity metadata to options's integrity metadata, its parser metadata to options's parser metadata, its credentials mode to options's credentials mode, and its referrer policy to options's referrer policy.

For any given script fetch options options, the descendant script fetch options are a new script fetch options whose items all have the same values, except for the integrity metadata, which is instead the empty string.


The algorithms below can be customized by optionally supplying a custom perform the fetch hook, which takes a request and an is top-level flag. The algorithm must complete with a response (which may be a network error), either synchronously (when using fetch a classic worker-imported script) or asynchronously (otherwise). The is top-level flag will be set for all classic script fetches, and for the initial fetch when fetching an external module script graph, fetching a module worker script graph, or fetching an import() module script graph, but not for the fetches resulting from import statements encountered throughout the graph.

By default, not supplying the perform the fetch will cause the below algorithms to simply fetch the given request, with algorithm-specific customizations to the request and validations of the resulting response.

To layer your own customizations on top of these algorithm-specific ones, supply a perform the fetch hook that modifies the given request, fetches it, and then performs specific validations of the resulting response (completing with a network error if the validations fail).

The hook can also be used to perform more subtle customizations, such as keeping a cache of responses and avoiding performing a fetch at all.

Service Workers is an example of a specification that runs these algorithms with its own options for the hook. [SW]


Now for the algorithms themselves.

To fetch a classic script given a url, a settings object, some options, a CORS setting, and a character encoding, run these steps. The algorithm will asynchronously complete with either null (on failure) or a new classic script (on success).

  1. Let request be the result of creating a potential-CORS request given url, "script", and CORS setting.

  2. Set request's client to settings object.

  3. Set up the classic script request given request and options.

  4. If the caller specified custom steps to perform the fetch, perform them on request, with the is top-level flag set. Return from this algorithm, and when the custom perform the fetch steps complete with response response, run the remaining steps.

    Otherwise, fetch request. Return from this algorithm, and run the remaining steps as part of the fetch's process response for the response response.

    response can be either CORS-same-origin or CORS-cross-origin. This only affects how error reporting happens.

  5. Set response to response's unsafe response.

  6. If response's type is "error", or response's status is not an ok status, then asynchronously complete this algorithm with null, and return.

    For historical reasons, this algorithm does not include MIME type checking, unlike the other script-fetching algorithms in this section.

  7. If response's Content Type metadata, if any, specifies a character encoding, and the user agent supports that encoding, then set character encoding to that encoding (ignoring the passed-in value).

  8. Let source text be the result of decoding response's body to Unicode, using character encoding as the fallback encoding.

    The decode algorithm overrides character encoding if the file contains a BOM.

  9. Let muted errors be true if response was CORS-cross-origin, and false otherwise.

  10. Let script be the result of creating a classic script given source text, settings object, response's url, options, and muted errors.

  11. Asynchronously complete this algorithm with script.

To fetch a classic worker script given a url, a fetch client settings object, a destination, and a script settings object, run these steps. The algorithm will asynchronously complete with either null (on failure) or a new classic script (on success).

  1. Let request be a new request whose url is url, client is fetch client settings object, destination is destination, mode is "same-origin", credentials mode is "same-origin", parser metadata is "not parser-inserted", and whose use-URL-credentials flag is set.

  2. If the caller specified custom steps to perform the fetch, perform them on request, with the is top-level flag set. Return from this algorithm, and when the custom perform the fetch steps complete with response response, run the remaining steps.

    Otherwise, fetch request. Return from this algorithm, and run the remaining steps as part of the fetch's process response for the response response.

  3. Set response to response's unsafe response.

  4. If either of the following conditions are met:

    then asynchronously complete this algorithm with null, and return.

  5. If both of the following conditions are met:

    then asynchronously complete this algorithm with null, and return.

    Other fetch schemes are exempted from MIME type checking for historical web-compatibility reasons. We might be able to tighten this in the future; see issue #3255.

  6. Let source text be the result of UTF-8 decoding response's body.

  7. Let script be the result of creating a classic script using source text, script settings object, response's url, and the default classic script fetch options.

  8. Asynchronously complete this algorithm with script.

To fetch a classic worker-imported script given a url and a settings object, run these steps. The algorithm will synchronously complete with a classic script on success, or throw an exception on failure.

  1. Let request be a new request whose url is url, client is settings object, destination is "script", parser metadata is "not parser-inserted", synchronous flag is set, and whose use-URL-credentials flag is set.

  2. If the caller specified custom steps to perform the fetch, perform them on request, with the is top-level flag set. Let response be the result.

    Otherwise, fetch request, and let response be the result.

    Unlike other algorithms in this section, the fetching process is synchronous here. Thus any perform the fetch steps will also finish their work synchronously.

  3. Set response to response's unsafe response.

  4. If any of the following conditions are met:

    then throw a "NetworkError" DOMException.

  5. Let source text be the result of UTF-8 decoding response's body.

  6. Let muted errors be true if response was CORS-cross-origin, and false otherwise.

  7. Let script be the result of creating a classic script given source text, settings object, response's url, the default classic script fetch options, and muted errors.

  8. Return script.

To fetch an external module script graph given a url, a settings object, and some options, run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success).

  1. Fetch a single module script given url, settings object, "script", options, settings object, "client", and with the top-level module fetch flag set. If the caller of this algorithm specified custom perform the fetch steps, pass those along as well. Wait until the algorithm asynchronously completes with result.

  2. If result is null, asynchronously complete this algorithm with null, and return.

  3. Let visited set be « url ».

  4. Fetch the descendants of and link result given settings object, destination, and visited set. When this asynchronously completes with final result, asynchronously complete this algorithm with final result.

To fetch an import() module script graph given a specifier, a base URL, a settings object, and some options, run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success).

  1. Let url be the result of resolving a module specifier given base URL and specifier.

  2. If url is failure, then asynchronously complete this algorithm with null, and return.

  3. Fetch a single module script given url, settings object, "script", options, settings object, "client", and with the top-level module fetch flag set. If the caller of this algorithm specified custom perform the fetch steps, pass those along as well. Wait until the algorithm asynchronously completes with result.

  4. If result is null, asynchronously complete this algorithm with null, and return.

  5. Let visited set be « url ».

  6. Fetch the descendants of and link result given settings object, destination, and visited set. When this asynchronously completes with final result, asynchronously complete this algorithm with final result.

To fetch a modulepreload module script graph given a url, a destination, a settings object, and some options, run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success), although it will perform optional steps even after completing.

  1. Fetch a single module script given url, settings object, destination, options, settings object, "client", and with the top-level module fetch flag set. Wait until algorithm asynchronously completes with result.

  2. Asynchronously complete this algorithm with result, but do not return.

  3. If result is not null, optionally perform the following steps:

    1. Let visited set be « url ».

    2. Fetch the descendants of and link result given settings object, destination, and visited set.

    Generally, performing these steps will be beneficial for performance, as it allows pre-loading the modules that will invariably be requested later, via algorithms such as fetch an external module script graph that fetch the entire graph. However, user agents might wish to skip them in bandwidth-constrained situations, or situations where the relevant fetches are already in flight.

To fetch an inline module script graph given a source text, base URL, settings object, and options, run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success).

  1. Let script be the result of creating a module script using source text, settings object, base URL, and options.

  2. If script is null, asynchronously complete this algorithm with null, and return.

  3. Let visited set be an empty set.

  4. Fetch the descendants of and link script, given settings object, the destination "script", and visited set. When this asynchronously completes with final result, asynchronously complete this algorithm with final result.

To fetch a module worker script graph given a url, a fetch client settings object, a destination, a credentials mode, and a module map settings object, fetch a worklet/module worker script graph given url, fetch client settings object, destination, credentials mode, and module map settings object, asynchronously completing with the asynchronous completion result of that algorithm.

To fetch a worklet script graph given a url, a fetch client settings object, a destination, a credentials mode, a module map settings object, and a module responses map, fetch a worklet/module worker script graph given url, fetch client settings object, destination, credentials mode, and module map settings object, asynchronously completing with the asynchronous completion result of that algorithm. Use the following custom steps to perform the fetch given response:

  1. Let requestURL be request's url.

  2. If moduleResponsesMap[requestURL] is "fetching", wait in parallel until that entry's value changes, then queue a task on the networking task source to proceed with running the following steps.

  3. If moduleResponsesMap[requestURL] exists, then asynchronously complete the perform the fetch steps with moduleResponsesMap[requestURL].

  4. Set moduleResponsesMap[requestURL] to "fetching".

  5. Fetch request. To process response for the response response:

    1. Set moduleResponsesMap[requestURL] to response.

    2. Asynchronously complete the perform the fetch steps with response.


The following algorithms are meant for internal use by this specification only as part of fetching an external module script graph or other similar concepts above, and should not be used directly by other specifications.

This diagram illustrates how these algorithms relate to the ones above, as well as to each other:

fetch an external module script graph fetch an import() module script graph fetch a modulepreload module script graph fetch an inline module script graph fetch a module worker script graph fetch a worklet script graph fetch a worklet/module worker script graph fetch the descendants of and link a module script fetch the descendants of a module script internal module script graph fetching procedure

To fetch a worklet/module worker script graph given a url, a fetch client settings object, a destination, a credentials mode, and a module map settings object, run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success).

  1. Let options be a script fetch options whose cryptographic nonce is the empty string, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is credentials mode, and referrer policy is the empty string.

  2. Fetch a single module script given url, fetch client settings object, destination, options, module map settings object, "client", and with the top-level module fetch flag set. If the caller of this algorithm specified custom perform the fetch steps, pass those along as well. Wait until the algorithm asynchronously completes with result.

  3. If result is null, asynchronously complete this algorithm with null, and return.

  4. Let visited set be « url ».

  5. Fetch the descendants of and link result given fetch client settings object, destination, and visited set. When this asynchronously completes with final result, asynchronously complete this algorithm with final result.

To fetch the descendants of and link a module script module script, given a fetch client settings object, a destination, and a visited set, run these steps. The algorithm will asynchronously complete with either null (on failure) or with module script (on success).

  1. Fetch the descendants of module script, given fetch client settings object, destination, and visited set.

  2. Return from this algorithm, and run the following steps when fetching the descendants of a module script asynchronously completes with result.

  3. If result is null, then asynchronously complete this algorithm with result.

    In this case, there was an error fetching one or more of the descendants. We will not attempt to link.

  4. Let parse error be the result of finding the first parse error given result.

  5. If parse error is null, then:

    1. Let record be result's record.

    2. Perform record.Link().

      This step will recursively call Link on all of the module's unlinked dependencies.

      If this throws an exception, set result's error to rethrow to that exception.

  6. Otherwise, set result's error to rethrow to parse error.

  7. Asynchronously complete this algorithm with result.

To fetch the descendants of a module script module script, given a fetch client settings object, a destination, and a visited set, run these steps. The algorithm will asynchronously complete with either null (on failure) or with module script (on success).

  1. If module script's record is null, then asynchronously complete this algorithm with module script and return.

  2. Let record be module script's record.

  3. If record is not a Cyclic Module Record, or if record.[[RequestedModules]] is empty, asynchronously complete this algorithm with module script.

  4. Let urls be a new empty list.

  5. For each string requested of record.[[RequestedModules]],

    1. Let url be the result of resolving a module specifier given module script's base URL and requested.

    2. Assert: url is never failure, because resolving a module specifier must have been previously successful with these same two arguments.

    3. If visited set does not contain url, then:

      1. Append url to urls.

      2. Append url to visited set.

  6. Let options be the descendant script fetch options for module script's fetch options.

  7. Assert: options is not null, as module script is a module script.

  8. For each url in urls, perform the internal module script graph fetching procedure given url, fetch client settings object, destination, options, module script's settings object, visited set, and module script's base URL. If the caller of this algorithm specified custom perform the fetch steps, pass those along while performing the internal module script graph fetching procedure.

    These invocations of the internal module script graph fetching procedure should be performed in parallel to each other.

    If any of the invocations of the internal module script graph fetching procedure asynchronously complete with null, asynchronously complete this algorithm with null, and return.

    Otherwise, wait until all of the internal module script graph fetching procedure invocations have asynchronously completed. Asynchronously complete this algorithm with module script.

To perform the internal module script graph fetching procedure given a url, a fetch client settings object, a destination, some options, a module map settings object, a visited set, and a referrer, perform these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success).

  1. Assert: visited set contains url.

  2. Fetch a single module script given url, fetch client settings object, destination, options, module map settings object, referrer, and with the top-level module fetch flag unset. If the caller of this algorithm specified custom perform the fetch steps, pass those along while fetching a single module script.

  3. Return from this algorithm, and run the following steps when fetching a single module script asynchronously completes with result:

  4. If result is null, asynchronously complete this algorithm with null, and return.

  5. Fetch the descendants of result given fetch client settings object, destination, and visited set.

  6. When the appropriate algorithm asynchronously completes with final result, asynchronously complete this algorithm with final result.

To fetch a single module script, given a url, a fetch client settings object, a destination, some options, a module map settings object, a referrer, and a top-level module fetch flag, run these steps. The algorithm will asynchronously complete with either null (on failure) or a module script (on success).

  1. Let moduleMap be module map settings object's module map.

  2. If moduleMap[url] is "fetching", wait in parallel until that entry's value changes, then queue a task on the networking task source to proceed with running the following steps.

  3. If moduleMap[url] exists, asynchronously complete this algorithm with moduleMap[url], and return.

  4. Set moduleMap[url] to "fetching".

  5. Let request be a new request whose url is url, destination is destination, mode is "cors", referrer is referrer, and client is fetch client settings object.

  6. If destination is "worker" or "sharedworker" and the top-level module fetch flag is set, then set request's mode to "same-origin".

  7. Set up the module script request given request and options.

  8. If the caller specified custom steps to perform the fetch, perform them on request, setting the is top-level flag if the top-level module fetch flag is set. Return from this algorithm, and when the custom perform the fetch steps complete with response response, run the remaining steps.

    Otherwise, fetch request. Return from this algorithm, and run the remaining steps as part of the fetch's process response for the response response.

    response is always CORS-same-origin.

  9. If any of the following conditions are met:

    then set moduleMap[url] to null, asynchronously complete this algorithm with null, and return.

  10. Let source text be the result of UTF-8 decoding response's body.

  11. Let module script be the result of creating a module script given source text, module map settings object, response's url, and options.

  12. Set moduleMap[url] to module script, and asynchronously complete this algorithm with module script.

    It is intentional that the module map is keyed by the request URL, whereas the base URL for the module script is set to the response URL. The former is used to deduplicate fetches, while the latter is used for URL resolution.

To find the first parse error given a root moduleScript and an optional discoveredSet:

  1. Let moduleMap be moduleScript's settings object's module map.

  2. If discoveredSet was not given, let it be an empty set.

  3. Append moduleScript to discoveredSet.

  4. If moduleScript's record is null, then return moduleScript's parse error.

  5. Let childSpecifiers be the value of moduleScript's record's [[RequestedModules]] internal slot.

  6. Let childURLs be the list obtained by calling resolve a module specifier once for each item of childSpecifiers, given moduleScript's base URL and that item. (None of these will ever fail, as otherwise moduleScript would have been marked as itself having a parse error.)

  7. Let childModules be the list obtained by getting each value in moduleMap whose key is given by an item of childURLs.

  8. For each childModule of childModules:

    1. Assert: childModule is a module script (i.e., it is not "fetching" or null); by now all module scripts in the graph rooted at moduleScript will have successfully been fetched.

    2. If discoveredSet already contains childModule, continue.

    3. Let childParseError be the result of finding the first parse error given childModule and discoveredSet.

    4. If childParseError is not null, return childParseError.

  9. Return null.

8.1.4.3 Creating scripts

To create a classic script, given a string source, an environment settings object settings, a URL baseURL, some script fetch options options, and an optional muted errors boolean:

  1. If muted errors was not provided, let it be false.

  2. If muted errors is true, then set baseURL to about:blank.

    When muted errors is true, baseURL is the script's CORS-cross-origin response's url, which shouldn't be exposed to JavaScript. Therefore, baseURL is sanitized here.

  3. If scripting is disabled for settings, then set source to the empty string.

  4. Let script be a new classic script that this algorithm will subsequently initialize.

  5. Set script's settings object to settings.

  6. Set script's base URL to baseURL.

  7. Set script's fetch options to options.

  8. Set script's muted errors to muted errors.

  9. Set script's parse error and error to rethrow to null.

  10. Let result be ParseScript(source, settings's Realm, script).

    Passing script as the last parameter here ensures result.[[HostDefined]] will be script.

  11. If result is a list of errors, then:

    1. Set script's parse error and its error to rethrow to result[0].

    2. Return script.

  12. Set script's record to result.

  13. Return script.

To create a module script, given a string source, an environment settings object settings, a URL baseURL, and some script fetch options options:

  1. If scripting is disabled for settings, then set source to the empty string.

  2. Let script be a new module script that this algorithm will subsequently initialize.

  3. Set script's settings object to settings.

  4. Set script's base URL to baseURL.

  5. Set script's fetch options to options.

  6. Set script's parse error and error to rethrow to null.

  7. Let result be ParseModule(source, settings's Realm, script).

    Passing script as the last parameter here ensures result.[[HostDefined]] will be script.

  8. If result is a list of errors, then:

    1. Set script's parse error to result[0].

    2. Return script.

  9. For each string requested of result.[[RequestedModules]]:

    1. Let url be the result of resolving a module specifier given script's base URL and requested.

    2. If url is failure, then:

      1. Let error be a new TypeError exception.

      2. Set script's parse error to error.

      3. Return script.

    This step is essentially validating all of the requested module specifiers. We treat a module with unresolvable module specifiers the same as one that cannot be parsed; in both cases, a syntactic issue makes it impossible to ever contemplate linking the module later.

  10. Set script's record to result.

  11. Return script.

8.1.4.4 Calling scripts

To run a classic script given a classic script script and an optional rethrow errors boolean:

  1. If rethrow errors is not given, let it be false.

  2. Let settings be the settings object of script.

  3. Check if we can run script with settings. If this returns "do not run" then return NormalCompletion(empty).

  4. Prepare to run script given settings.

  5. Let evaluationStatus be null.

  6. If script's error to rethrow is not null, then set evaluationStatus to Completion { [[Type]]: throw, [[Value]]: script's error to rethrow, [[Target]]: empty }.

  7. Otherwise, set evaluationStatus to ScriptEvaluation(script's record).

    If ScriptEvaluation does not complete because the user agent has aborted the running script, leave evaluationStatus as null.

  8. If evaluationStatus is an abrupt completion, then:

    1. If rethrow errors is true and script's muted errors is false, then:

      1. Clean up after running script with settings.

      2. Rethrow evaluationStatus.[[Value]].

    2. If rethrow errors is true and script's muted errors is true, then:

      1. Clean up after running script with settings.

      2. Throw a "NetworkError" DOMException.

    3. Otherwise, rethrow errors is false. Perform the following steps:

      1. Report the exception given by evaluationStatus.[[Value]] for script.

      2. Clean up after running script with settings.

      3. Return evaluationStatus.

  9. Clean up after running script with settings.

  10. If evaluationStatus is a normal completion, then return evaluationStatus.

  11. If we've reached this point, evaluationStatus was left as null because the script was aborted prematurely during evaluation. Return Completion { [[Type]]: throw, [[Value]]: a new "QuotaExceededError" DOMException, [[Target]]: empty }.

To run a module script given a module script script, with an optional rethrow errors boolean:

  1. If rethrow errors is not given, let it be false.

  2. Let settings be the settings object of script.

  3. Check if we can run script with settings. If this returns "do not run" then return NormalCompletion(empty).

  4. Prepare to run script given settings.

  5. Let evaluationStatus be null.

  6. If script's error to rethrow is not null, then set evaluationStatus to Completion { [[Type]]: throw, [[Value]]: script's error to rethrow, [[Target]]: empty }.

  7. Otherwise:

    1. Let record be script's record.

    2. Set evaluationStatus to record.Evaluate().

      This step will recursively evaluate all of the module's dependencies.

      If Evaluate fails to complete as a result of the user agent aborting the running script, then set evaluationStatus to Completion { [[Type]]: throw, [[Value]]: a new "QuotaExceededError" DOMException, [[Target]]: empty }.

  8. If evaluationStatus is an abrupt completion, then:

    1. If rethrow errors is true, rethrow the exception given by evaluationStatus.[[Value]].

    2. Otherwise, report the exception given by evaluationStatus.[[Value]] for script.

  9. Clean up after running script with settings.

  10. Return evaluationStatus.

The steps to check if we can run script with an environment settings object settings are as follows. They return either "run" or "do not run".

  1. If the global object specified by settings is a Window object whose Document object is not fully active, then return "do not run".

  2. If scripting is disabled for settings, then return "do not run".

  3. Return "run".

The steps to prepare to run script with an environment settings object settings are as follows:

  1. Push settings's realm execution context onto the JavaScript execution context stack; it is now the running JavaScript execution context.

  2. Add settings to the currently running task's script evaluation environment settings object set.

The steps to clean up after running script with an environment settings object settings are as follows:

  1. Assert: settings's realm execution context is the running JavaScript execution context.

  2. Remove settings's realm execution context from the JavaScript execution context stack.

  3. If the JavaScript execution context stack is now empty, perform a microtask checkpoint. (If this runs scripts, these algorithms will be invoked reentrantly.)

These algorithms are not invoked by one script directly calling another, but they can be invoked reentrantly in an indirect manner, e.g. if a script dispatches an event which has event listeners registered.

The running script is the script in the [[HostDefined]] field in the ScriptOrModule component of the running JavaScript execution context.

8.1.4.5 Killing scripts

Although the JavaScript specification does not account for this possibility, it's sometimes necessary to abort a running script. This causes any ScriptEvaluation or Source Text Module Record Evaluate invocations to cease immediately, emptying the JavaScript execution context stack without triggering any of the normal mechanisms like finally blocks. [JAVASCRIPT]

User agents may impose resource limitations on scripts, for example CPU quotas, memory limits, total execution time limits, or bandwidth limitations. When a script exceeds a limit, the user agent may either throw a "QuotaExceededError" DOMException, abort the script without an exception, prompt the user, or throttle script execution.

For example, the following script never terminates. A user agent could, after waiting for a few seconds, prompt the user to either terminate the script or let it continue.

<script>
 while (true) { /* loop */ }
</script>

User agents are encouraged to allow users to disable scripting whenever the user is prompted either by a script (e.g. using the window.alert() API) or because of a script's actions (e.g. because it has exceeded a time limit).

If scripting is disabled while a script is executing, the script should be terminated immediately.

User agents may allow users to specifically disable scripts just for the purposes of closing a browsing context.

For example, the prompt mentioned in the example above could also offer the user with a mechanism to just close the page entirely, without running any unload event handlers.

8.1.4.6 Runtime script errors

reportError

Support in all current engines.

Firefox93+Safari15.4+Chrome95+
Opera81+Edge95+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android93+Safari iOS15.4+Chrome Android95+WebView Android95+Samsung Internet17.0+Opera Android67+

When the user agent is required to report an error for a particular script script with a particular position line:col, using a particular target target, it must run these steps, after which the error is either handled or not handled:

  1. If target is in error reporting mode, then return; the error is not handled.

  2. Let target be in error reporting mode.

  3. (This is a tracking vector.) Let message be an implementation-defined string describing the error in a helpful manner.

  4. Let errorValue be the value that represents the error: in the case of an uncaught exception, that would be the value that was thrown; in the case of a JavaScript error that would be an Error object. If there is no corresponding value, then the null value must be used instead.

  5. Let urlString be the result of applying the URL serializer to the URL record that corresponds to the resource from which script was obtained.

    The resource containing the script will typically be the file from which the Document was parsed, e.g. for inline script elements or event handler content attributes; or the JavaScript file that the script was in, for external scripts. Even for dynamically-generated scripts, user agents are strongly encouraged to attempt to keep track of the original source of a script. For example, if an external script uses the document.write() API to insert an inline script element during parsing, the URL of the resource containing the script would ideally be reported as being the external script, and the line number might ideally be reported as the line with the document.write() call or where the string passed to that call was first constructed. Naturally, implementing this can be somewhat non-trivial.

    User agents are similarly encouraged to keep careful track of the original line numbers, even in the face of document.write() calls mutating the document as it is parsed, or event handler content attributes spanning multiple lines.

  6. If script's muted errors is true, then set message to "Script error.", urlString to the empty string, line and col to 0, and errorValue to null.

  7. Let notHandled be true.

  8. If target implements EventTarget, then set notHandled to the result of firing an event named error at target, using ErrorEvent, with the cancelable attribute initialized to true, the message attribute initialized to message, the filename attribute initialized to urlString, the lineno attribute initialized to line, the colno attribute initialized to col, and the error attribute initialized to errorValue.

  9. Let target no longer be in error reporting mode.

  10. If notHandled is false, then the error is handled. Otherwise, the error is not handled.

    Returning true in an event handler cancels the event per the event handler processing algorithm.

When the user agent is to report an exception E, the user agent must report the error for the relevant script, with the problematic position (line number and column number) in the resource containing the script, using the global object specified by the script's settings object as the target. If the error is still not handled after this, then the error may be reported to a developer console.

The existence of both report an error and report an exception is confusing, and both algorithms have known problems. You can track future cleanup in this area in issue #958.

ErrorEvent

Support in all current engines.

Firefox27+Safari6+Chrome10+
Opera11+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android27+Safari iOS6+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+

The ErrorEvent interface is defined as follows:

[Exposed=(Window,Worker)]
interface ErrorEvent : Event {
  constructor(DOMString type, optional ErrorEventInit eventInitDict = {});

  readonly attribute DOMString message;
  readonly attribute USVString filename;
  readonly attribute unsigned long lineno;
  readonly attribute unsigned long colno;
  readonly attribute any error;
};

dictionary ErrorEventInit : EventInit {
  DOMString message = "";
  USVString filename = "";
  unsigned long lineno = 0;
  unsigned long colno = 0;
  any error = null;
};

The message attribute must return the value it was initialized to. It represents the error message.

The filename attribute must return the value it was initialized to. It represents the URL of the script in which the error originally occurred.

The lineno attribute must return the value it was initialized to. It represents the line number where the error occurred in the script.

The colno attribute must return the value it was initialized to. It represents the column number where the error occurred in the script.

The error attribute must return the value it was initialized to. Where appropriate, it is set to the object representing the error (e.g., the exception object in the case of an uncaught DOM exception).

8.1.4.7 Unhandled promise rejections

Window/rejectionhandled_event

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera36+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS11.3+Chrome Android49+WebView Android49+Samsung Internet5.0+Opera Android36+

In addition to synchronous runtime script errors, scripts may experience asynchronous promise rejections, tracked via the unhandledrejection and rejectionhandled events. Tracking these rejections is done via the HostPromiseRejectionTracker abstract operation, but reporting them is defined here.

To notify about rejected promises on a given environment settings object settings object:

  1. Let list be a copy of settings object's about-to-be-notified rejected promises list.

  2. If list is empty, return.

  3. Clear settings object's about-to-be-notified rejected promises list.

  4. Let global be settings object's global object.

  5. Queue a global task on the DOM manipulation task source given global to run the following substep:

    1. For each promise p in list:

      1. If p's [[PromiseIsHandled]] internal slot is true, continue to the next iteration of the loop.

      2. Let notHandled be the result of firing an event named unhandledrejection at global , using PromiseRejectionEvent, with the cancelable attribute initialized to true, the promise attribute initialized to p, and the reason attribute initialized to the value of p's [[PromiseResult]] internal slot.

      3. If notHandled is false, then the promise rejection is handled. Otherwise, the promise rejection is not handled.

      4. If p's [[PromiseIsHandled]] internal slot is false, add p to settings object's outstanding rejected promises weak set.

This algorithm results in promise rejections being marked as handled or not handled. These concepts parallel handled and not handled script errors. If a rejection is still not handled after this, then the rejection may be reported to a developer console.

PromiseRejectionEvent

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera36+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS11.3+Chrome Android49+WebView Android49+Samsung Internet5.0+Opera Android36+

The PromiseRejectionEvent interface is defined as follows:

[Exposed=(Window,Worker)]
interface PromiseRejectionEvent : Event {
  constructor(DOMString type, PromiseRejectionEventInit eventInitDict);

  readonly attribute Promise<any> promise;
  readonly attribute any reason;
};

dictionary PromiseRejectionEventInit : EventInit {
  required Promise<any> promise;
  any reason;
};

PromiseRejectionEvent/promise

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera36+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS11.3+Chrome Android49+WebView Android49+Samsung Internet5.0+Opera Android36+

The promise attribute must return the value it was initialized to. It represents the promise which this notification is about.

PromiseRejectionEvent/reason

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera36+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS11.3+Chrome Android49+WebView Android49+Samsung Internet5.0+Opera Android36+

The reason attribute must return the value it was initialized to. It represents the rejection reason for the promise.

8.1.5 JavaScript specification host hooks

The JavaScript specification contains a number of implementation-defined abstract operations, that vary depending on the host environment. This section defines them for user agent hosts.

8.1.5.1 HostEnqueuePromiseJob(job, realm)

JavaScript contains an implementation-defined HostEnqueuePromiseJob(job, realm) abstract operation to schedule Promise-related operations. HTML schedules these operations in the microtask queue. User agents must use the following implementation: [JAVASCRIPT]

  1. If realm is not null, then let job settings be the settings object for realm. Otherwise, let job settings be null.

    If realm is not null, it is the Realm of the author code that will run. When job is returned by NewPromiseReactionJob, it is the realm of the promise's handler function. When job is returned by NewPromiseResolveThenableJob, it is the realm of the then function.

    If realm is null, either no author code will run or author code is guaranteed to throw. For the former, the author may not have passed in code to run, such as in promise.then(null, null). For the latter, it is because a revoked Proxy was passed. In both cases, all the steps below that would otherwise use job settings get skipped.

  2. Let incumbent settings be the incumbent settings object.

  3. Let active script be the active script.

  4. Let script execution context be null.

  5. If active script is not null, set script execution context to a new JavaScript execution context, with its Function field set to null, its Realm field set to active script's settings object's Realm, and its ScriptOrModule set to active script's record.

    As seen below, this is used in order to propagate the current active script forward to the time when the job is executed.

    A case where active script is non-null, and saving it in this way is useful, is the following:

    Promise.resolve('import(`./example.mjs`)').then(eval);

    Without this step (and the steps below that use it), there would be no active script when the import() expression is evaluated, since eval() is a built-in function that does not originate from any particular script.

    With this step in place, the active script is propagated from the above code into the job, allowing import() to use the original script's base URL appropriately.

    active script can be null if the user clicks on the following button:

    <button onclick="Promise.resolve('import(`./example.mjs`)').then(eval)">Click me</button>

    In this case, the JavaScript function for the event handler will be created by the get the current value of the event handler algorithm, which creates a function with null [[ScriptOrModule]] value. Thus, when the promise machinery calls HostEnqueuePromiseJob, there will be no active script to pass along.

    As a consequence, this means that when the import() expression is evaluated, there will still be no active script. Fortunately that is handled by our implementations of HostResolveImportedModule and HostImportModuleDynamically, by falling back to using the current settings object's API base URL.

  6. Queue a microtask on the surrounding agent's event loop to perform the following steps:

    1. If job settings is not null, then check if we can run script with job settings. If this returns "do not run" then return.

    2. If job settings is not null, then prepare to run script with job settings.

      This affects the entry concept while the job runs.

    3. Prepare to run a callback with incumbent settings.

      This affects the incumbent concept while the job runs.

    4. If script execution context is not null, then push script execution context onto the JavaScript execution context stack.

      As explained above, this affects the active script while the job runs.

    5. Let result be job().

      job is an abstract closure returned by NewPromiseReactionJob or NewPromiseResolveThenableJob.

    6. If script execution context is not null, then pop script execution context from the JavaScript execution context stack.

    7. Clean up after running a callback with incumbent settings.

    8. If job settings is not null, then clean up after running script with job settings.

    9. If result is an abrupt completion, then report the exception given by result.[[Value]].

8.1.5.2 HostEnsureCanCompileStrings(callerRealm, calleeRealm)

JavaScript contains an implementation-defined HostEnsureCanCompileStrings(callerRealm, calleeRealm) abstract operation. User agents must use the following implementation: [JAVASCRIPT]

  1. Perform ? EnsureCSPDoesNotBlockStringCompilation(callerRealm, calleeRealm). [CSP]

8.1.5.3 HostPromiseRejectionTracker(promise, operation)

JavaScript contains an implementation-defined HostPromiseRejectionTracker(promise, operation) abstract operation. User agents must use the following implementation: [JAVASCRIPT]

  1. Let script be the running script.

  2. If script's muted errors is true, terminate these steps.

  3. Let settings object be script's settings object.

  4. If operation is "reject",

    1. Add promise to settings object's about-to-be-notified rejected promises list.

  5. If operation is "handle",

    1. If settings object's about-to-be-notified rejected promises list contains promise, then remove promise from that list and return.

    2. If settings object's outstanding rejected promises weak set does not contain promise, then return.

    3. Remove promise from settings object's outstanding rejected promises weak set.

    4. Let global be settings object's global object.

    5. Queue a global task on the DOM manipulation task source given global to fire an event named rejectionhandled at global, using PromiseRejectionEvent, with the promise attribute initialized to promise, and the reason attribute initialized to the value of promise's [[PromiseResult]] internal slot.

8.1.5.4 Module-related host hooks

The JavaScript specification defines a syntax for modules, as well as some host-agnostic parts of their processing model. This specification defines the rest of their processing model: how the module system is bootstrapped, via the script element with type attribute set to "module", and how modules are fetched, resolved, and executed. [JAVASCRIPT]

Although the JavaScript specification speaks in terms of "scripts" versus "modules", in general this specification speaks in terms of classic scripts versus module scripts, since both of them use the script element.

modulePromise = import(specifier)

Returns a promise for the module namespace object for the module script identified by specifier. This allows dynamic importing of module scripts at runtime, instead of statically using the import statement form. The specifier will be resolved relative to the active script's base URL.

The returned promise will be rejected if an invalid specifier is given, or if a failure is encountered while fetching or evaluating the resulting module graph.

This syntax can be used inside both classic and module scripts. It thus provides a bridge into the module-script world, from the classic-script world.

url = import . meta . url

Returns the active module script's base URL.

This syntax can only be used inside module scripts.

A module map is a map of URL records to values that are either a module script, null (used to represent failed fetches), or a placeholder value "fetching". Module maps are used to ensure that imported JavaScript modules are only fetched, parsed, and evaluated once per Document or worker.

Since module maps are keyed by URL, the following code will create three separate entries in the module map, since it results in three different URLs:

import "https://example.com/module.mjs";
import "https://example.com/module.mjs#map-buster";
import "https://example.com/module.mjs?debug=true";

That is, URL queries and fragments can be varied to create distinct entries in the module map; they are not ignored. Thus, three separate fetches and three separate module evaluations will be performed.

In contrast, the following code would only create a single entry in the module map, since after applying the URL parser to these inputs, the resulting URL records are equal:

import "https://example.com/module2.mjs";
import "https:example.com/module2.mjs";
import "https://///example.com\\module2.mjs";
import "https://example.com/foo/../module2.mjs";

So in this second example, only one fetch and one module evaluation will occur.

Note that this behavior is the same as how shared workers are keyed by their parsed constructor url.

To resolve a module specifier given a URL base URL and a string specifier, perform the following steps. It will return either a URL record or failure.

  1. Apply the URL parser to specifier. If the result is not failure, return the result.

  2. If specifier does not start with the character U+002F SOLIDUS (/), the two-character sequence U+002E FULL STOP, U+002F SOLIDUS (./), or the three-character sequence U+002E FULL STOP, U+002E FULL STOP, U+002F SOLIDUS (../), return failure.

    This restriction is in place so that in the future we can allow custom module loaders to give special meaning to "bare" import specifiers, like import "jquery" or import "web/crypto". For now any such imports will fail, instead of being treated as relative URLs.

  3. Return the result of applying the URL parser to specifier with base URL as the base URL.

The following are valid module specifiers according to the above algorithm:

The following are valid module specifiers according to the above algorithm, but will invariably cause failures when they are fetched:

The following are not valid module specifiers according to the above algorithm:

8.1.5.4.1 HostGetImportMetaProperties(moduleRecord)

Reference/Statements/import.meta

Support in all current engines.

Firefox62+Safari11.1+Chrome64+
Opera51+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android62+Safari iOS12+Chrome Android64+WebView Android64+Samsung Internet9.0+Opera Android47+

JavaScript contains an implementation-defined HostGetImportMetaProperties abstract operation. User agents must use the following implementation: [JAVASCRIPT]

  1. Let module script be moduleRecord.[[HostDefined]].

  2. Let urlString be module script's base URL, serialized.

  3. Return « Record { [[Key]]: "url", [[Value]]: urlString } ».

8.1.5.4.2 HostImportModuleDynamically(referencingScriptOrModule, specifier, promiseCapability)

JavaScript contains an implementation-defined HostImportModuleDynamically abstract operation. User agents must use the following implementation: [JAVASCRIPT]

  1. Let settings object be the current settings object.

  2. If settings object's global object implements WorkletGlobalScope, then:

    1. Let completion be Completion { [[Type]]: throw, [[Value]]: a new TypeError, [[Target]]: empty }.

    2. Perform FinishDynamicImport(referencingScriptOrModule, specifier, promiseCapability, completion).

    3. Return.

  3. Let base URL be settings object's API base URL.

  4. Let fetch options be the default classic script fetch options.

  5. If referencingScriptOrModule is not null, then:

    1. Let referencing script be referencingScriptOrModule.[[HostDefined]].

    2. Set settings object to referencing script's settings object.

    3. Set base URL to referencing script's base URL.

    4. Set fetch options to the descendant script fetch options for referencing script's fetch options.

    As explained above for HostResolveImportedModule, in the common case, referencingScriptOrModule is non-null.

  6. Fetch an import() module script graph given specifier, base URL, settings object, and fetch options. Wait until the algorithm asynchronously completes with result.

  7. If result is null, then:

    1. Let completion be Completion { [[Type]]: throw, [[Value]]: a new TypeError, [[Target]]: empty }.

    2. Perform FinishDynamicImport(referencingScriptOrModule, specifier, promiseCapability, completion).

    3. Return.

  8. Run the module script result, with the rethrow errors boolean set to true.

  9. If running the module script throws an exception, then perform FinishDynamicImport(referencingScriptOrModule, specifier, promiseCapability, the thrown exception completion).

  10. Otherwise, perform FinishDynamicImport(referencingScriptOrModule, specifier, promiseCapability, NormalCompletion(undefined)).

  11. Return undefined.

8.1.5.4.3 HostResolveImportedModule(referencingScriptOrModule, specifier)

JavaScript contains an implementation-defined HostResolveImportedModule abstract operation. User agents must use the following implementation: [JAVASCRIPT]

  1. Let settings object be the current settings object.

  2. Let base URL be settings object's API base URL.

  3. If referencingScriptOrModule is not null, then:

    1. Let referencing script be referencingScriptOrModule.[[HostDefined]].

    2. Set settings object to referencing script's settings object.

    3. Set base URL to referencing script's base URL.

    referencingScriptOrModule is not usually null, but will be so for event handlers per the get the current value of the event handler algorithm. For example, given:

    <button onclick="import('./foo.mjs')">Click me</button>

    If a click event occurs, then at the time the import() expression runs, GetActiveScriptOrModule will return null, which will be passed to this abstract operation when HostResolveImportedModule is called by FinishDynamicImport.

  4. Let moduleMap be settings object's module map.

  5. Let url be the result of resolving a module specifier given base URL and specifier.

  6. Assert: url is never failure, because resolving a module specifier must have been previously successful with these same two arguments (either while creating the corresponding module script, or in fetch an import() module script graph).

  7. Let resolved module script be moduleMap[url]. (This entry must exist for us to have gotten to this point.)

  8. Assert: resolved module script is a module script (i.e., is not null or "fetching").

  9. Assert: resolved module script's record is not null.

  10. Return resolved module script's record.

8.1.6 事件循环

8.1.6.1 定义

为了协调事件、用户交互、脚本、渲染、网络等,用户代理必须使用本节描述的 事件循环。 每个 代理 有一个关联的 事件循环,它对每个代理是唯一的。

similar-origin 窗口代理事件循环 称为 窗口事件循环专用工作线程代理共享工作线程代理service worker 代理事件循环 称为 worker 事件循环worklet 代理事件循环 称为 worklet 事件循环

事件循环 不一定对应于实现上的线程。例如多个 窗口事件循环 可以在同一个线程里调度。

但是对于 [[CanBlock]] 设置为真的各种 代理, JavaScript 标准对 forward progress 提出了要求,这种情况下事实上要求了每个代理有自己的线程。


事件循环 有一个或更多的 任务队列任务队列 是一个 任务集合

任务队列集合 而非 队列, 因为 事件循环处理模型的第一步 会从选中的队列中取第一个 可运行 任务,而不是 出列 第一个任务。

微任务队列 不是 任务队列

任务封装的算法负责类似这样的工作:

事件

在特定的 EventTarget 上派发一个 Event 对象, 通常由专门的任务完成。

不是所有事件都是由 任务队列 派发的, 很多是在其他任务执行过程中派发的。

解析

HTML 解析器 标记化一个或更多字节, 然后处理结果标记。这通常是一个任务。

回调

调用一个回调通常是由专用任务来完成的。

使用资源

当一个算法 获取 一个资源时,如果获取发生在一个非阻塞的情况, 那么一旦某个或全部资源可用,对资源的处理由一个任务来执行。

对 DOM 操作作出反应

有些元素在 DOM 操作时会触发一些任务,例如当元素 插入到文档中 时。

形式化地,任务 是一个具有如下属性的 结构 结构:

steps
一系列的步骤,指定了要完成的工作。
source
任务来源 之一,用于分组和序列化相关任务。
document
和任务关联的 Document,对于不在 窗口事件循环 里的任务为 null。
脚本执行环境设置对象集合
用于在任务期间跟踪脚本执行的 环境设置对象集合

任务可执行的 当且仅当它的 document 为 null 或 完全激活

至于它的 source 字段,每个 任务 都来自一个特定的 任务源事件循环 中的每个 任务源 必须关联 特定的 任务队列

本质上,任务源 用于分离逻辑上不同类型的任务,用户代理可能希望区分它们。 用户代理使用 任务队列 来在给定的 事件循环 内合并任务源。

例如,用户代理可能有一个管理鼠标和键盘事件的 任务队列 (与之关联的是 用户交互任务源),以及另一个和其他所有 任务源 关联的任务队列。然后利用 事件循环处理模型 的初始化步骤提供的自由, 它可以优先处理键盘和鼠标事件,比其他任务多四分之三的时间。这样可以在不让其他任务队列饥饿的情况下保持 UI 可响应。 注意在这个配置下,处理模型仍然强制用户代理不会乱序执行任意 任务源 里的时间。


每个 事件循环 有一个 当前正在执行的任务, 它是一个 任务 或 null,初始为 null。用来处理再进入的情况。

每个 事件循环 有一个 微任务队列, 它是一个 微任务队列,初始为空。 微任务 是一个通俗的叫法,指由 入队微任务 算法创建的 任务

每个 事件循环 有一个 执行微任务检查点 布尔, 初始为假。它用来防止重新进入 微任务检查点 的调用。

8.1.6.2 Queuing tasks

To queue a task on a task source source, which performs a series of steps steps, optionally given an event loop event loop and a document document:

  1. If event loop was not given, set event loop to the implied event loop.

  2. If document was not given, set document to the implied document.

  3. Let task be a new task.

  4. Set task's steps to steps.

  5. Set task's source to source.

  6. Set task's document to the document.

  7. Set task's script evaluation environment settings object set to an empty set.

  8. Let queue be the task queue to which source is associated on event loop.

  9. Append task to queue.

To queue a global task on a task source source, with a global object global and a series of steps steps:

  1. Let event loop be global's relevant agent's event loop.

  2. Let document be global's associated Document, if global is a Window object; otherwise null.

  3. Queue a task given source, event loop, document, and steps.

To queue an element task on a task source source, with an element element and a series of steps steps:

  1. Let global be element's relevant global object.

  2. Queue a global task given source, global, and steps.

To queue a microtask which performs a series of steps steps, optionally given an event loop event loop and a document document:

  1. If event loop was not given, set event loop to the implied event loop.

  2. If document was not given, set document to the implied document.

  3. Let microtask be a new task.

  4. Set microtask's steps to steps.

  5. Set microtask's source to the microtask task source.

  6. Set microtask's document to document.

  7. Set task's script evaluation environment settings object set to an empty set.

  8. Enqueue task on event loop's microtask queue.

It is possible for a microtask to be moved to a regular task queue, if, during its initial execution, it spins the event loop. This is the only case in which the source, document, and script evaluation environment settings object set of the microtask are consulted; they are ignored by the perform a microtask checkpoint algorithm.

The implied event loop when queuing a task is the one that can deduced from the context of the calling algorithm. This is generally unambiguous, as most specification algorithms only ever involve a single agent (and thus a single event loop). The exception is algorithms involving or specifying cross-agent communication (e.g., between a window and a worker); for those cases, the implied event loop concept must not be relied upon and specifications must explicitly provide an event loop when queuing a task or microtask.

The implied document when queuing a task on an event loop event loop is determined as follows:

  1. If event loop is not a window event loop, then return null.

  2. If the task is being queued in the context of an element, then return the element's node document.

  3. If the task is being queued in the context of a browsing context, then return the browsing context's active document.

  4. If the task is being queued by or for a script, then return the script's settings object's responsible document.

  5. Assert: this step is never reached, because one of the previous conditions must be true. Really?

Both implied event loop and implied document are vaguely-defined and have a lot of action-at-a-distance. Perhaps we can come up with a more explicit architecture, while still avoiding all callers needing to explicitly specify the event loop and document.

8.1.6.3 处理模型

事件循环只要存在,就会不断执行以下步骤:

  1. taskQueue事件循环任务队列, 以 实现方定义 的方式去选择, 但是选定的任务队列必须包含至少一个 可运行的 任务。 如果没有这样的任务队列,跳到下面的 微任务 步骤。

    注意 微任务队列 不是 任务队列, 所以它不会在这一步中被选中。但是 微任务源 关联的 任务队列 可能被选中。在这种情况下,下一步中选中的 任务 最初是一个 微任务, 但最终会作为 spinning the event loop 的一部分被移走。

  2. oldestTask 为在 taskQueue 中的第一个 可执行 任务, 然后把它从 taskQueue 移除 remove

  3. 事件循环当前运行的任务设置为 oldestTask

  4. taskStartTime当前的高分辨率时间

  5. 执行 oldestTask步骤

  6. 事件循环当前运行的任务设置为 null。

  7. microtask: 执行微任务检查点

  8. hasARenderingOpportunity 为 false。

  9. now当前高分辨率时间[HRT]

  10. 通过执行以下步骤报告 任务 的持续时间:

    1. top-level browsing contexts 为空 集合

    2. oldestTask脚本执行环境设置对象集合 的每个 环境设置对象 settings追加 setting定级浏览上下文top-level browsing contexts

    3. 报告长任务,传入 taskStartTimenow (任务结束时间),top-level browsing contextsoldestTask

  11. 更新渲染:如果是 窗口事件循环 的话:

    1. docs相关代理事件循环 是这个事件循环的所有 Document 对象,可以任意排序,但必须满足以下条件:

      在遍历docs的下面步骤中,每个Document必须按照在列表中找到的顺序进行处理。

    2. Rendering opportunities: Remove from docs all Document objects whose browsing context do not have a rendering opportunity.

      A browsing context has a rendering opportunity if the user agent is currently able to present the contents of the browsing context to the user, accounting for hardware refresh rate constraints and user agent throttling for performance reasons, but considering content presentable even if it's outside the viewport.

      Browsing context rendering opportunities are determined based on hardware constraints such as display refresh rates and other factors such as page performance or whether the page is in the background. Rendering opportunities typically occur at regular intervals.

      This specification does not mandate any particular model for selecting rendering opportunities. But for example, if the browser is attempting to achieve a 60Hz refresh rate, then rendering opportunities occur at a maximum of every 60th of a second (about 16.7ms). If the browser finds that a browsing context is not able to sustain this rate, it might drop to a more sustainable 30 rendering opportunities per second for that browsing context, rather than occasionally dropping frames. Similarly, if a browsing context is not visible, the user agent might decide to drop that page to a much slower 4 rendering opportunities per second, or even less.

    3. If docs is not empty, then set hasARenderingOpportunity to true.

    4. Unnecessary rendering: Remove from docs all Document objects which meet both of the following conditions:

    5. Remove from docs all Document objects for which the user agent believes that it's preferrable to skip updating the rendering for other reasons.

      The step labeled Rendering opportunities prevents the user agent from updating the rendering when it is unable to present new content to the user (there's no rendering opportunity).

      The step labeled Unnecessary rendering prevents the user agent from updating the rendering when there's no new content to draw.

      This step enables the user agent to prevent the steps below from running for other reasons, for example, to ensure certain tasks are executed immediately after each other, with only microtask checkpoints interleaved (and without, e.g., animation frame callbacks interleaved). Concretely, a user agent might wish to coalesce timer callbacks together, with no intermediate rendering updates.

    6. For each fully active Document in docs, flush autofocus candidates for that Document if its browsing context is a top-level browsing context.

    7. 对于docs中的每个完全活跃的Document,运行该 Document 的调整大小步骤,当前时间作为时间戳传入。 [CSSOMVIEW]

    8. 对于docs中的每个完全活跃的Document,运行该 Document 的滚动步骤步骤,将当前时间作为时间戳传入。 [CSSOMVIEW]

    9. 对于docs中的每个完全活跃的Document评估媒体查询并报告该 Document 的更改,将当前时间作为时间戳传入。[CSSOMVIEW]

    10. 对于docs中的每个完全活跃的Document更新动画并为该 Document 发送事件,将当前时间作为时间戳传入。[WEBANIMATIONS]

    11. 对于docs中的每个完全活跃的Document,运行该 Document 的全屏步骤,将当前时间作为时间戳传入。[FULLSCREEN]

    12. 对于docs中的每个完全活跃的Document,运行该 Document 的动画帧回调,将当前时间作为时间戳传入。

    13. 对于docs中的每个完全活跃的Document,运行该 Document 的更新交叉观察步骤,将当前时间作为时间戳传入。 [INTERSECTIONOBSERVER]

    14. 对每个 docs 里的 Document 对象调用 标记渲染时间 算法。

    15. 对于docs中的每个完全活跃的Document,更新该文档的渲染或用户界面及其浏览上下文,以反映当前状态。

  12. If all of the following are true

    then for each Window object whose whose relevant agent's event loop is this event loop, run the start an idle period algorithm, passing the Window. [REQUESTIDLECALLBACK]

  13. If this is a worker event loop, then:

    1. If this event loop's agent's single realm's global object is a supported DedicatedWorkerGlobalScope and the user agent believes that it would benefit from having its rendering updated at this time, then:

      1. Let now be the current high resolution time. [HRT]

      2. Run the animation frame callbacks for that DedicatedWorkerGlobalScope, passing in now as the timestamp.

      3. Update the rendering of that dedicated worker to reflect the current state.

      Similar to the notes for updating the rendering in a window event loop, a user agent can determine the rate of rendering in the dedicated worker.

    2. If there are no tasks in the event loop's task queues and the WorkerGlobalScope object's closing flag is true, then destroy the event loop, aborting these steps, resuming the run a worker steps described in the Web workers section below.


当用户代理 执行微任务检查点 时:

  1. If the event loop's performing a microtask checkpoint is true, then return.

  2. Set the event loop's performing a microtask checkpoint to true.

  3. While the event loop's microtask queue is not empty:

    1. Let oldestMicrotask be the result of dequeuing from the event loop's microtask queue.

    2. Set the 事件循环's 当前执行任务 to oldestMicrotask.

    3. Run oldestMicrotask.

      This might involve invoking scripted callbacks, which eventually calls the clean up after running script steps, which call this microtask 检查点 algorithm again, which is why we use the 执行一个 microtask 检查点 flag to avoid reentrancy.

    4. Set the 事件循环's 当前执行任务 back to null.

  4. For each 环境设置对象 whose 负责事件循环 is this 事件循环, notify about rejected promises on that 环境设置对象.

  5. Cleanup Indexed Database transactions.

  6. Set the event loop's performing a microtask checkpoint to false.


When an algorithm running in parallel is to await a stable state, the user agent must 入队微任务 that runs the following steps, and must then stop executing (execution of the algorithm resumes when the microtask is run, as described in the following steps):

  1. Run the algorithm's synchronous section.

  2. Resumes execution of the algorithm in parallel, if appropriate, as described in the algorithm's steps.

Steps in synchronous sections are marked with ⌛.


Algorithm steps that say to spin the event loop until a condition goal is met are equivalent to substituting in the following algorithm steps:

  1. Let task be the 事件循环's 当前执行任务.

    task could be a microtask.

  2. Let task source be task's source.

  3. Let old stack be a copy of the JavaScript 执行上下文栈.

  4. Empty the JavaScript 执行上下文栈.

  5. Perform a microtask checkpoint.

    If task is a microtask this step will be a no-op due to performing a microtask checkpoint being true.

  6. In parallel:

    1. Wait until the condition goal is met.

    2. Queue a task on task source to:

      1. Replace the JavaScript execution context stack with old stack.

      2. Perform any steps that appear after this spin the event loop instance in the original algorithm.

        This resumes task.

  7. Stop task, allowing whatever algorithm that invoked it to resume.

    This causes the event loop's main set of steps or the perform a microtask checkpoint algorithm to continue.

Unlike other algorithms in this and other specifications, which behave similar to programming-language function calls, spin the event loop is more like a macro, which saves typing and indentation at the usage site by expanding into a series of steps and operations.

An algorithm whose steps are:

  1. Do something.

  2. Spin the event loop until awesomeness happens.

  3. Do something else.

is a shorthand which, after "macro expansion", becomes

  1. Do something.

  2. Let old stack be a copy of the JavaScript execution context stack.

  3. Empty the JavaScript execution context stack.

  4. Perform a microtask checkpoint.

  5. In parallel:

    1. Wait until awesomeness happens.

    2. Queue a task on the task source in which "do something" was done to:

      1. Replace the JavaScript execution context stack with old stack.

      2. Do something else.

Here is a more full example of the substitution, where the event loop is spun from inside a task that is queued from work in parallel. The version using spin the event loop:

  1. In parallel:

    1. Do parallel thing 1.

    2. Queue a task on the DOM manipulation task source to:

      1. Do task thing 1.

      2. Spin the event loop until awesomeness happens.

      3. Do task thing 2.

    3. Do parallel thing 2.

The fully expanded version:

  1. In parallel:

    1. Do parallel thing 1.

    2. Let old stack be null.

    3. Queue a task on the DOM manipulation task source to:

      1. Do task thing 1.

      2. Set old stack to a copy of the JavaScript execution context stack.

      3. Empty the JavaScript execution context stack.

      4. Perform a microtask checkpoint.

    4. Wait until awesomeness happens.

    5. Queue a task on the DOM manipulation task source to:

      1. Perform a microtask checkpoint.

    6. Wait until awesomeness happens.

    7. Queue a task on the DOM manipulation task source to:

      1. Replace the JavaScript execution context stack with old stack.

      2. Do task thing 2.

    8. Do parallel thing 2.


Some of the algorithms in this specification, for historical reasons, require the user agent to pause while running a task until a condition goal is met. This means running the following steps:

  1. If necessary, update the rendering or user interface of any Document or 浏览环境 to reflect the current state.

  2. Wait until the condition goal is met. While a user agent has a paused task, the corresponding 事件循环 must not run further tasks, and any script in the currently running task must block. User agents should remain responsive to user input while paused, however, albeit in a reduced capacity since the 事件循环 will not be doing anything.

Pausing is highly detrimental to the user experience, especially in scenarios where a single 事件循环 is shared among multiple documents. User agents are encouraged to experiment with alternatives to pausing, such as spinning the event loop or even simply proceeding without any kind of suspended execution at all, insofar as it is possible to do so while preserving compatibility with existing content. This specification will happily change if a less-drastic alternative is discovered to be web-compatible.

In the interim, implementers should be aware that the variety of alternatives that user agents might experiment with can change subtle aspects of 事件循环 behavior, including task and 微任务 timing. Implementations should continue experimenting even if doing so causes them to violate the exact semantics implied by the pause operation.

8.1.6.4 Generic task sources

The following task sources are used by a number of mostly unrelated features in this and other specifications.

The DOM manipulation task source

This task source is used for features that react to DOM manipulations, such as things that happen in a non-blocking fashion when an element is inserted into the document.

The user interaction task source

This task source is used for features that react to user interaction, for example keyboard or mouse input.

Events sent in response to user input (e.g. click events) must be fired using tasks queued with the user interaction task source. [UIEVENTS]

The networking task source

This task source is used for features that trigger in response to network activity.

The history traversal task source

This task source is used to queue calls to history.back() and similar APIs.

8.1.6.5 Dealing with the event loop from other specifications

Writing specifications that correctly interact with the event loop can be tricky. This is compounded by how this specification uses concurrency-model-independent terminology, so we say things like "event loop" and "in parallel" instead of using more familiar model-specific terms like "main thread" or "on a background thread".

By default, specification text generally runs on the event loop. This falls out from the formal event loop processing model, in that you can eventually trace most algorithms back to a task queued there.

The algorithm steps for any JavaScript method will be invoked by author code calling that method. And author code can only be run via queued tasks, usually originating somewhere in the script processing model.

From this starting point, the overriding guideline is that any work a specification needs to perform that would otherwise block the event loop must instead be performed in parallel with it. This includes (but is not limited to):

The next complication is that, in algorithm sections that are in parallel, you must not create or manipulate objects associated to a specific JavaScript realm, global, or environment settings object. (Stated in more familiar terms, you must not directly access main-thread artifacts from a background thread.) Doing so would create data races observable to JavaScript code, since after all, your algorithm steps are running in parallel to the JavaScript code.

You can, however, manipulate specification-level data structures and values from Infra, as those are realm-agnostic. They are never directly exposed to JavaScript without a specific conversion taking place (often via Web IDL). [INFRA] [WEBIDL]

To affect the world of observable JavaScript objects, then, you must queue a task to perform any such manipulations. This ensures your steps are properly interleaved with respect to other things happening on the event loop. Furthermore, you must choose a task source when queuing a task; this governs the relative order of your steps versus others. If you are unsure which task source to use, pick one of the generic task sources that sounds most applicable.

Most invocations of queue a task use the implied event loop, i.e., the one that is obvious from context. That is because it is very rare for algorithms to be invoked in contexts involving multiple event loops. (Unlike contexts involving multiple global objects, which happen all the time!) So unless you are writing a specification which, e.g., deals with manipulating workers, you can omit this argument when queuing a task.

Putting this all together, we can provide a template for a typical algorithm that needs to do work asynchronously:

  1. Do any synchronous setup work, while still on the event loop. This may include converting realm-specific JavaScript values into realm-agnostic specification-level values.

  2. Perform a set of potentially-expensive steps in parallel, operating entirely on realm-agnostic values, and producing a realm-agnostic result.

  3. Queue a task, on a specified task source, to convert the realm-agnostic result back into observable effects on the observable world of JavaScript objects on the event loop.

The following is an algorithm that "encrypts" a passed-in list of scalar value strings input, after parsing them as URLs:

  1. Let urls be an empty list.

  2. For each string of input:

    1. Let parsed be the result of parsing string relative to the current settings object.

    2. If parsed is failure, return a promise rejected with a "SyntaxError" DOMException.

    3. Let serialized be the result of applying the URL serializer to parsed.

    4. Append serialized to urls.

  3. Let realm be the current Realm Record.

  4. Let p be a new promise.

  5. Run the following steps in parallel:

    1. Let encryptedURLs be an empty list.

    2. For each url of urls:

      1. Wait 100 milliseconds, so that people think we're doing heavy-duty encryption.

      2. Let encrypted be a new string derived from url, whose nth code unit is equal to url's nth code unit plus 13.

      3. Append encrypted to encryptedURLs.

    3. Queue a task, on the networking task source, to perform the following steps:

      1. Let array be the result of converting encryptedURLs to a JavaScript array, in realm.

      2. Resolve p with array.

  6. Return p.

Here are several things to notice about this algorithm:

(On these last two points, see also w3ctag/promises-guide issue #52, heycam/webidl issue #135, and heycam/webidl issue #371, where we are still mulling over the subtleties of the above promise-resolution pattern.)

Another thing to note is that, in the event this algorithm was called from a Web IDL-specified operation taking a sequence<USVString>, there was an automatic conversion from realm-specific JavaScript objects provided by the author as input, into the realm-agnostic sequence<USVString> Web IDL type, which we then treat as a list of scalar value strings. So depending on how your specification is structured, there may be other implicit steps happening on the main event loop that play a part in this whole process of getting you ready to go in parallel.

8.1.7 事件

8.1.7.1 Event handlers

Events/Event_handlers

Many objects can have event handlers specified. These act as non-capture event listeners for the object on which they are specified. [DOM]

An event handler is a struct with two items:

Event handlers are exposed in two ways.

The first way, common to all event handlers, is as an event handler IDL attribute.

The second way is as an event handler content attribute. Event handlers on HTML elements and some of the event handlers on Window objects are exposed in this way.

For both of these two ways, the event handler is exposed through a name, which is a string that always starts with "on" and is followed by the name of the event for which the handler is intended.


Most of the time, the object that exposes an event handler is the same as the object on which the corresponding event listener is added. However, the body and frameset elements expose several event handlers that act upon the element's Window object, if one exists. In either case, we call the object an event handler acts upon the target of that event handler.

To determine the target of an event handler, given an EventTarget object eventTarget on which the event handler is exposed, and an event handler name name, the following steps are taken:

  1. If eventTarget is not a body element or a frameset element, then return eventTarget.

  2. If name is not the name of an attribute member of the WindowEventHandlers interface mixin and the Window-reflecting body element event handler set does not contain name, then return eventTarget.

  3. If eventTarget's node document is not an active document, then return null.

    This could happen if this object is a body element without a corresponding Window object, for example.

    This check does not necessarily prevent body and frameset elements that are not the body element of their node document from reaching the next step. In particular, a body element created in an active document (perhaps with document.createElement()) but not connected will also have its corresponding Window object as the target of several event handlers exposed through it.

  4. Return eventTarget's node document's relevant global object.


Each EventTarget object that has one or more event handlers specified has an associated event handler map, which is a map of strings representing names of event handlers to event handlers.

When an EventTarget object that has one or more event handlers specified is created, its event handler map must be initialized such that it contains an entry for each event handler that has that object as target, with items in those event handlers set to their initial values.

The order of the entries of event handler map could be arbitrary. It is not observable through any algorithms that operate on the map.

Entries are not created in the event handler map of an object for event handlers that are merely exposed on that object, but have some other object as their targets.


An event handler IDL attribute is an IDL attribute for a specific event handler. The name of the IDL attribute is the same as the name of the event handler.

The getter of an event handler IDL attribute with name name, when called, must run these steps:

  1. Let eventTarget be the result of determining the target of an event handler given this object and name.

  2. If eventTarget is null, then return null.

  3. Return the result of getting the current value of the event handler given eventTarget and name.

The setter of an event handler IDL attribute with name name, when called, must run these steps:

  1. Let eventTarget be the result of determining the target of an event handler given this object and name.

  2. If eventTarget is null, then return.

  3. If the given value is null, then deactivate an event handler given eventTarget and name.

  4. Otherwise:

    1. Let handlerMap be eventTarget's event handler map.

    2. Let eventHandler be handlerMap[name].

    3. Set eventHandler's value to the given value.

    4. Activate an event handler given eventTarget and name.

Certain event handler IDL attributes have additional requirements, in particular the onmessage attribute of MessagePort objects.


An event handler content attribute is a content attribute for a specific event handler. The name of the content attribute is the same as the name of the event handler.

Event handler content attributes, when specified, must contain valid JavaScript code which, when parsed, would match the FunctionBody production after automatic semicolon insertion.

The following attribute change steps are used to synchronize between event handler content attributes and event handlers: [DOM]

  1. If namespace is not null, or localName is not the name of an event handler content attribute on element, then return.

  2. Let eventTarget be the result of determining the target of an event handler given element and localName.

  3. If eventTarget is null, then return.

  4. If value is null, then deactivate an event handler given eventTarget and localName.

  5. Otherwise:

    1. If the Should element's inline behavior be blocked by Content Security Policy? algorithm returns "Blocked" when executed upon element, "script attribute", and value, then return. [CSP]

    2. Let handlerMap be eventTarget's event handler map.

    3. Let eventHandler be handlerMap[localName].

    4. Let location be the script location that triggered the execution of these steps.

    5. Set eventHandler's value to the internal raw uncompiled handler value/location.

    6. Activate an event handler given eventTarget and localName.

Per the DOM Standard, these steps are run even if oldValue and value are identical (setting an attribute to its current value), but not if oldValue and value are both null (removing an attribute that doesn't currently exist). [DOM]


To deactivate an event handler given an EventTarget object eventTarget and a string name that is the name of an event handler, run these steps:

  1. Let handlerMap be eventTarget's event handler map.

  2. Let eventHandler be handlerMap[name].

  3. Set eventHandler's value to null.

  4. Let listener be eventHandler's listener.

  5. If listener is not null, then remove an event listener with eventTarget and listener.

  6. Set eventHandler's listener to null.

To erase all event listeners and handlers given an EventTarget object eventTarget, run these steps:

  1. If eventTarget has an associated event handler map, then for each nameeventHandler of eventTarget's associated event handler map, deactivate an event handler given eventTarget and name.

  2. Remove all event listeners given eventTarget.

This algorithm is used to define document.open().

To activate an event handler given an EventTarget object eventTarget and a string name that is the name of an event handler, run these steps:

  1. Let handlerMap be eventTarget's event handler map.

  2. Let eventHandler be handlerMap[name].

  3. If eventHandler's listener is not null, then return.

  4. Let callback be the result of creating a Web IDL EventListener instance representing a reference to a function of one argument that executes the steps of the event handler processing algorithm, given eventTarget, name, and its argument.

    The EventListener's callback context can be arbitrary; it does not impact the steps of the event handler processing algorithm. [DOM]

    The callback is emphatically not the event handler itself. Every event handler ends up registering the same callback, the algorithm defined below, which takes care of invoking the right code, and processing the code's return value.

  5. Let listener be a new event listener whose type is the event handler event type corresponding to eventHandler and callback is callback.

    To be clear, an event listener is different from an EventListener.

  6. Add an event listener with eventTarget and listener.

  7. Set eventHandler's listener to listener.

The event listener registration happens only if the event handler's value is being set to non-null, and the event handler is not already activated. Since listeners are called in the order they were registered, assuming no deactivation occurred, the order of event listeners for a particular event type will always be:

  1. the event listeners registered with addEventListener() before the first time the event handler's value was set to non-null

  2. then the callback to which it is currently set, if any

  3. and finally the event listeners registered with addEventListener() after the first time the event handler's value was set to non-null.

This example demonstrates the order in which event listeners are invoked. If the button in this example is clicked by the user, the page will show four alerts, with the text "ONE", "TWO", "THREE", and "FOUR" respectively.

<button id="test">Start Demo</button>
<script>
 var button = document.getElementById('test');
 button.addEventListener('click', function () { alert('ONE') }, false);
 button.setAttribute('onclick', "alert('NOT CALLED')"); // event handler listener is registered here
 button.addEventListener('click', function () { alert('THREE') }, false);
 button.onclick = function () { alert('TWO'); };
 button.addEventListener('click', function () { alert('FOUR') }, false);
</script>

However, in the following example, the event handler is deactivated after its initial activation (and its event listener is removed), before being reactivated at a later time. The page will show five alerts with "ONE", "TWO", "THREE", "FOUR", and "FIVE" respectively, in order.

<button id="test">Start Demo</button>
<script>
 var button = document.getElementById('test');
 button.addEventListener('click', function () { alert('ONE') }, false);
 button.setAttribute('onclick', "alert('NOT CALLED')"); // event handler is activated here
 button.addEventListener('click', function () { alert('TWO') }, false);
 button.onclick = null;                                 // but deactivated here
 button.addEventListener('click', function () { alert('THREE') }, false);
 button.onclick = function () { alert('FOUR'); };       // and re-activated here
 button.addEventListener('click', function () { alert('FIVE') }, false);
</script>

The interfaces implemented by the event object do not influence whether an event handler is triggered or not.

The event handler processing algorithm for an EventTarget object eventTarget, a string name representing the name of an event handler, and an Event object event is as follows:

  1. Let callback be the result of getting the current value of the event handler given eventTarget and name.

  2. If callback is null, then return.

  3. Let special error event handling be true if event is an ErrorEvent object, event's type is error, and event's currentTarget implements the WindowOrWorkerGlobalScope mixin. Otherwise, let special error event handling be false.

  4. Process the Event object event as follows:

    If special error event handling is true

    Invoke callback with five arguments, the first one having the value of event's message attribute, the second having the value of event's filename attribute, the third having the value of event's lineno attribute, the fourth having the value of event's colno attribute, the fifth having the value of event's error attribute, and with the callback this value set to event's currentTarget. Let return value be the callback's return value. [WEBIDL]

    Otherwise

    Invoke callback with one argument, the value of which is the Event object event, with the callback this value set to event's currentTarget. Let return value be the callback's return value. [WEBIDL]

    If an exception gets thrown by the callback, end these steps and allow the exception to propagate. (It will propagate to the DOM event dispatch logic, which will then report the exception.)

  5. Process return value as follows:

    If event is a BeforeUnloadEvent object and event's type is beforeunload

    In this case, the event handler IDL attribute's type will be OnBeforeUnloadEventHandler, so return value will have been coerced into either null or a DOMString.

    If return value is not null, then:

    1. Set event's canceled flag.

    2. If event's returnValue attribute's value is the empty string, then set event's returnValue attribute's value to return value.

    If special error event handling is true

    If return value is true, then set event's canceled flag.

    Otherwise

    If return value is false, then set event's canceled flag.

    If we've gotten to this "Otherwise" clause because event's type is beforeunload but event is not a BeforeUnloadEvent object, then return value will never be false, since in such cases return value will have been coerced into either null or a DOMString.


The EventHandler callback function type represents a callback used for event handlers. It is represented in Web IDL as follows:

[LegacyTreatNonObjectAsNull]
callback EventHandlerNonNull = any (Event event);
typedef EventHandlerNonNull? EventHandler;

In JavaScript, any Function object implements this interface.

For example, the following document fragment:

<body onload="alert(this)" onclick="alert(this)">

...leads to an alert saying "[object Window]" when the document is loaded, and an alert saying "[object HTMLBodyElement]" whenever the user clicks something in the page.

The return value of the function affects whether the event is canceled or not: as described above, if the return value is false, the event is canceled.

There are two exceptions in the platform, for historical reasons:

For historical reasons, the onerror handler has different arguments:

[LegacyTreatNonObjectAsNull]
callback OnErrorEventHandlerNonNull = any ((Event or DOMString) event, optional DOMString source, optional unsigned long lineno, optional unsigned long colno, optional any error);
typedef OnErrorEventHandlerNonNull? OnErrorEventHandler;
window.onerror = (message, source, lineno, colno, error) => { … };

Similarly, the onbeforeunload handler has a different return value:

[LegacyTreatNonObjectAsNull]
callback OnBeforeUnloadEventHandlerNonNull = DOMString? (Event event);
typedef OnBeforeUnloadEventHandlerNonNull? OnBeforeUnloadEventHandler;

An internal raw uncompiled handler is a tuple with the following information:

When the user agent is to get the current value of the event handler given an EventTarget object eventTarget and a string name that is the name of an event handler, it must run these steps:

  1. Let handlerMap be eventTarget's event handler map.

  2. Let eventHandler be handlerMap[name].

  3. If eventHandler's value is an internal raw uncompiled handler, then:

    1. If eventTarget is an element, then let element be eventTarget, and document be element's node document. Otherwise, eventTarget is a Window object, let element be null, and document be eventTarget's associated Document.

    2. If scripting is disabled for document, then return null.

    3. Let body be the uncompiled script body in eventHandler's value.

    4. Let location be the location where the script body originated, as given by eventHandler's value.

    5. If element is not null and element has a form owner, let form owner be that form owner. Otherwise, let form owner be null.

    6. Let settings object be the relevant settings object of document.

    7. If body is not parsable as FunctionBody or if parsing detects an early error, then follow these substeps:

      1. Set eventHandler's value to null.

        This does not deactivate the event handler, which additionally removes the event handler's listener (if present).

      2. Report the error for the appropriate script and with the appropriate position (line number and column number) given by location, using settings object's global object. If the error is still not handled after this, then the error may be reported to a developer console.

      3. Return null.

    8. Push settings object's realm execution context onto the JavaScript execution context stack; it is now the running JavaScript execution context.

      This is necessary so the subsequent invocation of OrdinaryFunctionCreate takes place in the correct JavaScript Realm.

    9. Let function be the result of calling OrdinaryFunctionCreate, with arguments:

      functionPrototype
      %Function.prototype%
      sourceText
      If name is onerror and eventTarget is a Window object
      The string formed by concatenating "function ", name, "(event, source, lineno, colno, error) {", U+000A LF, body, U+000A LF, and "}".
      Otherwise
      The string formed by concatenating "function ", name, "(event) {", U+000A LF, body, U+000A LF, and "}".
      ParameterList
      If name is onerror and eventTarget is a Window object
      Let the function have five arguments, named event, source, lineno, colno, and error.
      Otherwise
      Let the function have a single argument called event.
      Body
      The result of parsing body above.
      thisMode
      non-lexical-this
      Scope
      1. Let realm be settings object's Realm.

      2. Let scope be realm.[[GlobalEnv]].

      3. If eventHandler is an element's event handler, then set scope to NewObjectEnvironment(document, scope).

        (Otherwise, eventHandler is a Window object's event handler.)

      4. If form owner is not null, then set scope to NewObjectEnvironment(form owner, scope).

      5. If element is not null, then set scope to NewObjectEnvironment(element, scope).

      6. Return scope.

    10. Remove settings object's realm execution context from the JavaScript execution context stack.

    11. Set function.[[ScriptOrModule]] to null.

      This is done because the default behavior, of associating the created function with the nearest script on the stack, can lead to path-dependent results. For example, an event handler which is first invoked by user interaction would end up with null [[ScriptOrModule]] (since then this algorithm would be first invoked when the active script is null), whereas one that is first invoked by dispatching an event from script would have its [[ScriptOrModule]] set to that script.

      Instead, we just always set [[ScriptOrModule]] to null. This is more intuitive anyway; the idea that the first script which dispatches an event is somehow responsible for the event handler code is dubious.

      In practice, this only affects the resolution of relative URLs via import(), which consult the base URL of the associated script. Nulling out [[ScriptOrModule]] means that HostResolveImportedModule and HostImportModuleDynamically will fall back to the current settings object's API base URL.

    12. Set eventHandler's value to the result of creating a Web IDL EventHandler callback function object whose object reference is function and whose callback context is settings object.

  4. Return eventHandler's value.

8.1.7.2 Event handlers on elements, Document objects, and Window objects

The following are the event handlers (and their corresponding event handler event types) that must be supported by all HTML elements, as both event handler content attributes and event handler IDL attributes; and that must be supported by all Document and Window objects, as event handler IDL attributes:

Event handler Event handler event type
onabort

GlobalEventHandlers/onabort

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
abort
onauxclick auxclick
oncancel

GlobalEventHandlers/oncancel

Support in one engine only.

FirefoxNoSafariNoChrome32+
Opera19+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOSNoChrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
cancel
oncanplay

GlobalEventHandlers/oncanplay

Support in all current engines.

Firefox9+Safari9+Chrome32+
Opera19+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS9+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
canplay
oncanplaythrough

GlobalEventHandlers/oncanplaythrough

Support in all current engines.

Firefox9+Safari9+Chrome32+
Opera19+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS9+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
canplaythrough
onchange

GlobalEventHandlers/onchange

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
change
onclick

GlobalEventHandlers/onclick

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
click
onclose

GlobalEventHandlers/onclose

Firefox53+SafariNoChrome32+
Opera19+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android53+Safari iOSNoChrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
close
oncontextmenu

GlobalEventHandlers/oncontextmenu

Support in all current engines.

Firefox9+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox Android9+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
contextmenu
oncuechange

HTMLTrackElement/cuechange_event

Support in all current engines.

Firefox68+Safari10+Chrome32+
Opera19+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android68+Safari iOS10+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
cuechange
ondblclick

GlobalEventHandlers/ondblclick

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
dblclick
ondrag drag
ondragend dragend
ondragenter dragenter
ondragleave dragleave
ondragover dragover
ondragstart dragstart
ondrop drop
ondurationchange

GlobalEventHandlers/ondurationchange

Support in all current engines.

Firefox9+Safari9+Chrome32+
Opera19+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS9+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
durationchange
onemptied

GlobalEventHandlers/onemptied

Support in all current engines.

Firefox9+Safari9+Chrome32+
Opera19+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS9+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
emptied
onended

GlobalEventHandlers/onended

Support in all current engines.

Firefox9+Safari9+Chrome32+
Opera19+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS9+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
ended
onformdata

GlobalEventHandlers/onformdata

Support in all current engines.

Firefox72+Safari15+Chrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS15+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+
formdata
oninput

GlobalEventHandlers/oninput

Support in all current engines.

Firefox9+Safari4+Chrome1+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+
input
oninvalid

GlobalEventHandlers/oninvalid

Support in all current engines.

Firefox9+Safari5+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)13+Internet ExplorerNo
Firefox Android9+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
invalid
onkeydown

GlobalEventHandlers/onkeydown

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
keydown
onkeypress keypress
onkeyup

GlobalEventHandlers/onkeyup

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
keyup
onloadeddata

GlobalEventHandlers/onloadeddata

Support in all current engines.

Firefox9+Safari9+Chrome32+
Opera19+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS9+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
loadeddata
onloadedmetadata

GlobalEventHandlers/onloadedmetadata

Support in all current engines.

Firefox9+Safari9+Chrome32+
Opera19+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS9+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
loadedmetadata
onloadstart

GlobalEventHandlers/onloadstart

Support in all current engines.

Firefox9+Safari9+Chrome32+
Opera19+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS9+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
loadstart
onmousedown

GlobalEventHandlers/onmousedown

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
mousedown
onmouseenter

GlobalEventHandlers/onmouseenter

Support in all current engines.

Firefox10+Safari7+Chrome30+
Opera17+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android10+Safari iOS7+Chrome Android30+WebView Android4.4+Samsung Internet2.0+Opera Android18+
mouseenter
onmouseleave

GlobalEventHandlers/onmouseleave

Support in all current engines.

Firefox10+Safari7+Chrome30+
Opera17+Edge79+
Edge (Legacy)12+Internet Explorer5.5+
Firefox Android10+Safari iOS7+Chrome Android30+WebView Android4.4+Samsung Internet2.0+Opera Android18+
mouseleave
onmousemove

GlobalEventHandlers/onmousemove

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
mousemove
onmouseout

GlobalEventHandlers/onmouseout

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
mouseout
onmouseover

GlobalEventHandlers/onmouseover

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
mouseover
onmouseup

GlobalEventHandlers/onmouseup

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
mouseup
onpause

GlobalEventHandlers/onpause

Support in all current engines.

Firefox9+Safari9+Chrome32+
Opera19+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS9+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
pause
onplay

GlobalEventHandlers/onplay

Support in all current engines.

Firefox9+Safari9+Chrome32+
Opera19+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS9+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
play
onplaying

GlobalEventHandlers/onplaying

Support in all current engines.

Firefox9+Safari9+Chrome32+
Opera19+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS9+Chrome Android32+WebView Android4.4.3+Samsung Internet2.0+Opera Android19+
playing
onprogress progress
onratechange ratechange
onreset

GlobalEventHandlers/onreset

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
reset
onsecuritypolicyviolation

GlobalEventHandlers/onsecuritypolicyviolation

Support in all current engines.

Firefox93+Safaripreview+Chrome97+
Opera83+Edge97+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android93+Safari iOSNoChrome Android97+WebView Android97+Samsung InternetNoOpera AndroidNo
securitypolicyviolation
onseeked seeked
onseeking seeking
onselect

GlobalEventHandlers/onselect

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
select
onslotchange

GlobalEventHandlers/onslotchange

Support in all current engines.

Firefox93+Safaripreview+Chrome97+
Opera83+Edge97+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android93+Safari iOSNoChrome Android97+WebView Android97+Samsung InternetNoOpera AndroidNo
slotchange
onstalled stalled
onsubmit

GlobalEventHandlers/onsubmit

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
submit
onsuspend suspend
ontimeupdate timeupdate
ontoggle toggle
onvolumechange volumechange
onwaiting waiting
onwebkitanimationend webkitAnimationEnd
onwebkitanimationiteration webkitAnimationIteration
onwebkitanimationstart webkitAnimationStart
onwebkittransitionend webkitTransitionEnd
onwheel

GlobalEventHandlers/onwheel

Support in all current engines.

Firefox17+Safari7+Chrome31+
Opera18+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android17+Safari iOS7+Chrome Android31+WebView Android4.4.3+Samsung Internet2.0+Opera Android18+
wheel

The following are the event handlers (and their corresponding event handler event types) that must be supported by all HTML elements other than body and frameset elements, as both event handler content attributes and event handler IDL attributes; that must be supported by all Document objects, as event handler IDL attributes; and that must be supported by all Window objects, as event handler IDL attributes on the Window objects themselves, and with corresponding event handler content attributes and event handler IDL attributes exposed on all body and frameset elements that are owned by that Window object's associated Document:

Event handler Event handler event type
onblur

GlobalEventHandlers/onblur

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
blur
onerror

GlobalEventHandlers/onerror

Support in all current engines.

Firefox1+Safari6+Chrome10+
Opera11.6+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS6+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12+
error
onfocus

GlobalEventHandlers/onfocus

Support in all current engines.

Firefox9+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
focus
onload

GlobalEventHandlers/onload

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
load
onresize

GlobalEventHandlers/onresize

Support in all current engines.

Firefox38+Safari10.1+Chrome34+
Opera21+Edge79+
Edge (Legacy)NoInternet Explorer🔰 4+
Firefox Android38+Safari iOS10.3+Chrome Android34+WebView Android37+Samsung Internet2.0+Opera Android21+
resize
onscroll

GlobalEventHandlers/onscroll

Support in all current engines.

Firefox9+Safari1.3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
scroll

We call the set of the names of the event handlers listed in the first column of this table the Window-reflecting body element event handler set.


The following are the event handlers (and their corresponding event handler event types) that must be supported by Window objects, as event handler IDL attributes on the Window objects themselves, and with corresponding event handler content attributes and event handler IDL attributes exposed on all body and frameset elements that are owned by that Window object's associated Document:

Event handler Event handler event type
onafterprint

Window/afterprint_event

Support in all current engines.

Firefox6+Safari13+Chrome63+
Opera50+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android6+Safari iOS13+Chrome Android63+WebView Android63+Samsung Internet8.0+Opera Android46+
afterprint
onbeforeprint

Window/beforeprint_event

Support in all current engines.

Firefox6+Safari13+Chrome63+
Opera50+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android6+Safari iOS13+Chrome Android63+WebView Android63+Samsung Internet8.0+Opera Android46+
beforeprint
onbeforeunload

Window/beforeunload_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
beforeunload
onhashchange

Window/hashchange_event

Support in all current engines.

Firefox3.6+Safari5+Chrome8+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
hashchange
onlanguagechange

Window/languagechange_event

Support in all current engines.

Firefox32+Safari10.1+Chrome37+
Opera24+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android4+Safari iOS10.3+Chrome Android37+WebView Android37+Samsung Internet4.0+Opera Android24+
languagechange
onmessage

Window/message_event

Support in all current engines.

Firefox9+Safari4+Chrome60+
Opera47+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android9+Safari iOS4+Chrome Android60+WebView Android60+Samsung Internet8.0+Opera Android47+
message
onmessageerror

Window/messageerror_event

Firefox57+SafariNoChrome60+
Opera47+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android57+Safari iOSNoChrome Android60+WebView Android60+Samsung Internet8.0+Opera Android47+
messageerror
onoffline

Window/offline_event

Support in all current engines.

Firefox9+Safari4+Chrome3+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
offline
ononline

Window/online_event

Support in all current engines.

Firefox9+Safari4+Chrome3+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
online
onpagehide pagehide
onpageshow pageshow
onpopstate

Window/popstate_event

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS4.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11.5+
popstate
onrejectionhandled

Window/rejectionhandled_event

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera36+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS11.3+Chrome Android49+WebView Android49+Samsung Internet5.0+Opera Android36+
rejectionhandled
onstorage

Window/storage_event

Support in all current engines.

Firefox45+Safari4+Chrome1+
Opera15+Edge79+
Edge (Legacy)15+Internet Explorer9+
Firefox Android45+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
storage
onunhandledrejection

Window/unhandledrejection_event

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera36+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS11.3+Chrome Android49+WebView Android49+Samsung Internet5.0+Opera Android36+
unhandledrejection
onunload

Window/unload_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
unload

This list of event handlers is reified as event handler IDL attributes through the WindowEventHandlers interface mixin.


The following are the event handlers (and their corresponding event handler event types) that must be supported by all HTML elements, as both event handler content attributes and event handler IDL attributes; and that must be supported by all Document objects, as event handler IDL attributes:

Event handler Event handler event type
oncut

HTMLElement/cut_event

Support in all current engines.

Firefox9+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
cut
oncopy

HTMLElement/copy_event

Support in all current engines.

Firefox3+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
copy
onpaste

HTMLElement/paste_event

Support in all current engines.

Firefox9+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
paste

This list of event handlers is reified as event handler IDL attributes through the DocumentAndElementEventHandlers interface mixin.


The following are the event handlers (and their corresponding event handler event types) that must be supported on Document objects as event handler IDL attributes:

Event handler Event handler event type
onreadystatechange readystatechange
8.1.7.2.1 IDL definitions

GlobalEventHandlers

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+
interface mixin GlobalEventHandlers {
  attribute EventHandler onabort;
  attribute EventHandler onauxclick;
  attribute EventHandler onblur;
  attribute EventHandler oncancel;
  attribute EventHandler oncanplay;
  attribute EventHandler oncanplaythrough;
  attribute EventHandler onchange;
  attribute EventHandler onclick;
  attribute EventHandler onclose;
  attribute EventHandler oncontextmenu;
  attribute EventHandler oncuechange;
  attribute EventHandler ondblclick;
  attribute EventHandler ondrag;
  attribute EventHandler ondragend;
  attribute EventHandler ondragenter;
  attribute EventHandler ondragleave;
  attribute EventHandler ondragover;
  attribute EventHandler ondragstart;
  attribute EventHandler ondrop;
  attribute EventHandler ondurationchange;
  attribute EventHandler onemptied;
  attribute EventHandler onended;
  attribute OnErrorEventHandler onerror;
  attribute EventHandler onfocus;
  attribute EventHandler onformdata;
  attribute EventHandler oninput;
  attribute EventHandler oninvalid;
  attribute EventHandler onkeydown;
  attribute EventHandler onkeypress;
  attribute EventHandler onkeyup;
  attribute EventHandler onload;
  attribute EventHandler onloadeddata;
  attribute EventHandler onloadedmetadata;
  attribute EventHandler onloadstart;
  attribute EventHandler onmousedown;
  [LegacyLenientThis] attribute EventHandler onmouseenter;
  [LegacyLenientThis] attribute EventHandler onmouseleave;
  attribute EventHandler onmousemove;
  attribute EventHandler onmouseout;
  attribute EventHandler onmouseover;
  attribute EventHandler onmouseup;
  attribute EventHandler onpause;
  attribute EventHandler onplay;
  attribute EventHandler onplaying;
  attribute EventHandler onprogress;
  attribute EventHandler onratechange;
  attribute EventHandler onreset;
  attribute EventHandler onresize;
  attribute EventHandler onscroll;
  attribute EventHandler onsecuritypolicyviolation;
  attribute EventHandler onseeked;
  attribute EventHandler onseeking;
  attribute EventHandler onselect;
  attribute EventHandler onslotchange;
  attribute EventHandler onstalled;
  attribute EventHandler onsubmit;
  attribute EventHandler onsuspend;
  attribute EventHandler ontimeupdate;
  attribute EventHandler ontoggle;
  attribute EventHandler onvolumechange;
  attribute EventHandler onwaiting;
  attribute EventHandler onwebkitanimationend;
  attribute EventHandler onwebkitanimationiteration;
  attribute EventHandler onwebkitanimationstart;
  attribute EventHandler onwebkittransitionend;
  attribute EventHandler onwheel;
};

interface mixin WindowEventHandlers {
  attribute EventHandler onafterprint;
  attribute EventHandler onbeforeprint;
  attribute OnBeforeUnloadEventHandler onbeforeunload;
  attribute EventHandler onhashchange;
  attribute EventHandler onlanguagechange;
  attribute EventHandler onmessage;
  attribute EventHandler onmessageerror;
  attribute EventHandler onoffline;
  attribute EventHandler ononline;
  attribute EventHandler onpagehide;
  attribute EventHandler onpageshow;
  attribute EventHandler onpopstate;
  attribute EventHandler onrejectionhandled;
  attribute EventHandler onstorage;
  attribute EventHandler onunhandledrejection;
  attribute EventHandler onunload;
};

interface mixin DocumentAndElementEventHandlers {
  attribute EventHandler oncopy;
  attribute EventHandler oncut;
  attribute EventHandler onpaste;
};
8.1.7.3 Event firing

Certain operations and methods are defined as firing events on elements. For example, the click() method on the HTMLElement interface is defined as firing a click event on the element. [UIEVENTS]

Firing a synthetic mouse event named e at target, with an optional not trusted flag, means running these steps:

  1. Let event be the result of creating an event using MouseEvent.

  2. Initialize event's type attribute to e.

  3. Initialize event's bubbles and cancelable attributes to true.

  4. Set event's composed flag.

  5. If the not trusted flag is set, initialize event's isTrusted attribute to false.

  6. Initialize event's ctrlKey, shiftKey, altKey, and metaKey attributes according to the current state of the key input device, if any (false for any keys that are not available).

  7. Initialize event's view attribute to target's node document's Window object, if any, and null otherwise.

  8. event's getModifierState() method is to return values appropriately describing the current state of the key input device.

  9. Return the result of dispatching event at target.

Firing a click event at target means firing a synthetic mouse event named click at target.

8.2 The WindowOrWorkerGlobalScope mixin

The WindowOrWorkerGlobalScope mixin is for use of APIs that are to be exposed on Window and WorkerGlobalScope objects.

Other standards are encouraged to further extend it using partial interface mixin WindowOrWorkerGlobalScope { … }; along with an appropriate reference.

typedef (DOMString or Function) TimerHandler;

interface mixin WindowOrWorkerGlobalScope {
  [Replaceable] readonly attribute USVString origin;
  readonly attribute boolean isSecureContext;
  readonly attribute boolean crossOriginIsolated;

  // base64 utility methods
  DOMString btoa(DOMString data);
  ByteString atob(DOMString data);

  // timers
  long setTimeout(TimerHandler handler, optional long timeout = 0, any... arguments);
  undefined clearTimeout(optional long handle = 0);
  long setInterval(TimerHandler handler, optional long timeout = 0, any... arguments);
  undefined clearInterval(optional long handle = 0);

  // microtask queuing
  undefined queueMicrotask(VoidFunction callback);

  // ImageBitmap
  Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image, optional ImageBitmapOptions options = {});
  Promise<ImageBitmap> createImageBitmap(ImageBitmapSource image, long sx, long sy, long sw, long sh, optional ImageBitmapOptions options = {});
};
Window includes WindowOrWorkerGlobalScope;
WorkerGlobalScope includes WindowOrWorkerGlobalScope;
self . isSecureContext

isSecureContext

Support in all current engines.

Firefox49+Safari11.1+Chrome47+
Opera34+Edge79+
Edge (Legacy)15+Internet ExplorerNo
Firefox Android49+Safari iOS11.3+Chrome Android47+WebView Android47+Samsung Internet5.0+Opera Android34+

Returns whether or not this global object represents a secure context. [SECURE-CONTEXTS]

self . origin

origin

Support in all current engines.

Firefox54+Safari11+Chrome59+
Opera46+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android54+Safari iOS11+Chrome Android59+WebView Android59+Samsung Internet7.0+Opera Android43+

Returns the global object's origin, serialized as string.

self . crossOriginIsolated

crossOriginIsolated

Support in all current engines.

Firefox72+Safari15.2+Chrome87+
Opera73+Edge87+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS15.2+Chrome Android87+WebView AndroidNoSamsung Internet14.0+Opera AndroidNo

Returns whether scripts running in this global are allowed to use APIs that require cross-origin isolation. This depends on the `Cross-Origin-Opener-Policy` and `Cross-Origin-Embedder-Policy` HTTP response headers and the "cross-origin-isolated" feature.

Developers are strongly encouraged to use self.origin over location.origin. The former returns the origin of the environment, the latter of the URL of the environment. Imagine the following script executing in a document on https://stargate.example/:

var frame = document.createElement("iframe")
frame.onload = function() {
  var frameWin = frame.contentWindow
  console.log(frameWin.location.origin) // "null"
  console.log(frameWin.origin) // "https://stargate.example"
}
document.body.appendChild(frame)

self.origin is a more reliable security indicator.

The isSecureContext getter steps are to return true if this's relevant settings object is a secure context, or false otherwise.

The origin getter steps are to return this's relevant settings object's origin, serialized.

The crossOriginIsolated getter steps are to return this's relevant settings object's cross-origin isolated capability.

8.3 Base64 utility methods

The atob() and btoa() methods allow developers to transform content to and from the base64 encoding.

In these APIs, for mnemonic purposes, the "b" can be considered to stand for "binary", and the "a" for "ASCII". In practice, though, for primarily historical reasons, both the input and output of these functions are Unicode strings.

result = self . btoa( data )

btoa

Support in all current engines.

Firefox1+Safari3+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

Takes the input data, in the form of a Unicode string containing only characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, and converts it to its base64 representation, which it returns.

Throws an "InvalidCharacterError" DOMException exception if the input string contains any out-of-range characters.

result = self . atob( data )

atob

Support in all current engines.

Firefox1+Safari3+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

Takes the input data, in the form of a Unicode string containing base64-encoded binary data, decodes it, and returns a string consisting of characters in the range U+0000 to U+00FF, each representing a binary byte with values 0x00 to 0xFF respectively, corresponding to that binary data.

Throws an "InvalidCharacterError" DOMException if the input string is not valid base64 data.

The btoa(data) method must throw an "InvalidCharacterError" DOMException if data contains any character whose code point is greater than U+00FF. Otherwise, the user agent must convert data to a byte sequence whose nth byte is the eight-bit representation of the nth code point of data, and then must apply forgiving-base64 encode to that byte sequence and return the result.

The atob(data) method, when invoked, must run the following steps:

  1. Let decodedData be the result of running forgiving-base64 decode on data.

  2. If decodedData is failure, then throw an "InvalidCharacterError" DOMException.

  3. Return decodedData.

8.4 Dynamic markup insertion

APIs for dynamically inserting markup into the document interact with the parser, and thus their behavior varies depending on whether they are used with HTML documents (and the HTML parser) or XML documents (and the XML parser).

Document objects have a throw-on-dynamic-markup-insertion counter, which is used in conjunction with the create an element for the token algorithm to prevent custom element constructors from being able to use document.open(), document.close(), and document.write() when they are invoked by the parser. Initially, the counter must be set to zero.

8.4.1 Opening the input stream

document = document . open( )

Document/open

Support in all current engines.

Firefox1+Safari11+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS11+Chrome Android64+WebView Android64+Samsung Internet9.0+Opera Android47+

Causes the Document to be replaced in-place, as if it was a new Document object, but reusing the previous object, which is then returned.

The resulting Document has an HTML parser associated with it, which can be given data to parse using document.write().

The method has no effect if the Document is still being parsed.

Throws an "InvalidStateError" DOMException if the Document is an XML document.

Throws an "InvalidStateError" DOMException if the parser is currently executing a custom element constructor.

window = document . open( url, name, features )

Works like the window.open() method.

Document objects have an ignore-opens-during-unload counter, which is used to prevent scripts from invoking the document.open() method (directly or indirectly) while the document is being unloaded. Initially, the counter must be set to zero.

Document objects have an active parser was aborted boolean, which is used to prevent scripts from invoking the document.open() and document.write() methods (directly or indirectly) after the document's active parser has been aborted. It is initially false.

The document open steps, given a document, are as follows:

  1. If document is an XML document, then throw an "InvalidStateError" DOMException exception.

  2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.

  3. Let entryDocument be the entry global object's associated Document.

  4. If document's origin is not same origin to entryDocument's origin, then throw a "SecurityError" DOMException.

  5. If document has an active parser whose script nesting level is greater than 0, then return document.

    This basically causes document.open() to be ignored when it's called in an inline script found during parsing, while still letting it have an effect when called from a non-parser task such as a timer callback or event handler.

  6. Similarly, if document's ignore-opens-during-unload counter is greater than 0, then return document.

    This basically causes document.open() to be ignored when it's called from a beforeunload, pagehide, or unload event handler while the Document is being unloaded.

  7. If document's active parser was aborted is true, then return document.

    This notably causes document.open() to be ignored if it is called after a navigation has started, but only during the initial parse. See issue #4723 for more background.

  8. If document's browsing context is non-null and there is an existing attempt to navigate document's browsing context, then stop document loading given document.

    Issue #3447 looks into the distinction between an ongoing instance of the navigate algorithm versus tasks to navigate that are still queued. For the purpose of implementing this step, both an ongoing instance of the navigate algorithm and tasks queued to navigate should be counted towards "an existing attempt to navigate," at least until that issue is resolved.

  9. For each shadow-including inclusive descendant node of document, erase all event listeners and handlers given node.

  10. If document is the associated Document of document's relevant global object, then erase all event listeners and handlers given document's relevant global object.

  11. Replace all with null within document, without firing any mutation events.

  12. If document is fully active, then:

    1. Let newURL be a copy of entryDocument's URL.

    2. If entryDocument is not document, then set newURL's fragment to null.

    3. Run the URL and history update steps with document and newURL.

  13. If document's iframe load in progress flag is set, then set document's mute iframe load flag.

  14. Set document to no-quirks mode.

  15. Create a new HTML parser and associate it with document. This is a script-created parser (meaning that it can be closed by the document.open() and document.close() methods, and that the tokenizer will wait for an explicit call to document.close() before emitting an end-of-file token). The encoding confidence is irrelevant.

  16. Set the current document readiness of document to "loading".

  17. Finally, set the insertion point to point at just before the end of the input stream (which at this point will be empty).

  18. Return document.

The document open steps do not affect whether a Document is ready for post-load tasks or completely loaded.

The open(unused1, unused2) method must return the result of running the document open steps with this Document object.

The unused1 and unused2 arguments are ignored, but kept in the IDL to allow code that calls the function with one or two arguments to continue working. They are necessary due to Web IDL overload resolution algorithm rules, which would throw a TypeError exception for such calls had the arguments not been there. heycam/webidl issue #581 investigates changing the algorithm to allow for their removal. [WEBIDL]

The open(url, name, features) method must run these steps:

  1. If this Document object is not an active document, then throw an "InvalidAccessError" DOMException exception.

  2. Return the result of running the window open steps with url, name, and features.

8.4.2 Closing the input stream

document . close()

Document/close

Support in all current engines.

Firefox1+Safari11+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS11+Chrome Android64+WebView Android64+Samsung Internet9.0+Opera Android47+

Closes the input stream that was opened by the document.open() method.

Throws an "InvalidStateError" DOMException if the Document is an XML document.

Throws an "InvalidStateError" DOMException if the parser is currently executing a custom element constructor.

The close() method must run the following steps:

  1. If the Document object is an XML document, then throw an "InvalidStateError" DOMException.

  2. If the Document object's throw-on-dynamic-markup-insertion counter is greater than zero, then throw an "InvalidStateError" DOMException.

  3. If there is no script-created parser associated with the document, then return.

  4. Insert an explicit "EOF" character at the end of the parser's input stream.

  5. If there is a pending parsing-blocking script, then return.

  6. Run the tokenizer, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the explicit "EOF" character or spins the event loop.

8.4.3 document.write()

document . write(text...)

Document/write

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

In general, adds the given string(s) to the Document's input stream.

This method has very idiosyncratic behavior. In some cases, this method can affect the state of the HTML parser while the parser is running, resulting in a DOM that does not correspond to the source of the document (e.g. if the string written is the string "<plaintext>" or "<!--"). In other cases, the call can clear the current page first, as if document.open() had been called. In yet more cases, the method is simply ignored, or throws an exception. Users agents are explicitly allowed to avoid executing script elements inserted via this method. And to make matters even worse, the exact behavior of this method can in some cases be dependent on network latency, which can lead to failures that are very hard to debug. For all these reasons, use of this method is strongly discouraged.

Throws an "InvalidStateError" DOMException when invoked on XML documents.

Throws an "InvalidStateError" DOMException if the parser is currently executing a custom element constructor.

Document objects have an ignore-destructive-writes counter, which is used in conjunction with the processing of script elements to prevent external scripts from being able to use document.write() to blow away the document by implicitly calling document.open(). Initially, the counter must be set to zero.

The document write steps, given a Document object document and a string input, are as follows:

  1. If document is an XML document, then throw an "InvalidStateError" DOMException.

  2. If document's throw-on-dynamic-markup-insertion counter is greater than 0, then throw an "InvalidStateError" DOMException.

  3. If document's active parser was aborted is true, then return.

  4. If the insertion point is undefined, then:

    1. If document's ignore-opens-during-unload counter is greater than 0 or document's ignore-destructive-writes counter is greater than 0, then return.

    2. Run the document open steps with document.

  5. Insert input into the input stream just before the insertion point.

  6. If there is no pending parsing-blocking script, have the HTML parser process input, one code point at a time, processing resulting tokens as they are emitted, and stopping when the tokenizer reaches the insertion point or when the processing of the tokenizer is aborted by the tree construction stage (this can happen if a script end tag token is emitted by the tokenizer).

    If the document.write() method was called from script executing inline (i.e. executing because the parser parsed a set of script tags), then this is a reentrant invocation of the parser. If the parser pause flag is set, the tokenizer will abort immediately and no HTML will be parsed, per the tokenizer's parser pause flag check.

The document.write(...) method, when invoked, must run the document write steps with this Document object and a string that is the concatanation of all arguments passed.

8.4.4 document.writeln()

document . writeln(text...)

Document/writeln

Support in all current engines.

Firefox1+Safari11+Chrome64+
Opera51+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS11+Chrome Android64+WebView Android64+Samsung Internet9.0+Opera Android47+

Adds the given string(s) to the Document's input stream, followed by a newline character. If necessary, calls the open() method implicitly first.

Throws an "InvalidStateError" DOMException when invoked on XML documents.

Throws an "InvalidStateError" DOMException if the parser is currently executing a custom element constructor.

The document.writeln(...) method, when invoked, must run the document write steps with this Document object and a string that is the concatanation of all arguments passed and U+000A LINE FEED.

8.5 DOM parsing

DOMParser

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

The DOMParser interface allows authors to create new Document objects by parsing strings, as either HTML or XML.

parser = new DOMParser()

DOMParser/DOMParser

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Constructs a new DOMParser object.

document = parser . parseFromString( string, type )

DOMParser/parseFromString

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Parses string using either the HTML or XML parser, according to type, and returns the resulting Document. type can be "text/html" (which will invoke the HTML parser), or any of "text/xml", "application/xml", "application/xhtml+xml", or "image/svg+xml" (which will invoke the XML parser).

For the XML parser, if string cannot be parsed, then the returned Document will contain elements describing the resulting error.

Note that script elements are not evaluated during parsing, and the resulting document's encoding will always be UTF-8.

Values other than the above for type will cause a TypeError exception to be thrown.

The design of DOMParser, as a class that needs to be constructed and then have its parseFromString() method called, is an unfortunate historical artifact. If we were designing this functionality today it would be a standalone function.

[Exposed=Window]
interface DOMParser {
  constructor();

  [NewObject] Document parseFromString(DOMString string, DOMParserSupportedType type);
};

enum DOMParserSupportedType {
  "text/html",
  "text/xml",
  "application/xml",
  "application/xhtml+xml",
  "image/svg+xml"
};

The new DOMParser() constructor steps are to do nothing.

The parseFromString(string, type) method steps are:

  1. Let document be a new Document, whose content type is type and url is this's relevant global object's associated Document's URL.

    The document's encoding will be left as its default, of UTF-8. In particular, any XML declarations or meta elements found while parsing string will have no effect.

  2. Switch on type:

    "text/html"
    1. Set document's type to "html".

    2. Create an HTML parser parser, associated with document.

    3. Place string into the input stream for parser. The encoding confidence is irrelevant.

    4. Start parser and let it run until it has consumed all the characters just inserted into the input stream.

      This might mutate the document's mode.

    Since document does not have a browsing context, scripting is disabled.

    Otherwise
    1. Create an XML parser parse, associated with document, and with XML scripting support disabled.

    2. Parse string using parser.

    3. If the previous step resulted in an XML well-formedness or XML namespace well-formedness error, then:

      1. Assert: document has no child nodes.

      2. Let root be the result of creating an element given document, "parsererror", and "http://www.mozilla.org/newlayout/xml/parsererror.xml".

      3. Optionally, add attributes or children to root to describe the nature of the parsing error.

      4. Append root to document.

  3. Return document.

8.6 Timers

The setTimeout() and setInterval() methods allow authors to schedule timer-based callbacks.

handle = self . setTimeout( handler [, timeout [, arguments... ] ] )

setTimeout

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.

handle = self . setTimeout( code [, timeout ] )

Schedules a timeout to compile and run code after timeout milliseconds.

self . clearTimeout( handle )

clearTimeout

Support in all current engines.

Firefox1+Safari4+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

Cancels the timeout set with setTimeout() or setInterval() identified by handle.

handle = self . setInterval( handler [, timeout [, arguments... ] ] )

setInterval

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Schedules a timeout to run handler every timeout milliseconds. Any arguments are passed straight through to the handler.

handle = self . setInterval( code [, timeout ] )

Schedules a timeout to compile and run code every timeout milliseconds.

self . clearInterval( handle )

clearInterval

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

Cancels the timeout set with setInterval() or setTimeout() identified by handle.

Timers can be nested; after five such nested timers, however, the interval is forced to be at least four milliseconds.

This API does not guarantee that timers will run exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.

Objects that implement the WindowOrWorkerGlobalScope mixin have a list of active timers. Each entry in this lists is identified by a number, which must be unique within the list for the lifetime of the object that implements the WindowOrWorkerGlobalScope mixin.


The setTimeout() method must return the value returned by the timer initialization steps, passing them the method's arguments, the object on which the method for which the algorithm is running is implemented (a Window or WorkerGlobalScope object) as the method context, and the repeat flag set to false.

The setInterval() method must return the value returned by the timer initialization steps, passing them the method's arguments, the object on which the method for which the algorithm is running is implemented (a Window or WorkerGlobalScope object) as the method context, and the repeat flag set to true.

The clearTimeout() and clearInterval() methods must clear the entry identified as handle from the list of active timers of the WindowOrWorkerGlobalScope object on which the method was invoked, if any, where handle is the argument passed to the method. (If handle does not identify an entry in the list of active timers of the WindowOrWorkerGlobalScope object on which the method was invoked, the method does nothing.)

Because clearTimeout() and clearInterval() clear entries from the same list, either method can be used to clear timers created by setTimeout() or setInterval().


The timer initialization steps, which are invoked with some method arguments, a method context, a repeat flag which can be true or false, and optionally (and only if the repeat flag is true) a previous handle, are as follows:

  1. Let method context proxy be method context if that is a WorkerGlobalScope object, or else the WindowProxy that corresponds to method context.

  2. If previous handle was provided, let handle be previous handle; otherwise, let handle be an implementation-defined integer that is greater than zero that will identify the timeout to be set by this call in the list of active timers.

  3. If previous handle was not provided, add an entry to the list of active timers for handle.

  4. Let callerRealm be the current Realm Record, and calleeRealm be method context's JavaScript realm.

  5. Let initiating script be the active script.

  6. Assert: initiating script is not null, since this algorithm is always called from some script.

  7. Let task be a task that runs the following substeps:

    1. If the entry for handle in the list of active timers has been cleared, then abort these steps.

    2. Run the appropriate set of steps from the following list:

      If the first method argument is a Function

      Invoke the Function. Use the third and subsequent method arguments (if any) as the arguments for invoking the Function. Use method context proxy as the callback this value. If this throws an exception, catch it, and report the exception.

      Otherwise
      1. Perform HostEnsureCanCompileStrings(callerRealm, calleeRealm). If this throws an exception, catch it, report the exception, and abort these steps.

      2. Let script source be the first method argument.

      3. Let settings object be method context's environment settings object.

      4. Let base URL be initiating script's base URL.

      5. Let fetch options be a script fetch options whose cryptographic nonce is initiating script's fetch options's cryptographic nonce, integrity metadata is the empty string, parser metadata is "not-parser-inserted", credentials mode is initiating script's fetch options's credentials mode, and referrer policy is initiating script's fetch options's referrer policy.

        The effect of these options ensures that the string compilation done by setTimeout() and setInterval() behaves equivalently to that done by eval(). That is, module script fetches via import() will behave the same in both contexts.

      6. Let script be the result of creating a classic script given script source, settings object, base URL, and fetch options.

      7. Run the classic script script.

    3. If the repeat flag is true, then call timer initialization steps again, passing them the same method arguments, the same method context, with the repeat flag still set to true, and with the previous handle set to handler.

  8. Let timeout be the second method argument.

  9. If the currently running task is a task that was created by this algorithm, then let nesting level be the task's timer nesting level. Otherwise, let nesting level be zero.

    The task's timer nesting level is used both for nested calls to setTimeout(), and for the repeating timers created by setInterval(). (Or, indeed, for any combination of the two.) In other words, it represents nested invocations of this algorithm, not of a particular method.

  10. If timeout is less than 0, then set timeout to 0.

  11. If nesting level is greater than 5, and timeout is less than 4, then set timeout to 4.

  12. Increment nesting level by one.

  13. Let task's timer nesting level be nesting level.

  14. Return handle, and then continue running this algorithm in parallel.

  15. If method context is a Window object, wait until the Document associated with method context has been fully active for a further timeout milliseconds (not necessarily consecutively).

    Otherwise, method context is a WorkerGlobalScope object; wait until timeout milliseconds have passed with the worker not suspended (not necessarily consecutively).

  16. Wait until any invocations of this algorithm that had the same method context, that started before this one, and whose timeout is equal to or less than this one's, have completed.

    Argument conversion as defined by Web IDL (for example, invoking toString() methods on objects passed as the first argument) happens in the algorithms defined in Web IDL, before this algorithm is invoked.

    So for example, the following rather silly code will result in the log containing "ONE TWO ":

    var log = '';
    function logger(s) { log += s + ' '; }
    
    setTimeout({ toString: function () {
      setTimeout("logger('ONE')", 100);
      return "logger('TWO')";
    } }, 100);
  17. Optionally, wait a further implementation-defined length of time.

    This is intended to allow user agents to pad timeouts as needed to optimize the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.

  18. Queue a global task on the timer task source given method context to run task.

    Once the task has been processed, if the repeat flag is false, it is safe to remove the entry for handle from the list of active timers (there is no way for the entry's existence to be detected past this point, so it does not technically matter one way or the other).

To run tasks of several milliseconds back to back without any delay, while still yielding back to the browser to avoid starving the user interface (and to avoid the browser killing the script for hogging the CPU), simply queue the next timer before performing work:

function doExpensiveWork() {
  var done = false;
  // ...
  // this part of the function takes up to five milliseconds
  // set done to true if we're done
  // ...
  return done;
}

function rescheduleWork() {
  var handle = setTimeout(rescheduleWork, 0); // preschedule next iteration
  if (doExpensiveWork())
    clearTimeout(handle); // clear the timeout if we don't need it
}

function scheduleWork() {
  setTimeout(rescheduleWork, 0);
}

scheduleWork(); // queues a task to do lots of work

8.7 Microtask queuing

queueMicrotask

Support in all current engines.

Firefox69+Safari12.1+Chrome71+
Opera58+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS12.2+Chrome Android71+WebView Android71+Samsung Internet10.0+Opera Android50+
self . queueMicrotask(callback)

Queues a microtask to run the given callback.

The queueMicrotask(callback) method must queue a microtask to invoke callback, and if callback throws an exception, report the exception.

The queueMicrotask() method allows authors to schedule a callback on the microtask queue. This allows their code to run after the currently-executing task has run to completion and the JavaScript execution context stack is empty, but without yielding control back to the event loop, as would be the case when using, for example, setTimeout(f, 0).

Authors ought to be aware that scheduling a lot of microtasks has the same performance downsides as running a lot of synchronous code. Both will prevent the browser from doing its own work, such as rendering or scrolling. In many cases, requestAnimationFrame() or requestIdleCallback() is a better choice. In particular, if the goal is to run code before the next rendering cycle, that is the purpose of requestAnimationFrame().

As can be seen from the following examples, the best way of thinking about queueMicrotask() is as a mechanism for rearranging synchronous code, effectively placing the queued code immediately after the current task's worth of non-queued JavaScript.

The most common reason for using queueMicrotask() is to create consistent ordering, even in the cases where information is available synchronously, without introducing undue delay.

For example, consider a custom element firing a load event, that also maintains an internal cache of previously-loaded data. A naïve implementation might look like:

MyElement.prototype.loadData = function (url) {
  if (this._cache[url]) {
    this._setData(this._cache[url]);
    this.dispatchEvent(new Event("load"));
  } else {
    fetch(url).then(res => res.arrayBuffer()).then(data => {
      this._cache[url] = data;
      this._setData(data);
      this.dispatchEvent(new Event("load"));
    });
  }
};

This naïve implementation is problematic, however, in that it causes its users to experience inconsistent behavior. For example, code such as

element.addEventListener("load", () => console.log("loaded"));
console.log("1");
element.loadData();
console.log("2");

will sometimes log "1, 2, loaded" (if the data needs to be fetched), and sometimes log "1, loaded, 2" (if the data is already cached). Similarly, after the call to loadData(), it will be inconsistent whether or not the data is set on the element.

To get a consistent ordering, queueMicrotask() can be used:

MyElement.prototype.loadData = function (url) {
  if (this._cache[url]) {
    queueMicrotask(() => {
      this._setData(this._cache[url]);
      this.dispatchEvent(new Event("load"));
    });
  } else {
    fetch(url).then(res => res.arrayBuffer()).then(data => {
      this._cache[url] = data;
      this._setData(data);
      this.dispatchEvent(new Event("load"));
    });
  }
};

By essentially rearranging the queued code to be after the currently-executing task, this ensures a consistent ordering and update of the element's state.

Another interesting use of queueMicrotask() is to allow uncoordinated "batching" of work by multiple callers. For example, consider a library function that wants to send data somewhere as soon as possible, but doesn't want to make multiple network requests if doing so is easily avoidable. One way to balance this would be like so:

const queuedToSend = [];

function sendData(data) {
  queuedToSend.push(data);

  if (queuedToSend.length === 1) {
    queueMicrotask(() => {
      const stringToSend = JSON.stringify(queuedToSend);
      queuedToSend.length = 0;

      fetch("/endpoint", stringToSend);
    });
  }
}

With this architecture, multiple subsequent calls to sendData() within the same turn of the event loop will be batched together into one fetch() call, but with no intervening event loop tasks preempting the fetch (as would have happened with similar code that instead used setTimeout()).

8.8 用户提示

8.8.1 Simple dialogs

window . alert(message)

Window/alert

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Displays a modal alert with the given message, and waits for the user to dismiss it.

result = window . confirm(message)

Window/confirm

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Displays a modal OK/Cancel prompt with the given message, waits for the user to dismiss it, and returns true if the user clicks OK and false if the user clicks Cancel.

result = window . prompt(message [, default] )

Window/prompt

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Displays a modal text control prompt with the given message, waits for the user to dismiss it, and returns the value that the user entered. If the user cancels the prompt, then returns null instead. If the second argument is present, then the given value is used as a default.

Logic that depends on tasks or microtasks, such as media elements loading their media data, are stalled when these methods are invoked.

To optionally truncate a simple dialog string s, return either s itself or some string derived from s that is shorter. User agents should not provide UI for displaying the elided portion of s, as this makes it too easy for abusers to create dialogs of the form "Important security alert! Click 'Show More' for full details!".

For example, a user agent might want to only display the first 100 characters of a message. Or, a user agent might replace the middle of the string with "…". These types of modifications can be useful in limiting the abuse potential of unnaturally large, trustworthy-looking system dialogs.

The alert(message) method, when invoked, must run the following steps:

  1. If the event loop's termination nesting level is nonzero, optionally return.

  2. If the active sandboxing flag set of this Window object's associated Document has the sandboxed modals flag set, then return.

  3. Optionally, return. (For example, the user agent might give the user the option to ignore all alerts, and would thus abort at this step whenever the method was invoked.)

  4. If the method was invoked with no arguments, then let message be the empty string; otherwise, let message be the method's first argument.

  5. Set message to the result of normalizing newlines given message.

  6. Set message to the result of optionally truncating message.

  7. Show message to the user, treating U+000A LF as a line break.

  8. Optionally, pause while waiting for the user to acknowledge the message.

The confirm(message) method, when invoked, must run the following steps:

  1. If the event loop's termination nesting level is nonzero, optionally return false.

  2. If the active sandboxing flag set of this Window object's associated Document has the sandboxed modals flag set, then return.

  3. Optionally, return false. (For example, the user agent might give the user the option to ignore all prompts, and would thus abort at this step whenever the method was invoked.)

  4. Set message to the result of normalizing newlines given message.

  5. Set message to the result of optionally truncating message.

  6. Show message to the user, treating U+000A LF as a line break, and ask the user to respond with a positive or negative response.

  7. Pause until the user responds either positively or negatively.

  8. If the user responded positively, return true; otherwise, the user responded negatively: return false.

The prompt(message, default) method, when invoked, must run the following steps:

  1. If the event loop's termination nesting level is nonzero, optionally return null.

  2. If the active sandboxing flag set of this Window object's associated Document has the sandboxed modals flag set, then return.

  3. Optionally, return null. (For example, the user agent might give the user the option to ignore all prompts, and would thus abort at this step whenever the method was invoked.)

  4. Set message to the result of optionally truncating message.

  5. Set message to the result of normalizing newlines given message.

  6. Set default to the result of optionally truncating default.

  7. Show message to the user, treating U+000A LF as a line break, and ask the user to either respond with a string value or abort. The response must be defaulted to the value given by default.

  8. Pause while waiting for the user's response.

  9. If the user aborts, then return null; otherwise, return the string that the user responded with.

8.8.2 Printing

Window/print

Support in all current engines.

Firefox1+Safari1.1+Chrome1+
Opera6+Edge79+
Edge (Legacy)12+Internet Explorer5+
Firefox AndroidNoSafari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
window . print()

Prompts the user to print the page.

When the print() method is invoked, if the Document is ready for post-load tasks, then the user agent must run the printing steps. Otherwise, the user agent must only set the print when loaded flag on the Document.

User agents should also run the printing steps whenever the user asks for the opportunity to obtain a physical form (e.g. printed copy), or the representation of a physical form (e.g. PDF copy), of a document.

The printing steps are as follows:

  1. The user agent may display a message to the user or return (or both).

    For instance, a kiosk browser could silently ignore any invocations of the print() method.

    For instance, a browser on a mobile device could detect that there are no printers in the vicinity and display a message saying so before continuing to offer a "save to PDF" option.

  2. If the active sandboxing flag set of this Window object's associated Document has the sandboxed modals flag set, then return.

    If the printing dialog is blocked by a Document's sandbox, then neither the beforeprint nor afterprint events will be fired.

  3. The user agent must fire an event named beforeprint at the relevant global object of the Document that is being printed, as well as any child browsing contexts in it.

    The beforeprint event can be used to annotate the printed copy, for instance adding the time at which the document was printed.

  4. The user agent should offer the user the opportunity to obtain a physical form (or the representation of a physical form) of the document. The user agent may wait for the user to either accept or decline before returning; if so, the user agent must pause while the method is waiting. Even if the user agent doesn't wait at this point, the user agent must use the state of the relevant documents as they are at this point in the algorithm if and when it eventually creates the alternate form.

  5. The user agent must fire an event named afterprint at the relevant global object of the Document that is being printed, as well as any child browsing contexts in it.

    The afterprint event can be used to revert annotations added in the earlier event, as well as showing post-printing UI. For instance, if a page is walking the user through the steps of applying for a home loan, the script could automatically advance to the next step after having printed a form or other.

8.9 System state and capabilities

8.9.1 The Navigator object

Navigator

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Window/navigator

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera3+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

The navigator attribute of the Window interface must return an instance of the Navigator interface, which represents the identity and state of the user agent (the client), and allows web pages to register themselves as potential protocol handlers:

[Exposed=Window]
interface Navigator {
  // objects implementing this interface also implement the interfaces given below
};
Navigator includes NavigatorID;
Navigator includes NavigatorLanguage;
Navigator includes NavigatorOnLine;
Navigator includes NavigatorContentUtils;
Navigator includes NavigatorCookies;
Navigator includes NavigatorPlugins;
Navigator includes NavigatorConcurrentHardware;

These interface mixins are defined separately so that WorkerNavigator can re-use parts of the Navigator interface.

8.9.1.1 Client identification
interface mixin NavigatorID {
  readonly attribute DOMString appCodeName; // constant "Mozilla"
  readonly attribute DOMString appName; // constant "Netscape"
  readonly attribute DOMString appVersion;
  readonly attribute DOMString platform;
  readonly attribute DOMString product; // constant "Gecko"
  [Exposed=Window] readonly attribute DOMString productSub;
  readonly attribute DOMString userAgent;
  [Exposed=Window] readonly attribute DOMString vendor;
  [Exposed=Window] readonly attribute DOMString vendorSub; // constant ""
};

In certain cases, despite the best efforts of the entire industry, web browsers have bugs and limitations that web authors are forced to work around.

This section defines a collection of attributes that can be used to determine, from script, the kind of user agent in use, in order to work around these issues.

The user agent has a navigator compatibility mode, which is either Chrome, Gecko, or WebKit.

The navigator compatibility mode constrains the NavigatorID interface to the combinations of attribute values and presence of taintEnabled() and oscpu that are known to be compatible with existing web content.

Client detection should always be limited to detecting known current versions; future versions and unknown versions should always be assumed to be fully compliant.

self . navigator . appCodeName

Returns the string "Mozilla".

self . navigator . appName

Returns the string "Netscape".

self . navigator . appVersion

Returns the version of the browser.

self . navigator . platform

Navigator/platform

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns the name of the platform.

self . navigator . product

Returns the string "Gecko".

window . navigator . productSub

Returns either the string "20030107", or the string "20100101".

self . navigator . userAgent

Navigator/userAgent

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

WorkerNavigator/userAgent

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

Returns the complete `User-Agent` header.

window . navigator . vendor

Navigator/vendor

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android14+

Returns either the empty string, the string "Apple Computer, Inc.", or the string "Google Inc.".

window . navigator . vendorSub

Returns the empty string.

appCodeName

Must return the string "Mozilla".

appName

Must return the string "Netscape".

appVersion

Must return either the string "4.0" or a string representing the version of the browser in detail, e.g. "1.0 (VMS; en-US) Mellblomenator/9000".

platform

Must return either the empty string or a string representing the platform on which the browser is executing, e.g. "MacIntel", "Win32", "FreeBSD i386", "WebTV OS".

product

Must return the string "Gecko".

productSub

Must return the appropriate string from the following list:

If the navigator compatibility mode is Chrome or WebKit

The string "20030107".

If the navigator compatibility mode is Gecko

The string "20100101".

userAgent

Must return the default `User-Agent` value.

vendor

Must return the appropriate string from the following list:

If the navigator compatibility mode is Chrome

The string "Google Inc.".

If the navigator compatibility mode is Gecko

The empty string.

If the navigator compatibility mode is WebKit

The string "Apple Computer, Inc.".

vendorSub

Must return the empty string.

If the navigator compatibility mode is Gecko, then the user agent must also support the following partial interface:

partial interface mixin NavigatorID {
  [Exposed=Window] boolean taintEnabled(); // constant false
  [Exposed=Window] readonly attribute DOMString oscpu;
};

The taintEnabled() method must return false.

The oscpu attribute's getter must return either the empty string or a string representing the platform on which the browser is executing, e.g. "Windows NT 10.0; Win64; x64", "Linux x86_64".

(This is a tracking vector.) Any information in this API that varies from user to user can be used to profile the user. In fact, if enough such information is available, a user can actually be uniquely identified. For this reason, user agent implementers are strongly urged to include as little information in this API as possible.

8.9.1.2 Language preferences
interface mixin NavigatorLanguage {
  readonly attribute DOMString language;
  readonly attribute FrozenArray<DOMString> languages;
};
self . navigator . language

Navigator/language

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

WorkerNavigator/language

Support in all current engines.

Firefox3.5+Safari10+Chrome4+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android4+Safari iOS10+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android10.1+

Returns a language tag representing the user's preferred language.

self . navigator . languages

Navigator/languages

Support in all current engines.

Firefox32+Safari10.1+Chrome37+
Opera24+Edge79+
Edge (Legacy)16+Internet ExplorerNo
Firefox Android32+Safari iOS10.3+Chrome Android37+WebView Android37+Samsung Internet3.0+Opera Android24+

WorkerNavigator/languages

Support in all current engines.

Firefox32+Safari10.1+Chrome37+
Opera24+Edge79+
Edge (Legacy)16+Internet ExplorerNo
Firefox Android32+Safari iOS10.3+Chrome Android37+WebView Android37+Samsung Internet3.0+Opera Android24+

Returns an array of language tags representing the user's preferred languages, with the most preferred language first.

The most preferred language is the one returned by navigator.language.

A languagechange event is fired at the Window or WorkerGlobalScope object when the user agent's understanding of what the user's preferred languages are changes.

language

Must return a valid BCP 47 language tag representing either a plausible language or the user's most preferred language. [BCP47]

languages

Must return a frozen array of valid BCP 47 language tags representing either one or more plausible languages, or the user's preferred languages, ordered by preference with the most preferred language first. The same object must be returned until the user agent needs to return different values, or values in a different order. [BCP47]

Whenever the user agent needs to make the navigator.languages attribute of a Window or WorkerGlobalScope object global return a new set of language tags, the user agent must queue a global task on the DOM manipulation task source given global to fire an event named languagechange at global, and wait until that task begins to be executed before actually returning a new value.

To determine a plausible language, the user agent should bear in mind the following:

(This is a tracking vector.) To avoid introducing any more fingerprinting vectors, user agents should use the same list for the APIs defined in this function as for the HTTP `Accept-Language` header.

8.9.1.3 Custom scheme handlers: the registerProtocolHandler() method

Navigator/registerProtocolHandler

Firefox2+SafariNoChrome13+
Opera11.6+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android4+Safari iOSNoChrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo
interface mixin NavigatorContentUtils {
  [SecureContext] undefined registerProtocolHandler(DOMString scheme, USVString url);
  [SecureContext] undefined unregisterProtocolHandler(DOMString scheme, USVString url);
};
window . navigator . registerProtocolHandler(scheme, url)

Registers a handler for scheme at url. For example, an online telephone messaging service could register itself as a handler of the sms: scheme, so that if the user clicks on such a link, they are given the opportunity to use that web site. [SMS]

The string "%s" in url is used as a placeholder for where to put the URL of the content to be handled.

Throws a "SecurityError" DOMException if the user agent blocks the registration (this might happen if trying to register as a handler for "http", for instance).

Throws a "SyntaxError" DOMException if the "%s" string is missing in url.

window . navigator . unregisterProtocolHandler(scheme, url)

Unregisters the handler given by the arguments.

Throws a "SecurityError" DOMException if the user agent blocks the deregistration (this might happen if with invalid schemes, for instance).

Throws a "SyntaxError" DOMException if the "%s" string is missing in url.

The registerProtocolHandler(scheme, url) method steps are:

  1. Let (normalizedScheme, normalizedURLString) be the result of running normalize protocol handler parameters with scheme, url, and this's relevant settings object.

  2. In parallel: register a handler for normalizedScheme and normalizedURLString. User agents may, within the constraints described, do whatever they like. A user agent could, for instance, prompt the user and offer the user the opportunity to add the site to a shortlist of handlers, or make the handlers their default, or cancel the request. User agents could also silently collect the information, providing it only when relevant to the user.

    User agents should keep track of which sites have registered handlers (even if the user has declined such registrations) so that the user is not repeatedly prompted with the same request.

    When the user agent uses this handler for a URL inputURL:

    1. Assert: inputURL's scheme is normalizedScheme.

    2. Let inputURLString be the serialization of inputURL.

    3. Let encodedURL be the result of running UTF-8 percent-encode on inputURLString using the component percent-encode set.

    4. Let handlerURLString be normalizedURLString.

    5. Replace the first instance of "%s" in handlerURLString with encodedURL.

    6. Let resultURL be the result of parsing handlerURLString.

    7. Navigate an appropriate browsing context to resultURL.

    If the user had visited a site at https://example.com/ that made the following call:

    navigator.registerProtocolHandler('web+soup', 'soup?url=%s')

    ...and then, much later, while visiting https://www.example.net/, clicked on a link such as:

    <a href="web+soup:chicken-kïwi">Download our Chicken Kïwi soup!</a>

    ...then the UA might navigate to the following URL:

    https://example.com/soup?url=web+soup:chicken-k%C3%AFwi

    This site could then do whatever it is that it does with soup (synthesize it and ship it to the user, or whatever).

    This does not define when the handler is used. To some extent, the processing model for navigating across documents defines some cases where it is relevant, but in general user agents may use this information wherever they would otherwise consider handing schemes to native plugins or helper applications.

The unregisterProtocolHandler(scheme, url) method steps are:

  1. Let (normalizedScheme, normalizedURLString) be the result of running normalize protocol handler parameters with scheme, url, and this's relevant settings object.

  2. In parallel: unregister the handler described by normalizedScheme and normalizedURLString.


To normalize protocol handler parameters, given a string scheme, a string url, and an environment settings object environment, run these steps:

  1. Set scheme to scheme, converted to ASCII lowercase.

  2. If scheme is neither a safelisted scheme nor a string starting with "web+" followed by one or more ASCII lower alphas, then throw a "SecurityError" DOMException.

    This means that including a colon in scheme (as in "mailto:") will throw.

    The following schemes are the safelisted schemes:

    This list can be changed. If there are schemes that ought to be added, please send feedback.

  3. If url does not contain "%s", then throw a "SyntaxError" DOMException.

  4. Parse url relative to environment.

  5. If that fails, then throw a "SyntaxError" DOMException.

    This is forcibly the case if the %s placeholder is in the host or port of the URL.

  6. If the resulting URL record's scheme is not "https" or the resulting URL record's origin is not same origin with environment's origin, then throw a "SecurityError" DOMException.

  7. Return (scheme, resulting URL string).

    The resulting URL string will by definition not be a valid URL string as it includes the string "%s" which is not a valid component in a URL.

8.9.1.3.1 Security and privacy

Custom scheme handlers can introduce a number of concerns, in particular privacy concerns.

Hijacking all web usage. User agents should not allow schemes that are key to its normal operation, such as an HTTP(S) scheme, to be rerouted through third-party sites. This would allow a user's activities to be trivially tracked, and would allow user information, even in secure connections, to be collected.

Hijacking defaults. User agents are strongly urged to not automatically change any defaults, as this could lead the user to send data to remote hosts that the user is not expecting. New handlers registering themselves should never automatically cause those sites to be used.

Registration spamming. User agents should consider the possibility that a site will attempt to register a large number of handlers, possibly from multiple domains (e.g., by redirecting through a series of pages each on a different domain, and each registering a handler for web+spam: — analogous practices abusing other web browser features have been used by pornography web sites for many years). User agents should gracefully handle such hostile attempts, protecting the user.

Hostile handler metadata. User agents should protect against typical attacks against strings embedded in their interface, for example ensuring that markup or escape characters in such strings are not executed, that null bytes are properly handled, that over-long strings do not cause crashes or buffer overruns, and so forth.

Leaking private data. Web page authors may reference a custom scheme handler using URL data considered private. They might do so with the expectation that the user's choice of handler points to a page inside the organization, ensuring that sensitive data will not be exposed to third parties. However, a user may have registered a handler pointing to an external site, resulting in a data leak to that third party. Implementors might wish to consider allowing administrators to disable custom handlers on certain subdomains, content types, or schemes.

Leaking credentials. User agents must never send username or password information in the URLs that are escaped and included sent to the handler sites. User agents may even avoid attempting to pass to web-based handlers the URLs of resources that are known to require authentication to access, as such sites would be unable to access the resources in question without prompting the user for credentials themselves (a practice that would require the user to know whether to trust the third-party handler, a decision many users are unable to make or even understand).

Interface interference. User agents should be prepared to handle intentionally long arguments to the methods. For example, if the user interface exposed consists of an "accept" button and a "deny" button, with the "accept" binding containing the name of the handler, it's important that a long name not cause the "deny" button to be pushed off the screen.

8.9.1.4 Cookies
interface mixin NavigatorCookies {
  readonly attribute boolean cookieEnabled;
};
window . navigator . cookieEnabled

Navigator/cookieEnabled

Support in all current engines.

Firefox1+Safari1+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12.1+

Returns false if setting a cookie will be ignored, and true otherwise.

The cookieEnabled attribute must return true if the user agent attempts to handle cookies according to HTTP State Management Mechanism, and false if it ignores cookie change requests. [COOKIES]

8.9.1.5 Plugins
interface mixin NavigatorPlugins {
  [SameObject] readonly attribute PluginArray plugins;
  [SameObject] readonly attribute MimeTypeArray mimeTypes;
  boolean javaEnabled();
};

[Exposed=Window,
 LegacyUnenumerableNamedProperties]
interface PluginArray {
  undefined refresh(optional boolean reload = false);
  readonly attribute unsigned long length;
  getter Plugin? item(unsigned long index);
  getter Plugin? namedItem(DOMString name);
};

[Exposed=Window,
 LegacyUnenumerableNamedProperties]
interface MimeTypeArray {
  readonly attribute unsigned long length;
  getter MimeType? item(unsigned long index);
  getter MimeType? namedItem(DOMString name);
};

[Exposed=Window,
 LegacyUnenumerableNamedProperties]
interface Plugin {
  readonly attribute DOMString name;
  readonly attribute DOMString description;
  readonly attribute DOMString filename;
  readonly attribute unsigned long length;
  getter MimeType? item(unsigned long index);
  getter MimeType? namedItem(DOMString name);
};

[Exposed=Window]
interface MimeType {
  readonly attribute DOMString type;
  readonly attribute DOMString description;
  readonly attribute DOMString suffixes; // comma-separated
  readonly attribute Plugin enabledPlugin;
};
window . navigator . plugins . refresh( [ refresh ] )

Updates the lists of supported plugins and MIME types for this page, and reloads the page if the lists have changed.

window . navigator . plugins . length

Returns the number of plugins, represented by Plugin objects, that the user agent reports.

plugin = window . navigator . plugins . item(index)
window . navigator . plugins[index]

Returns the specified Plugin object.

plugin = window . navigator . plugins . item(name)
window . navigator . plugins[name]

Returns the Plugin object for the plugin with the given name.

window . navigator . mimeTypes . length

Returns the number of MIME types, represented by MimeType objects, supported by the plugins that the user agent reports.

mimeType = window . navigator . mimeTypes . item(index)
window . navigator . mimeTypes[index]

Returns the specified MimeType object.

mimeType = window . navigator . mimeTypes . item(name)
window . navigator . mimeTypes[name]

Returns the MimeType object for the given MIME type.

plugin . name

Returns the plugin's name.

plugin . description

Returns the plugin's description.

plugin . filename

Returns the plugin library's filename, if applicable on the current platform.

plugin . length

Returns the number of MIME types, represented by MimeType objects, supported by the plugin.

mimeType = plugin . item(index)
plugin[index]

Returns the specified MimeType object.

mimeType = plugin . item(name)
plugin[name]

Returns the MimeType object for the given MIME type.

mimeType . type

Returns the MIME type.

mimeType . description

Returns the MIME type's description.

mimeType . suffixes

Returns the MIME type's typical file extensions, in a comma-separated list.

mimeType . enabledPlugin

Returns the Plugin object that implements this MIME type.

window . navigator . javaEnabled()

Returns true if there's a plugin that supports the MIME type "application/x-java-vm".

The navigator.plugins attribute must return a PluginArray object.

The navigator.mimeTypes attribute must return a MimeTypeArray object.


A PluginArray object represents none, some, or all of the plugins supported by the user agent, each of which is represented by a Plugin object. Each of these Plugin objects may be hidden plugins. A hidden plugin can't be enumerated, but can still be inspected by using its name.

The fewer plugins are represented by the PluginArray object, and of those, the more that are hidden, the more the user's privacy will be protected. Each exposed plugin increases the number of bits that can be derived for fingerprinting. Hiding a plugin helps, but unless it is an extremely rare plugin, it is likely that a site attempting to derive the list of plugins can still determine whether the plugin is supported or not by probing for it by name (the names of popular plugins are widely known). Therefore not exposing a plugin at all is preferred. Unfortunately, many legacy sites use this feature to determine, for example, which plugin to use to play video. Not exposing any plugins at all might therefore not be entirely plausible.

The PluginArray objects created by a user agent must not be live. The set of plugins represented by the objects must not change once an object is created, except when it is updated by the refresh() method.

Each plugin represented by a PluginArray can support a number of MIME types. For each such plugin, the user agent must pick one or more of these MIME types to be those that are explicitly supported.

The explicitly supported MIME types of a plugin are those that are exposed through the Plugin and MimeTypeArray interfaces. As with plugins themselves, any variation between users regarding what is exposed allows sites to fingerprint users. User agents are therefore encouraged to expose the same MIME types for all users of a plugin, regardless of the actual types supported... at least, within the constraints imposed by compatibility with legacy content.

(This is a tracking vector.) The supported property indices of a PluginArray object are the numbers from zero to the number of non-hidden plugins represented by the object, if any.

(This is a tracking vector.) The length attribute must return the number of non-hidden plugins represented by the object.

The item() method of a PluginArray object must return null if the argument is not one of the object's supported property indices, and otherwise must return the result of running the following steps, using the method's argument as index:

  1. Let list be the Plugin objects representing the non-hidden plugins represented by the PluginArray object.

  2. Sort list alphabetically by the name of each Plugin.

  3. Return the indexth entry in list.

It is important for privacy that the order of plugins not leak additional information, e.g., the order in which plugins were installed.

(This is a tracking vector.) The supported property names of a PluginArray object are the values of the name attributes of all the Plugin objects represented by the PluginArray object.

The namedItem() method of a PluginArray object must return null if the argument is not one of the object's supported property names, and otherwise must return the Plugin object, of those represented by the PluginArray object, that has a name equal to the method's argument.

The refresh() method of the PluginArray object of a Navigator object, when invoked, must check to see if any plugins have been installed or reconfigured since the user agent created the PluginArray object. If so, and the method's argument is true, then the user agent must act as if the location.reload() method was called instead. Otherwise, the user agent must update the PluginArray object and MimeTypeArray object created for attributes of that Navigator object, and the Plugin and MimeType objects created for those PluginArray and MimeTypeArray objects, using the same Plugin objects for cases where the name is the same, and the same MimeType objects for cases where the type is the same, and creating new objects for cases where there were no matching objects immediately prior to the refresh() call. Old Plugin and MimeType objects must continue to return the same values that they had prior to the update, though naturally now the data is stale and may appear inconsistent (for example, an old MimeType entry might list as its enabledPlugin a Plugin object that no longer lists that MimeType as a supported MimeType).


A MimeTypeArray object represents the MIME types explicitly supported by plugins supported by the user agent, each of which is represented by a MimeType object.

The MimeTypeArray objects created by a user agent must not be live. The set of MIME types represented by the objects must not change once an object is created, except when it is updated by the PluginArray object's refresh() method.

(This is a tracking vector.) The supported property indices of a MimeTypeArray object are the numbers from zero to the number of MIME types explicitly supported by non-hidden plugins represented by the corresponding PluginArray object, if any.

(This is a tracking vector.) The length attribute must return the number of MIME types explicitly supported by non-hidden plugins represented by the corresponding PluginArray object, if any.

The item() method of a MimeTypeArray object must return null if the argument is not one of the object's supported property indices, and otherwise must return the result of running the following steps, using the method's argument as index:

  1. Let list be the MimeType objects representing the MIME types explicitly supported by non-hidden plugins represented by the corresponding PluginArray object, if any.

  2. Sort list alphabetically by the type of each MimeType.

  3. Return the indexth entry in list.

It is important for privacy that the order of MIME types not leak additional information, e.g., the order in which plugins were installed.

(This is a tracking vector.) The supported property names of a MimeTypeArray object are the values of the type attributes of all the MimeType objects represented by the MimeTypeArray object.

The namedItem() method of a MimeTypeArray object must return null if the argument is not one of the object's supported property names, and otherwise must return the MimeType object that has a type equal to the method's argument.


A Plugin object represents a plugin. It has several attributes to provide details about the plugin, and can be enumerated to obtain the list of MIME types that it explicitly supports.

The Plugin objects created by a user agent must not be live. The set of MIME types represented by the objects, and the values of the objects' attributes, must not change once an object is created, except when updated by the PluginArray object's refresh() method.

The reported MIME types for a Plugin object are the MIME types explicitly supported by the corresponding plugin when this object was last created or updated by refresh(), whichever happened most recently.

(This is a tracking vector.) The supported property indices of a Plugin object are the numbers from zero to the number of reported MIME types.

(This is a tracking vector.) The length attribute must return the number of reported MIME types.

The item() method of a Plugin object must return null if the argument is not one of the object's supported property indices, and otherwise must return the result of running the following steps, using the method's argument as index:

  1. Let list be the MimeType objects representing the reported MIME types.

  2. Sort list alphabetically by the type of each MimeType.

  3. Return the indexth entry in list.

It is important for privacy that the order of MIME types not leak additional information, e.g., the order in which plugins were installed.

(This is a tracking vector.) The supported property names of a Plugin object are the values of the type attributes of the MimeType objects representing the reported MIME types.

The namedItem() method of a Plugin object must return null if the argument is not one of the object's supported property names, and otherwise must return the MimeType object that has a type equal to the method's argument.

The name attribute must return the plugin's name.

The description and filename attributes must return implementation-defined (in all likelihood, plugin-defined) strings. In each case, the same string must be returned each time, except that the strings returned may change when the refresh() method updates the object.

(This is a tracking vector.) If the values returned by the description or filename attributes vary between versions of a plugin, they can be used both as a fingerprinting vector and, even more importantly, as a trivial way to determine what security vulnerabilities a plugin (and thus a browser) may have. It is thus highly recommended that the description attribute just return the same value as the name attribute, and that the filename attribute return the empty string.


A MimeType object represents a MIME type that is, or was, explicitly supported by a plugin.

The MimeType objects created by a user agent must not be live. The values of the objects' attributes must not change once an object is created, except when updated by the PluginArray object's refresh() method.

The type attribute must return the valid MIME type string with no parameters describing the MIME type.

The description and suffixes attributes must return implementation-defined (in all likelihood, plugin-defined) strings. In each case, the same string must be returned each time, except that the strings returned may change when the refresh() method updates the object.

(This is a tracking vector.) If the values returned by the description or suffixes attributes vary between versions of a plugin, they can be used both as a fingerprinting vector and, even more importantly, as a trivial way to determine what security vulnerabilities a plugin (and thus a browser) may have. It is thus highly recommended that the description attribute just return the same value as the type attribute, and that the suffixes attribute return the empty string.

Commas in the suffixes attribute are interpreted as separating subsequent filename extensions, as in "htm,html".

The enabledPlugin attribute must return the Plugin object that represents the plugin that explicitly supported the MIME type that this MimeType object represents when this object was last created or updated by refresh(), whichever happened most recently.


(This is a tracking vector.) The navigator.javaEnabled() method must return true if the user agent supports a plugin that supports the MIME type "application/x-java-vm"; otherwise it must return false.

8.10 Images

ImageBitmap

Support in all current engines.

Firefox42+Safari15+Chrome50+
Opera37+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android42+Safari iOS15+Chrome Android50+WebView Android50+Samsung Internet5.0+Opera Android37+
[Exposed=(Window,Worker), Serializable, Transferable]
interface ImageBitmap {
  readonly attribute unsigned long width;
  readonly attribute unsigned long height;
  undefined close();
};

typedef (CanvasImageSource or
         Blob or
         ImageData) ImageBitmapSource;

enum ImageOrientation { "none", "flipY" };
enum PremultiplyAlpha { "none", "premultiply", "default" };
enum ColorSpaceConversion { "none", "default" };
enum ResizeQuality { "pixelated", "low", "medium", "high" };

dictionary ImageBitmapOptions {
  ImageOrientation imageOrientation = "none";
  PremultiplyAlpha premultiplyAlpha = "default";
  ColorSpaceConversion colorSpaceConversion = "default";
  [EnforceRange] unsigned long resizeWidth;
  [EnforceRange] unsigned long resizeHeight;
  ResizeQuality resizeQuality = "low";
};

An ImageBitmap object represents a bitmap image that can be painted to a canvas without undue latency.

The exact judgement of what is undue latency of this is left up to the implementer, but in general if making use of the bitmap requires network I/O, or even local disk I/O, then the latency is probably undue; whereas if it only requires a blocking read from a GPU or system RAM, the latency is probably acceptable.

promise = self . createImageBitmap(image [, options ])

createImageBitmap

Support in all current engines.

Firefox42+Safari15+Chrome50+
Opera37+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android42+Safari iOS15+Chrome Android50+WebView Android50+Samsung Internet5.0+Opera Android37+
promise = self . createImageBitmap(image, sx, sy, sw, sh [, options ])

Takes image, which can be an img element, an SVG image element, a video element, a canvas element, a Blob object, an ImageData object, or another ImageBitmap object, and returns a promise that is resolved when a new ImageBitmap is created.

If no ImageBitmap object can be constructed, for example because the provided image data is not actually an image, then the promise is rejected instead.

If sx, sy, sw, and sh arguments are provided, the source image is cropped to the given pixels, with any pixels missing in the original replaced by transparent black. These coordinates are in the source image's pixel coordinate space, not in CSS pixels.

If options is provided, the ImageBitmap object's bitmap data is modified according to options. For example, if the premultiplyAlpha option is set to "premultiply", the bitmap data's color channels are premultiplied by its alpha channel.

Rejects the promise with an "InvalidStateError" DOMException if the source image is not in a valid state (e.g., an img element that hasn't loaded successfully, an ImageBitmap object whose [[Detached]] internal slot value is true, an ImageData object whose data attribute value's [[ViewedArrayBuffer]] internal slot is detached, or a Blob whose data cannot be interpreted as a bitmap image).

Rejects the promise with a "SecurityError" DOMException if the script is not allowed to access the image data of the source image (e.g. a video that is CORS-cross-origin, or a canvas being drawn on by a script in a worker from another origin).

imageBitmap . close()

ImageBitmap/close

Support in all current engines.

Firefox46+Safari15+Chrome52+
Opera37+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android46+Safari iOS15+Chrome Android52+WebView Android52+Samsung Internet6.0+Opera Android37+

Releases imageBitmap's underlying bitmap data.

imageBitmap . width

ImageBitmap/width

Support in all current engines.

Firefox42+Safari15+Chrome50+
Opera37+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android42+Safari iOS15+Chrome Android50+WebView Android50+Samsung Internet5.0+Opera Android37+

Returns the intrinsic width of the image, in CSS pixels.

imageBitmap . height

ImageBitmap/height

Support in all current engines.

Firefox42+Safari15+Chrome50+
Opera37+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android42+Safari iOS15+Chrome Android50+WebView Android50+Samsung Internet5.0+Opera Android37+

Returns the intrinsic height of the image, in CSS pixels.

An ImageBitmap object whose [[Detached]] internal slot value is false always has associated bitmap data, with a width and a height. However, it is possible for this data to be corrupted. If an ImageBitmap object's media data can be decoded without errors, it is said to be fully decodable.

An ImageBitmap object's bitmap has an origin-clean flag, which indicates whether the bitmap is tainted by content from a different origin. The flag is initially set to true and may be changed to false by the steps of createImageBitmap().


ImageBitmap objects are serializable objects and transferable objects.

Their serialization steps, given value and serialized, are:

  1. If value's origin-clean flag is not set, then throw a "DataCloneError" DOMException.

  2. Set serialized.[[BitmapData]] to a copy of value's bitmap data.

Their deserialization steps, given serialized and value, are:

  1. Set value's bitmap data to serialized.[[BitmapData]].

Their transfer steps, given value and dataHolder, are:

  1. If value's origin-clean flag is not set, then throw a "DataCloneError" DOMException.

  2. Set dataHolder.[[BitmapData]] to value's bitmap data.

  3. Unset value's bitmap data.

Their transfer-receiving steps, given dataHolder and value, are:

  1. Set value's bitmap data to dataHolder.[[BitmapData]].


The createImageBitmap(image, options) and createImageBitmap(image sx, sy, sw, sh, options) methods, when invoked, must run these steps:

  1. Let p be a new promise.

  2. If either sw or sh is given and is 0, then return p rejected with a RangeError.

  3. If either options's resizeWidth or options's resizeHeight is present and is 0, then return p rejected with an "InvalidStateError" DOMException.

  4. Check the usability of the image argument. If this throws an exception or returns bad, then return p rejected with an "InvalidStateError" DOMException.

  5. Let imageBitmap be a new ImageBitmap object.

  6. Switch on image:

    img
    SVG image
    1. If image's media data has no intrinsic dimensions (e.g., it's a vector graphic with no specified content size) and either options's resizeWidth or options's resizeHeight is not present, then return p rejected with an "InvalidStateError" DOMException.

    2. If image's media data has no intrinsic dimensions (e.g., it's a vector graphics with no specified content size), it should be rendered to a bitmap of the size specified by the resizeWidth and the resizeHeight options.

    3. Set imageBitmap's bitmap data to a copy of image's media data, cropped to the source rectangle with formatting. If this is an animated image, imageBitmap's bitmap data must only be taken from the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation.

    4. If the origin of image's image is not same origin with entry settings object's origin, then set the origin-clean flag of imageBitmap's bitmap to false.

    5. Run this step in parallel:

      1. Resolve p with imageBitmap.

    video
    1. If image's networkState attribute is NETWORK_EMPTY, then return p rejected with an "InvalidStateError" DOMException.

    2. Set imageBitmap's bitmap data to a copy of the frame at the current playback position, at the media resource's intrinsic width and intrinsic height (i.e., after any aspect-ratio correction has been applied), cropped to the source rectangle with formatting.

    3. If the origin of image's video is not same origin with entry settings object's origin, then set the origin-clean flag of imageBitmap's bitmap to false.

    4. Run this step in parallel:

      1. Resolve p with imageBitmap.

    canvas
    1. Set imageBitmap's bitmap data to a copy of image's bitmap data, cropped to the source rectangle with formatting.

    2. Set the origin-clean flag of the imageBitmap's bitmap to the same value as the origin-clean flag of image's bitmap.

    3. Run this step in parallel:

      1. Resolve p with imageBitmap.

    Blob

    Run these step in parallel:

    1. Let imageData be the result of reading image's data. If an error occurs during reading of the object, then reject p with an "InvalidStateError" DOMException and abort these steps.

    2. Apply the image sniffing rules to determine the file format of imageData, with MIME type of image (as given by image's type attribute) giving the official type.

    3. If imageData is not in a supported image file format (e.g., it's not an image at all), or if imageData is corrupted in some fatal way such that the image dimensions cannot be obtained (e.g., a vector graphic with no intrinsic size), then reject p with an "InvalidStateError" DOMException and abort these steps.

    4. Set imageBitmap's bitmap data to imageData, cropped to the source rectangle with formatting. If this is an animated image, imageBitmap's bitmap data must only be taken from the default image of the animation (the one that the format defines is to be used when animation is not supported or is disabled), or, if there is no such image, the first frame of the animation.

    5. Resolve p with imageBitmap.

    ImageData
    1. Let buffer be image's data attribute value's [[ViewedArrayBuffer]] internal slot.

    2. If IsDetachedBuffer(buffer) is true, then return p rejected with an "InvalidStateError" DOMException.

    3. Set imageBitmap's bitmap data to image's image data, cropped to the source rectangle with formatting.

    4. Run this step in parallel:

      1. Resolve p with imageBitmap.

    ImageBitmap
    1. Set imageBitmap's bitmap data to a copy of image's bitmap data, cropped to the source rectangle with formatting.

    2. Set the origin-clean flag of imageBitmap's bitmap to the same value as the origin-clean flag of image's bitmap.

    3. Run this step in parallel:

      1. Resolve p with imageBitmap.

  7. Return p.

When the steps above require that the user agent crop bitmap data to the source rectangle with formatting, the user agent must run the following steps:

  1. Let input be the bitmap data being transformed.

  2. If sx, sy, sw and sh are specified, let sourceRectangle be a rectangle whose corners are the four points (sx, sy), (sx+sw, sy),(sx+sw, sy+sh), (sx,sy+sh). Otherwise let sourceRectangle be a rectangle whose corners are the four points (0,0), (width of input, 0), (width of input, height of input), (0, height of input).

    If either sw or sh are negative, then the top-left corner of this rectangle will be to the left or above the (sx, sy) point.

  3. Clip sourceRectangle to the dimensions of input.

  4. Let outputWidth be determined as follows:

    If the resizeWidth member of options is specified
    the value of the resizeWidth member of options
    If the resizeWidth member of options is not specified, but the resizeHeight member is specified
    the width of sourceRectangle, times the value of the resizeHeight member of options, divided by the height of sourceRectangle, rounded up to the nearest integer
    If neither resizeWidth nor resizeHeight are specified
    the width of sourceRectangle
  5. Let outputHeight be determined as follows:

    If the resizeHeight member of options is specified
    the value of the resizeHeight member of options
    If the resizeHeight member of options is not specified, but the resizeWidth member is specified
    the height of sourceRectangle, times the value of the resizeWidth member of options, divided by the width of sourceRectangle, rounded up to the nearest integer
    If neither resizeWidth nor resizeHeight are specified
    the height of sourceRectangle
  6. Place input on an infinite transparent black grid plane, positioned so that its top left corner is at the origin of the plane, with the x-coordinate increasing to the right, and the y-coordinate increasing down, and with each pixel in the input image data occupying a cell on the plane's grid.

  7. Let output be the rectangle on the plane denoted by sourceRectangle.

  8. Scale output to the size specified by outputWidth and outputHeight. The user agent should use the value of the resizeQuality option to guide the choice of scaling algorithm.

  9. If the value of the imageOrientation member of options is "flipY", output must be flipped vertically, disregarding any image orientation metadata of the source (such as EXIF metadata), if any. [EXIF]

    If the value is "none", no extra step is required.

  10. If image is an img element or a Blob object, let val be the value of the colorSpaceConversion member of options, and then run these substeps:

    1. If val is "default", the color space conversion behavior is implementation-specific, and should be chosen according to the color space that the implementation uses for drawing images onto the canvas.

    2. If val is "none", output must be decoded without performing any color space conversions. This means that the image decoding algorithm must ignore color profile metadata embedded in the source data as well as the display device color profile.

    The native color space of canvas is currently unspecified, but this is expected to change in the future.

  11. Let val be the value of premultiplyAlpha member of options, and then run these substeps:

    1. If val is "default", the alpha premultiplication behavior is implementation-specific, and should be chosen according to implementation deems optimal for drawing images onto the canvas.

    2. If val is "premultiply", the output that is not premultiplied by alpha must have its color components multiplied by alpha and that is premultiplied by alpha must be left untouched.

    3. If val is "none", the output that is not premultiplied by alpha must be left untouched and that is premultiplied by alpha must have its color components divided by alpha.

  12. Return output.

When the close() method is called, the user agent must run these steps:

  1. Set this ImageBitmap object's [[Detached]] internal slot value to true.

  2. Unset this ImageBitmap object's bitmap data.

The width attribute's getter must run these steps:

  1. If this ImageBitmap object's [[Detached]] internal slot's value is true, then return 0.

  2. Return this ImageBitmap object's width, in CSS pixels.

The height attribute's getter must run these steps:

  1. If this ImageBitmap object's [[Detached]] internal slot's value is true, then return 0.

  2. Return this ImageBitmap object's height, in CSS pixels.

The ResizeQuality enumeration is used to express a preference for the interpolation quality to use when scaling images.

The "pixelated" value indicates a preference to scale the image that maximizes the appearance. Scaling algorithms that "smooth" colors are acceptable, such as bilinear interpolation.

The "low" value indicates a preference for a low level of image interpolation quality. Low-quality image interpolation may be more computationally efficient than higher settings.

The "medium" value indicates a preference for a medium level of image interpolation quality.

The "high" value indicates a preference for a high level of image interpolation quality. High-quality image interpolation may be more computationally expensive than lower settings.

Bilinear scaling is an example of a relatively fast, lower-quality image-smoothing algorithm. Bicubic or Lanczos scaling are examples of image-scaling algorithms that produce higher-quality output. This specification does not mandate that specific interpolation algorithms be used unless the value is "pixelated".

Using this API, a sprite sheet can be precut and prepared:

var sprites = {};
function loadMySprites() {
  var image = new Image();
  image.src = 'mysprites.png';
  var resolver;
  var promise = new Promise(function (arg) { resolver = arg });
  image.onload = function () {
    resolver(Promise.all([
      createImageBitmap(image,  0,  0, 40, 40).then(function (image) { sprites.person = image }),
      createImageBitmap(image, 40,  0, 40, 40).then(function (image) { sprites.grass  = image }),
      createImageBitmap(image, 80,  0, 40, 40).then(function (image) { sprites.tree   = image }),
      createImageBitmap(image,  0, 40, 40, 40).then(function (image) { sprites.hut    = image }),
      createImageBitmap(image, 40, 40, 40, 40).then(function (image) { sprites.apple  = image }),
      createImageBitmap(image, 80, 40, 40, 40).then(function (image) { sprites.snake  = image })
    ]));
  };
  return promise;
}

function runDemo() {
  var canvas = document.querySelector('canvas#demo');
  var context = canvas.getContext('2d');
  context.drawImage(sprites.tree, 30, 10);
  context.drawImage(sprites.snake, 70, 10);
}

loadMySprites().then(runDemo);

8.11 Animation frames

Some objects include the AnimationFrameProvider interface mixin.

callback FrameRequestCallback = undefined (DOMHighResTimeStamp time);

interface mixin AnimationFrameProvider {
  unsigned long requestAnimationFrame(FrameRequestCallback callback);
  undefined cancelAnimationFrame(unsigned long handle);
};
Window includes AnimationFrameProvider;
DedicatedWorkerGlobalScope includes AnimationFrameProvider;

Each AnimationFrameProvider object also has a target object that stores the provider's internal state. It is defined as follows:

If the AnimationFrameProvider is a Window
The Window's associated Document
If the AnimationFrameProvider is a DedicatedWorkerGlobalScope
The DedicatedWorkerGlobalScope

Each target object has a map of animation frame callbacks, which is an ordered map that must be initially empty, and an animation frame callback identifier, which is a number that must initially be zero.

An AnimationFrameProvider provider is considered supported if any of the following hold:


Window/requestAnimationFrame

Support in all current engines.

Firefox23+Safari7+Chrome24+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android23+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android14+

The requestAnimationFrame(callback) method must run the following steps:

  1. If this AnimationFrameProvider is not supported, then throw a "NotSupportedError" DOMException.

  2. Let target be this AnimationFrameProvider's target object.

  3. Increment target's animation frame callback identifier by one, and let handle be the result.

  4. Let callbacks be target's map of animation frame callbacks.

  5. Set callbacks[handle] to callback.

  6. Return handle.

Window/cancelAnimationFrame

Support in all current engines.

Firefox23+Safari7+Chrome24+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android23+Safari iOS7+Chrome Android25+WebView Android4.4+Samsung Internet1.5+Opera Android14+

The cancelAnimationFrame(handle) method must run the following steps:

  1. If this AnimationFrameProvider is not supported, then throw a "NotSupportedError" DOMException.

  2. Let callbacks be this AnimationFrameProvider's target object's map of animation frame callbacks.

  3. Remove callbacks[handle].

To run the animation frame callbacks for a target object target with a timestamp now:

  1. Let callbacks be target's map of animation frame callbacks.

  2. Let callbackHandles be the result of getting the keys of callbacks.

  3. For each handle in callbackHandles, if handle exists in callbacks:

    1. Let callback be callbacks[handle].

    2. Remove callbacks[handle].

    3. Invoke callback, passing now as the only argument, and if an exception is thrown, report the exception.

Inside workers, requestAnimationFrame() can be used together with an OffscreenCanvas transferred from a canvas element. First, in the document, transfer control to the worker:

const offscreenCanvas = document.getElementById("c").transferControlToOffscreen();
worker.postMessage(offscreenCanvas, [offscreenCanvas]);

Then, in the worker, the following code will draw a rectangle moving from left to right:

let ctx, pos = 0;
function draw(dt) {
  ctx.clearRect(0, 0, 100, 100);
  ctx.fillRect(pos, 0, 10, 10);
  pos += 10 * dt;
  requestAnimationFrame(draw);
}

self.onmessage = function(ev) {
  const transferredCanvas = ev.data;
  ctx = transferredCanvas.getContext("2d");
  draw();
};

9 通信

9.1 MessageEvent 接口

服务器发送的事件, Web sockets, 跨文档通信, 通道通信, 和 广播通道 中的 消息 使用 MessageEvent 接口:

[Constructor(DOMString type, optional MessageEventInit eventInitDict), Exposed=(Window,Worker,AudioWorklet)]
interface MessageEvent : Event {
  readonly attribute any data;
  readonly attribute USVString origin;
  readonly attribute DOMString lastEventId;
  readonly attribute MessageEventSource? source;
  readonly attribute FrozenArray<MessagePort> ports;

  void initMessageEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional any data = null, optional USVString origin = "", optional DOMString lastEventId = "", optional MessageEventSource? source = null, optional sequence<MessagePort> ports = []);
};

dictionary MessageEventInit : EventInit {
  any data = null;
  USVString origin = "";
  DOMString lastEventId = "";
  MessageEventSource? source = null;
  sequence<MessagePort> ports = [];
};

typedef (WindowProxy or MessagePort or ServiceWorker) MessageEventSource;
event . data

MessageEvent/data

Support in all current engines.

Firefox3+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

返回消息的数据。

event . origin

MessageEvent/origin

Support in all current engines.

Firefox3+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

返回消息的域,用于 服务器发送的事件跨文档通信

event . lastEventId

MessageEvent/lastEventId

Support in all current engines.

Firefox3+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)17+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

返回 上一个事件 ID 字符串, 用于 服务器发送的事件

event . source

MessageEvent/source

Support in all current engines.

Firefox3+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet ExplorerNo
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

返回源 window 的 WindowProxy, 用于 跨文档通信, 挂载 MessagePort, 以及在 SharedWorkerGlobalScope 对象上触发的 connect 事件中。

event . ports

MessageEvent/ports

Support in all current engines.

Firefox3+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

返回与消息同时发送的 MessagePort 数组, 用于 跨文档通信通道通信

data 属性必须返回它被初始化的值。 表示被发送的消息。

origin 属性必须返回它被初始化的值。 在 服务器发送的事件跨文档通信 中, 它表示发送消息的文档的 (通常是文档的 scheme, 主机名和端口, 不包括它的路径和 fragment)。

lastEventId 属性必须返回它被初始化的值。在 服务器发送的事件 中, 它表示事件源的 上一个事件 ID 字符串

source 属性必须返回它被初始化的值。 在 跨文档通信 中, 它表示发送消息的 Window 对象的 浏览上下文WindowProxy; 在 共享 Worker 使用的 connect 事件中,它表示 正在连接的新 MessagePort

ports 属性必须返回它被初始化的值。 在 跨文档通信通道通信 中它表示, 被发送的 MessagePort 数组。

initMessageEvent() 方法初始化事件的方式必须与命名相似的 initEvent() 方法类似。 [DOM]

很多 API (例如 WebSocketEventSource)都 在它们的 message 事件上直接使用 MessageEvent 接口,而没有使用 MessagePort API。

9.2 服务器发送的事件

Server-sent_events

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera11+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+

9.2.1 概述

This section is non-normative.

为了让服务器能够使用 HTTP 或专用的服务器推送协议推送数据给 Web 页面, 本规范引入了 EventSource 接口。

使用本 API 包括创建 EventSource 对象和注册事件处理器。

var source = new EventSource('updates.cgi');
source.onmessage = function (event) {
  alert(event.data);
};

在服务器端,某个脚本(这个例子中是 "updates.cgi")发送了 下列格式的消息,并设置了 text/event-stream 的 MIME 类型:

data: This is the first message.

data: This is the second message, it
data: has two lines.

data: This is the third message.

作者可以使用不同的事件类型分隔事件。下面这个是有两种事件类型("add" 和 "remove")的流:

event: add
data: 73857293

event: remove
data: 2153

event: add
data: 113411

处理这样的流的脚本可能看起来像这样(其中 addHandlerremoveHandler 函数接受一个参数,就是事件):

var source = new EventSource('updates.cgi');
source.addEventListener('add', addHandler, false);
source.addEventListener('remove', removeHandler, false);

默认的事件类型是 "message"。

事件流总是使用 UTF-8 解码。没有办法声明另外一种字符编码。


事件流请求可以使用 HTTP 301 或 307 重定向,就像普通 HTTP 请求一样。 如果连接关闭客户端会重新连接;可以使用 HTTP 204 No Content 响应码来告诉客户端不要重连了。

使用这个 API 而不是用 XMLHttpRequestiframe 模拟, 可以让用户代理更好地利用网络资源,尤其是用户代理实现者和网络维护者可以事先协调。 其他的好处包括,能显著节约移动设备的电量。 这在下面的一章 无连接推送 中有更详细的讨论。

9.2.2 The EventSource interface

EventSource

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera11+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
[Exposed=(Window,Worker)]
interface EventSource : EventTarget {
  constructor(USVString url, optional EventSourceInit eventSourceInitDict = {});

  readonly attribute USVString url;
  readonly attribute boolean withCredentials;

  // ready state
  const unsigned short CONNECTING = 0;
  const unsigned short OPEN = 1;
  const unsigned short CLOSED = 2;
  readonly attribute unsigned short readyState;

  // networking
  attribute EventHandler onopen;
  attribute EventHandler onmessage;
  attribute EventHandler onerror;
  undefined close();
};

dictionary EventSourceInit {
  boolean withCredentials = false;
};

Each EventSource object has the following associated with it:

Apart from url these are not currently exposed on the EventSource object.

source = new EventSource( url [, { withCredentials: true } ])

EventSource/EventSource

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera11+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12+

Creates a new EventSource object.

url is a string giving the URL that will provide the event stream.

Setting withCredentials to true will set the credentials mode for connection requests to url to "include".

source . close()

EventSource/close

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12+

Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.

source . url

EventSource/url

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12+

Returns the URL providing the event stream.

source . withCredentials

EventSource/withCredentials

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12+

Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.

source . readyState

EventSource/readyState

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12+

Returns the state of this EventSource object's connection. It can have the values described below.

The EventSource(url, eventSourceInitDict) constructor, when invoked, must run these steps:

  1. Let ev be a new EventSource object.

  2. Let settings be ev's relevant settings object.

  3. Let urlRecord be the result of parsing url with settings's API base URL and settings's API URL character encoding.

  4. If urlRecord is failure, then throw a "SyntaxError" DOMException.

  5. Set ev's url to urlRecord.

  6. Let corsAttributeState be Anonymous.

  7. If the value of eventSourceInitDict's withCredentials member is true, then set corsAttributeState to Use Credentials and set ev's withCredentials attribute to true.

  8. Let request be the result of creating a potential-CORS request given urlRecord, the empty string, and corsAttributeState.

  9. Set request's client to settings.

  10. User agents may set `Accept`/`text/event-stream` in request's header list.

  11. Set request's cache mode to "no-store".

  12. Set ev's request to request.

  13. Run this step in parallel:

    1. Fetch request.

  14. Return ev.


The url attribute's getter must return the serialization of this EventSource object's url.

The withCredentials attribute must return the value to which it was last initialized. When the object is created, it must be initialized to false.

The readyState attribute represents the state of the connection. It can have the following values:

CONNECTING (numeric value 0)
The connection has not yet been established, or it was closed and the user agent is reconnecting.
OPEN (numeric value 1)
The user agent has an open connection and is dispatching events as it receives them.
CLOSED (numeric value 2)
The connection is not open, and the user agent is not trying to reconnect. Either there was a fatal error or the close() method was invoked.

When the object is created its readyState must be set to CONNECTING (0). The rules given below for handling the connection define when the value changes.

The close() method must abort any instances of the fetch algorithm started for this EventSource object, and must set the readyState attribute to CLOSED.

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the EventSource interface:

Event handler Event handler event type
onopen

EventSource/open_event

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12+
open
onmessage

EventSource/message_event

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12+
message
onerror

EventSource/error_event

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12+
error

9.2.3 Processing model

The resource indicated in the argument to the EventSource constructor is fetched when the constructor is run.

As data is received, the tasks queued by the networking task source to handle the data must act as follows.

HTTP 200 OK responses with a `Content-Type` header specifying the type `text/event-stream`, ignoring any MIME type parameters, must be processed line by line as described below.

When a successful response with a supported MIME type is received, such that the user agent begins parsing the contents of the stream, the user agent must announce the connection.

The task that the networking task source places on the task queue once fetching for such a resource (with the correct MIME type) has completed must cause the user agent to reestablish the connection in parallel. This applies whether the connection is closed gracefully or unexpectedly (but does not apply when fetching is canceled by the user agent, e.g., in response to window.stop(), since in those cases the final task is actually discarded). It doesn't apply for the error conditions listed below except where explicitly specified.

HTTP 200 OK responses that have a Content-Type specifying an unsupported type, or that have no Content-Type at all, must cause the user agent to fail the connection.

Network errors that prevents the connection from being established in the first place (e.g. DNS errors), should cause the user agent to reestablish the connection in parallel, unless the user agent knows that to be futile, in which case the user agent may fail the connection.

Any other HTTP response code not listed here, as well as the cancelation of the fetch algorithm by the user agent (e.g. in response to window.stop() or the user canceling the network connection manually) must cause the user agent to fail the connection.


When a user agent is to announce the connection, the user agent must queue a task which, if the readyState attribute is set to a value other than CLOSED, sets the readyState attribute to OPEN and fires an event named open at the EventSource object.

When a user agent is to reestablish the connection, the user agent must run the following steps. These steps are run in parallel, not as part of a task. (The tasks that it queues, of course, are run like normal tasks and not themselves in parallel.)

  1. Queue a task to run the following steps:

    1. If the readyState attribute is set to CLOSED, abort the task.

    2. Set the readyState attribute to CONNECTING.

    3. Fire an event named error at the EventSource object.

  2. Wait a delay equal to the reconnection time of the event source.

  3. Optionally, wait some more. In particular, if the previous attempt failed, then user agents might introduce an exponential backoff delay to avoid overloading a potentially already overloaded server. Alternatively, if the operating system has reported that there is no network connectivity, user agents might wait for the operating system to announce that the network connection has returned before retrying.

  4. Wait until the aforementioned task has run, if it has not yet run.

  5. Queue a task to run the following steps:

    1. If the EventSource object's readyState attribute is not set to CONNECTING, return.

    2. Let request be the EventSource object's request.

    3. If the EventSource object's last event ID string is not the empty string, set `Last-Event-ID`/last event ID string, encoded as UTF-8, in request's header list.

    4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section.

When a user agent is to fail the connection, the user agent must queue a task which, if the readyState attribute is set to a value other than CLOSED, sets the readyState attribute to CLOSED and fires an event named error at the EventSource object. Once the user agent has failed the connection, it does not attempt to reconnect!


The task source for any tasks that are queued by EventSource objects is the remote event task source.

9.2.4 Parsing an event stream

This event stream format's MIME type is text/event-stream.

The event stream format is as described by the stream production of the following ABNF, the character set for which is Unicode. [ABNF]

stream        = [ bom ] *event
event         = *( comment / field ) end-of-line
comment       = colon *any-char end-of-line
field         = 1*name-char [ colon [ space ] *any-char ] end-of-line
end-of-line   = ( cr lf / cr / lf )

; characters
lf            = %x000A ; U+000A LINE FEED (LF)
cr            = %x000D ; U+000D CARRIAGE RETURN (CR)
space         = %x0020 ; U+0020 SPACE
colon         = %x003A ; U+003A COLON (:)
bom           = %xFEFF ; U+FEFF BYTE ORDER MARK
name-char     = %x0000-0009 / %x000B-000C / %x000E-0039 / %x003B-10FFFF
                ; a scalar value other than U+000A LINE FEED (LF), U+000D CARRIAGE RETURN (CR), or U+003A COLON (:)
any-char      = %x0000-0009 / %x000B-000C / %x000E-10FFFF
                ; a scalar value other than U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR)

Event streams in this format must always be encoded as UTF-8. [ENCODING]

Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair, a single U+000A LINE FEED (LF) character, or a single U+000D CARRIAGE RETURN (CR) character.

Since connections established to remote servers for such resources are expected to be long-lived, UAs should ensure that appropriate buffering is used. In particular, while line buffering with lines are defined to end with a single U+000A LINE FEED (LF) character is safe, block buffering or line buffering with different expected line endings can cause delays in event dispatch.

9.2.5 Interpreting an event stream

Streams must be decoded using the UTF-8 decode algorithm.

The UTF-8 decode algorithm strips one leading UTF-8 Byte Order Mark (BOM), if any.

The stream must then be parsed by reading everything line by line, with a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair, a single U+000A LINE FEED (LF) character not preceded by a U+000D CARRIAGE RETURN (CR) character, and a single U+000D CARRIAGE RETURN (CR) character not followed by a U+000A LINE FEED (LF) character being the ways in which a line can end.

When a stream is parsed, a data buffer, an event type buffer, and a last event ID buffer must be associated with it. They must be initialized to the empty string

Lines must be processed, in the order they are received, as follows:

If the line is empty (a blank line)

Dispatch the event, as defined below.

If the line starts with a U+003A COLON character (:)

Ignore the line.

If the line contains a U+003A COLON character (:)

Collect the characters on the line before the first U+003A COLON character (:), and let field be that string.

Collect the characters on the line after the first U+003A COLON character (:), and let value be that string. If value starts with a U+0020 SPACE character, remove it from value.

Process the field using the steps described below, using field as the field name and value as the field value.

Otherwise, the string is not empty but does not contain a U+003A COLON character (:)

Process the field using the steps described below, using the whole line as the field name, and the empty string as the field value.

Once the end of the file is reached, any pending data must be discarded. (If the file ends in the middle of an event, before the final empty line, the incomplete event is not dispatched.)


The steps to process the field given a field name and a field value depend on the field name, as given in the following list. Field names must be compared literally, with no case folding performed.

If the field name is "event"

Set the event type buffer to field value.

If the field name is "data"

Append the field value to the data buffer, then append a single U+000A LINE FEED (LF) character to the data buffer.

If the field name is "id"

If the field value does not contain U+0000 NULL, then set the last event ID buffer to the field value. Otherwise, ignore the field.

If the field name is "retry"

If the field value consists of only ASCII digits, then interpret the field value as an integer in base ten, and set the event stream's reconnection time to that integer. Otherwise, ignore the field.

Otherwise

The field is ignored.

When the user agent is required to dispatch the event, the user agent must process the data buffer, the event type buffer, and the last event ID buffer using steps appropriate for the user agent.

For web browsers, the appropriate steps to dispatch the event are as follows:

  1. Set the last event ID string of the event source to the value of the last event ID buffer. The buffer does not get reset, so the last event ID string of the event source remains set to this value until the next time it is set by the server.

  2. If the data buffer is an empty string, set the data buffer and the event type buffer to the empty string and return.

  3. If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer.

  4. Let event be the result of creating an event using MessageEvent, in the relevant Realm of the EventSource object.

  5. Initialize event's type attribute to message, its data attribute to data, its origin attribute to the serialization of the origin of the event stream's final URL (i.e., the URL after redirects), and its lastEventId attribute to the last event ID string of the event source.

  6. If the event type buffer has a value other than the empty string, change the type of the newly created event to equal the value of the event type buffer.

  7. Set the data buffer and the event type buffer to the empty string.

  8. Queue a task which, if the readyState attribute is set to a value other than CLOSED, dispatches the newly created event at the EventSource object.

If an event doesn't have an "id" field, but an earlier event did set the event source's last event ID string, then the event's lastEventId field will be set to the value of whatever the last seen "id" field was.

For other user agents, the appropriate steps to dispatch the event are implementation dependent, but at a minimum they must set the data and event type buffers to the empty string before returning.

The following event stream, once followed by a blank line:

data: YHOO
data: +2
data: 10

...would cause an event message with the interface MessageEvent to be dispatched on the EventSource object. The event's data attribute would contain the string "YHOO\n+2\n10" (where "\n" represents a newline).

This could be used as follows:

var stocks = new EventSource("https://stocks.example.com/ticker.php");
stocks.onmessage = function (event) {
  var data = event.data.split('\n');
  updateStocks(data[0], data[1], data[2]);
};

...where updateStocks() is a function defined as:

function updateStocks(symbol, delta, value) { ... }

...or some such.

The following stream contains four blocks. The first block has just a comment, and will fire nothing. The second block has two fields with names "data" and "id" respectively; an event will be fired for this block, with the data "first event", and will then set the last event ID to "1" so that if the connection died between this block and the next, the server would be sent a `Last-Event-ID` header with the value "1". The third block fires an event with data "second event", and also has an "id" field, this time with no value, which resets the last event ID to the empty string (meaning no `Last-Event-ID` header will now be sent in the event of a reconnection being attempted). Finally, the last block just fires an event with the data " third event" (with a single leading space character). Note that the last still has to end with a blank line, the end of the stream is not enough to trigger the dispatch of the last event.

: test stream

data: first event
id: 1

data:second event
id

data:  third event

The following stream fires two events:

data

data
data

data:

The first block fires events with the data set to the empty string, as would the last block if it was followed by a blank line. The middle block fires an event with the data set to a single newline character. The last block is discarded because it is not followed by a blank line.

The following stream fires two identical events:

data:test

data: test

This is because the space after the colon is ignored if present.

9.2.6 Authoring notes

Legacy proxy servers are known to, in certain cases, drop HTTP connections after a short timeout. To protect against such proxy servers, authors can include a comment line (one starting with a ':' character) every 15 seconds or so.

Authors wishing to relate event source connections to each other or to specific documents previously served might find that relying on IP addresses doesn't work, as individual clients can have multiple IP addresses (due to having multiple proxy servers) and individual IP addresses can have multiple clients (due to sharing a proxy server). It is better to include a unique identifier in the document when it is served and then pass that identifier as part of the URL when the connection is established.

Authors are also cautioned that HTTP chunking can have unexpected negative effects on the reliability of this protocol, in particular if the chunking is done by a different layer unaware of the timing requirements. If this is a problem, chunking can be disabled for serving event streams.

Clients that support HTTP's per-server connection limitation might run into trouble when opening multiple pages from a site if each page has an EventSource to the same domain. Authors can avoid this using the relatively complex mechanism of using unique domain names per connection, or by allowing the user to enable or disable the EventSource functionality on a per-page basis, or by sharing a single EventSource object using a shared worker.

9.2.7 无连接推送和其他特性

在受控环境中运行的用户代理(例如与特定运营商绑定的手机上的浏览器), 可能会将连接管理工作卸载到网络上的代理服务器上。 在这种情况下,出于符合性目的的用户代理被认为包括手机软件和网络代理。

例如,移动设备上的一个浏览器在已经建立连接后,可能检测到这是一个支持的网络, 因此请求这个网络上的一个代理服务器来接管连接的管理工作。 这一情况下的时间线可能是这样的:

  1. 浏览器连接到远程 HTTP 服务器并请求 EventSource 构造器中的作者指定的资源。
  2. 服务器发送了一些消息。
  3. 在两个消息之间,浏览器检测到除了有一个 TCP 连接外整个网络活动是空闲的, 于是决定切换到睡眠模式来保存电量。
  4. 浏览器断开服务器连接。
  5. 浏览器联系网络上的一个服务,并请求它(一个 "推送代理")来代替维护连接。
  6. 这个 "推送代理" 服务联系远程 HTTP 服务器并请求 EventSource 构造器 (可能包含一个 `Last-Event-ID` HTTP 头) 中的作者指定的资源。
  7. 浏览器允许移动设备进入睡眠。
  8. 服务器发送了另一条消息。
  9. "推送代理" 服务使用类似 OMA 的技术将事件传送给移动设备, 该事件仅唤醒足以处理该事件的程序,然后返回到睡眠状态。

这可以减少总的数据用量,因此会节省可观的电量。

除了实现既有 API 和本规范定义的 text/event-stream 连线格式, 以及上述更分散的实现方式之外, 也可以支持由其他 适用规范 定义的事件帧的格式。 本规范中没有定义如何解析和处理它们。

9.2.8 垃圾回收

EventSource 对象的 readyStateCONNECTING 且该对象有一个或更多事件监听器 在监听 open, messageerror 事件时, 调用 EventSource 对象的构造器的 WindowWorkerGlobalScope 对象上 必须有一个指向 EventSource 对象自己的强引用。

EventSource 对象的 readyStateOPEN 且该对象有一个或更多事件监听器 在监听 messageerror 事件时, 调用 EventSource 对象的构造器的 WindowWorkerGlobalScope 对象上 必须有一个指向 EventSource 对象自己的强引用。

远程事件任务源 中存在由 EventSource 对象入队的事件时, 调用 EventSource 对象的构造器的 WindowWorkerGlobalScope 对象上 必须有一个指向那个 EventSource 对象的强引用。

当用户代理要 强制关闭 一个 EventSource 对象时(这在 Document 对象永远消失时就会发生), 用户代理必须终止为这个 EventSource 对象启动的任何 fetch 算法的实例, 同时必须设置 readyState 属性为 CLOSED

如果 EventSource 对象在连接仍然打开的情况下被垃圾回收, 用户代理必须终止为这个 EventSource 对象启动的任何 fetch 算法的实例。

9.2.9 Implementation advice

This section is non-normative.

User agents are strongly urged to provide detailed diagnostic information about EventSource objects and their related network connections in their development consoles, to aid authors in debugging code using this API.

For example, a user agent could have a panel displaying all the EventSource objects a page has created, each listing the constructor's arguments, whether there was a network error, what the CORS status of the connection is and what headers were sent by the client and received from the server to lead to that status, the messages that were received and how they were parsed, and so forth.

Implementations are especially encouraged to report detailed information to their development consoles whenever an error event is fired, since little to no information can be made available in the events themselves.

9.3 Web sockets

9.3.1 概述

This section is non-normative.

为使得 Web 应用能够维持与服务器端进程的双向通信, 本规范引入了 WebSocket 接口。

该接口不允许对底层网络的直接访问。 例如,没有自定义服务器代理消息的话,该接口实现不了 IRC 客户端。

9.3.2 The WebSocket interface

enum BinaryType { "blob", "arraybuffer" };
[Exposed=(Window,Worker)]
interface WebSocket : EventTarget {
  constructor(USVString url, optional (DOMString or sequence<DOMString>) protocols = []);

  readonly attribute USVString url;

  // ready state
  const unsigned short CONNECTING = 0;
  const unsigned short OPEN = 1;
  const unsigned short CLOSING = 2;
  const unsigned short CLOSED = 3;
  readonly attribute unsigned short readyState;
  readonly attribute unsigned long long bufferedAmount;

  // networking
  attribute EventHandler onopen;
  attribute EventHandler onerror;
  attribute EventHandler onclose;
  readonly attribute DOMString extensions;
  readonly attribute DOMString protocol;
  undefined close(optional [Clamp] unsigned short code, optional USVString reason);

  // messaging
  attribute EventHandler onmessage;
  attribute BinaryType binaryType;
  undefined send(USVString data);
  undefined send(Blob data);
  undefined send(ArrayBuffer data);
  undefined send(ArrayBufferView data);
};

Each WebSocket object has an associated url (a URL record).

socket = new WebSocket(url [, protocols ] )

Creates a new WebSocket object, immediately establishing the associated WebSocket connection.

url is a string giving the URL over which the connection is established. Only "ws" or "wss" schemes are allowed; others will cause a "SyntaxError" DOMException. URLs with fragments will also cause such an exception.

protocols is either a string or an array of strings. If it is a string, it is equivalent to an array consisting of just that string; if it is omitted, it is equivalent to the empty array. Each string in the array is a subprotocol name. The connection will only be established if the server reports that it has selected one of these subprotocols. The subprotocol names have to match the requirements for elements that comprise the value of Sec-WebSocket-Protocol fields as defined by The WebSocket protocol. [WSP]

socket . send( data )

Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.

socket . close( [ code ] [, reason ] )

Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.

socket . url

Returns the URL that was used to establish the WebSocket connection.

socket . readyState

Returns the state of the WebSocket object's connection. It can have the values described below.

socket . bufferedAmount

Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network.

If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.)

socket . extensions

Returns the extensions selected by the server, if any.

socket . protocol

Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation.

socket . binaryType [ = value ]

Returns a string that indicates how binary data from the WebSocket object is exposed to scripts:

"blob"

Binary data is returned in Blob form.

"arraybuffer"

Binary data is returned in ArrayBuffer form.

Can be set, to change how binary data is returned. The default is "blob".

The WebSocket(url, protocols) constructor, when invoked, must run these steps:

  1. Let urlRecord be the result of applying the URL parser to url.

  2. If urlRecord is failure, then throw a "SyntaxError" DOMException.

  3. If urlRecord's scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException.

  4. If urlRecord's fragment is non-null, then throw a "SyntaxError" DOMException.

  5. If protocols is a string, set protocols to a sequence consisting of just that string.

  6. If any of the values in protocols occur more than once or otherwise fail to match the requirements for elements that comprise the value of Sec-WebSocket-Protocol fields as defined by The WebSocket protocol, then throw a "SyntaxError" DOMException. [WSP]

  7. Run this step in parallel:

    1. Establish a WebSocket connection given urlRecord, protocols, and the entry settings object. [FETCH]

      If the establish a WebSocket connection algorithm fails, it triggers the fail the WebSocket connection algorithm, which then invokes the close the WebSocket connection algorithm, which then establishes that the WebSocket connection is closed, which fires the close event as described below.

  8. Return a new WebSocket object whose url is urlRecord.


The url attribute's getter must return this WebSocket object's url, serialized.

The readyState attribute represents the state of the connection. It can have the following values:

CONNECTING (numeric value 0)
The connection has not yet been established.
OPEN (numeric value 1)
The WebSocket connection is established and communication is possible.
CLOSING (numeric value 2)
The connection is going through the closing handshake, or the close() method has been invoked.
CLOSED (numeric value 3)
The connection has been closed or could not be opened.

When the object is created its readyState must be set to CONNECTING (0).

The extensions attribute must initially return the empty string. After the WebSocket connection is established, its value might change, as defined below.

The protocol attribute must initially return the empty string. After the WebSocket connection is established, its value might change, as defined below.

The close(code, reason) method, when invoked, must run these steps:

  1. If code is present, but is neither an integer equal to 1000 nor an integer in the range 3000 to 4999, inclusive, throw an "InvalidAccessError" DOMException.

  2. If reason is present, then run these substeps:

    1. Let reasonBytes be the result of encoding reason.

    2. If reasonBytes is longer than 123 bytes, then throw a "SyntaxError" DOMException.

  3. Run the first matching steps from the following list:

    If the readyState attribute is in the CLOSING (2) or CLOSED (3) state

    Do nothing.

    The connection is already closing or is already closed. If it has not already, a close event will eventually fire as described below.

    If the WebSocket connection is not yet established [WSP]

    Fail the WebSocket connection and set the readyState attribute's value to CLOSING (2). [WSP]

    The fail the WebSocket connection algorithm invokes the close the WebSocket connection algorithm, which then establishes that the WebSocket connection is closed, which fires the close event as described below.

    If the WebSocket closing handshake has not yet been started [WSP]

    Start the WebSocket closing handshake and set the readyState attribute's value to CLOSING (2). [WSP]

    If neither code nor reason is present, the WebSocket Close message must not have a body.

    WebSocket Protocol erroneously states that the status code is required for the start the WebSocket closing handshake algorithm.

    If code is present, then the status code to use in the WebSocket Close message must be the integer given by close. [WSP]

    If reason is also present, then reasonBytes must be provided in the Close message after the status code. [WSP]

    The start the WebSocket closing handshake algorithm eventually invokes the close the WebSocket connection algorithm, which then establishes that the WebSocket connection is closed, which fires the close event as described below.

    Otherwise

    Set the readyState attribute's value to CLOSING (2).

    The WebSocket closing handshake is started, and will eventually invoke the close the WebSocket connection algorithm, which will establish that the WebSocket connection is closed, and thus the close event will fire, as described below.

The close() method does not discard previously sent messages before starting the WebSocket closing handshake — even if, in practice, the user agent is still busy sending those messages, the handshake will only start after the messages are sent.


The bufferedAmount attribute must return the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but that, as of the last time the event loop reached step 1, had not yet been transmitted to the network. (This thus includes any text sent during the execution of the current task, regardless of whether the user agent is able to transmit text in the background in parallel with script execution.) This does not include framing overhead incurred by the protocol, or buffering done by the operating system or network hardware.

In this simple example, the bufferedAmount attribute is used to ensure that updates are sent either at the rate of one update every 50ms, if the network can handle that rate, or at whatever rate the network can handle, if that is too fast.

var socket = new WebSocket('ws://game.example.com:12010/updates');
socket.onopen = function () {
  setInterval(function() {
    if (socket.bufferedAmount == 0)
      socket.send(getUpdateData());
  }, 50);
};

The bufferedAmount attribute can also be used to saturate the network without sending the data at a higher rate than the network can handle, though this requires more careful monitoring of the value of the attribute over time.


When a WebSocket object is created, its binaryType IDL attribute must be set to the string "blob". On getting, it must return the last value it was set to. On setting, the user agent must set the IDL attribute to the new value.

User agents can use the binaryType attribute as a hint for how to handle incoming binary data: if the attribute is set to "blob", it is safe to spool it to disk, and if it is set to "arraybuffer", it is likely more efficient to keep the data in memory. Naturally, user agents are encouraged to use more subtle heuristics to decide whether to keep incoming data in memory or not, e.g. based on how big the data is or how common it is for a script to change the attribute at the last minute. This latter aspect is important in particular because it is quite possible for the attribute to be changed after the user agent has received the data but before the user agent has fired the event for it.

The send(data) method transmits data using the connection. If the readyState attribute is CONNECTING, it must throw an "InvalidStateError" DOMException. Otherwise, the user agent must run the appropriate set of steps from the following list:

If the argument is a string

If the WebSocket connection is established and the WebSocket closing handshake has not yet started, then the user agent must send a WebSocket Message comprised of the data argument using a text frame opcode; if the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must flag the WebSocket as full and then close the WebSocket connection. Any invocation of this method with a string argument that does not throw an exception must increase the bufferedAmount attribute by the number of bytes needed to express the argument as UTF-8. [UNICODE] [ENCODING] [WSP]

If the argument is a Blob object

If the WebSocket connection is established, and the WebSocket closing handshake has not yet started, then the user agent must send a WebSocket Message comprised of data using a binary frame opcode; if the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must flag the WebSocket as full and then close the WebSocket connection. The data to be sent is the raw data represented by the Blob object. Any invocation of this method with a Blob argument that does not throw an exception must increase the bufferedAmount attribute by the size of the Blob object's raw data, in bytes. [WSP] [FILEAPI]

If the argument is an ArrayBuffer object

If the WebSocket connection is established, and the WebSocket closing handshake has not yet started, then the user agent must send a WebSocket Message comprised of data using a binary frame opcode; if the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must flag the WebSocket as full and then close the WebSocket connection. The data to be sent is the data stored in the buffer described by the ArrayBuffer object. Any invocation of this method with an ArrayBuffer argument that does not throw an exception must increase the bufferedAmount attribute by the length of the ArrayBuffer in bytes. [WSP]

If the argument is an object that matches the ArrayBufferView type definition

If the WebSocket connection is established, and the WebSocket closing handshake has not yet started, then the user agent must send a WebSocket Message comprised of data using a binary frame opcode; if the data cannot be sent, e.g. because it would need to be buffered but the buffer is full, the user agent must flag the WebSocket as full and then close the WebSocket connection. The data to be sent is the data stored in the section of the buffer described by the ArrayBuffer object that data references. Any invocation of this method with this kind of argument that does not throw an exception must increase the bufferedAmount attribute by the length of data's buffer in bytes. [WSP]


The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the WebSocket interface:

Event handler Event handler event type
onopen open
onmessage message
onerror error
onclose close

9.3.3 Feedback from the protocol

When the WebSocket connection is established, the user agent must queue a task to run these steps:

  1. Change the readyState attribute's value to OPEN (1).

  2. Change the extensions attribute's value to the extensions in use, if it is not the null value. [WSP]

  3. Change the protocol attribute's value to the subprotocol in use, if it is not the null value. [WSP]

  4. Fire an event named open at the WebSocket object.

Since the algorithm above is queued as a task, there is no race condition between the WebSocket connection being established and the script setting up an event listener for the open event.


When a WebSocket message has been received with type type and data data, the user agent must queue a task to follow these steps: [WSP]

  1. If the readyState attribute's value is not OPEN (1), then return.

  2. Let dataForEvent be determined by switching on type and binaryType:

    type indicates that the data is Text
    a new DOMString containing data
    type indicates that the data is Binary and binaryType is "blob"
    a new Blob object, created in the relevant Realm of the WebSocket object, that represents data as its raw data [FILEAPI]
    type indicates that the data is Binary and binaryType is "arraybuffer"
    a new ArrayBuffer object, created in the relevant Realm of the WebSocket object, whose contents are data
  3. Fire an event named message at the WebSocket object, using MessageEvent, with the origin attribute initialized to the serialization of the WebSocket object's url's origin, and the data attribute initialized to dataForEvent.

User agents are encouraged to check if they can perform the above steps efficiently before they run the task, picking tasks from other task queues while they prepare the buffers if not. For example, if the binaryType attribute was set to "blob" when the data arrived, and the user agent spooled all the data to disk, but just before running the above task for this particular message the script switched binaryType to "arraybuffer", the user agent would want to page the data back to RAM before running this task so as to avoid stalling the main thread while it created the ArrayBuffer object.

Here is an example of how to define a handler for the message event in the case of text frames:

mysocket.onmessage = function (event) {
  if (event.data == 'on') {
    turnLampOn();
  } else if (event.data == 'off') {
    turnLampOff();
  }
};

The protocol here is a trivial one, with the server just sending "on" or "off" messages.


When the WebSocket closing handshake is started, the user agent must queue a task to change the readyState attribute's value to CLOSING (2). (If the close() method was called, the readyState attribute's value will already be set to CLOSING (2) when this task runs.) [WSP]


When the WebSocket connection is closed, possibly cleanly, the user agent must queue a task to run the following substeps:

  1. Change the readyState attribute's value to CLOSED (3).

  2. If the user agent was required to fail the WebSocket connection, or if the the WebSocket connection was closed after being flagged as full, fire an event named error at the WebSocket object. [WSP]

  3. Fire an event named close at the WebSocket object, using CloseEvent, with the wasClean attribute initialized to true if the connection closed cleanly and false otherwise, the code attribute initialized to the WebSocket connection close code, and the reason attribute initialized to the result of applying UTF-8 decode without BOM to the WebSocket connection close reason. [WSP]

User agents must not convey any failure information to scripts in a way that would allow a script to distinguish the following situations:

In all of these cases, the the WebSocket connection close code would be 1006, as required by WebSocket Protocol. [WSP]

Allowing a script to distinguish these cases would allow a script to probe the user's local network in preparation for an attack.

In particular, this means the code 1015 is not used by the user agent (unless the server erroneously uses it in its close frame, of course).


The task source for all tasks queued in this section is the WebSocket task source.

9.3.4 Ping and Pong frames

The WebSocket protocol defines Ping and Pong frames that can be used for keep-alive, heart-beats, network status probing, latency instrumentation, and so forth. These are not currently exposed in the API.

User agents may send ping and unsolicited pong frames as desired, for example in an attempt to maintain local network NAT mappings, to detect failed connections, or to display latency metrics to the user. User agents must not use pings or unsolicited pongs to aid the server; it is assumed that servers will solicit pongs whenever appropriate for the server's needs.

9.3.5 The CloseEvent interface

WebSocket objects use the CloseEvent interface for their close events:

[Exposed=(Window,Worker)]
interface CloseEvent : Event {
  constructor(DOMString type, optional CloseEventInit eventInitDict = {});

  readonly attribute boolean wasClean;
  readonly attribute unsigned short code;
  readonly attribute USVString reason;
};

dictionary CloseEventInit : EventInit {
  boolean wasClean = false;
  unsigned short code = 0;
  USVString reason = "";
};
event . wasClean

Returns true if the connection closed cleanly; false otherwise.

event . code

Returns the WebSocket connection close code provided by the server.

event . reason

Returns the WebSocket connection close reason provided by the server.

The wasClean attribute must return the value it was initialized to. It represents whether the connection closed cleanly or not.

The code attribute must return the value it was initialized to. It represents the WebSocket connection close code provided by the server.

The reason attribute must return the value it was initialized to. It represents the WebSocket connection close reason provided by the server.

9.3.6 Garbage collection

A WebSocket object whose readyState attribute's value was set to CONNECTING (0) as of the last time the event loop reached step 1 must not be garbage collected if there are any event listeners registered for open events, message events, error events, or close events.

A WebSocket object whose readyState attribute's value was set to OPEN (1) as of the last time the event loop reached step 1 must not be garbage collected if there are any event listeners registered for message events, error, or close events.

A WebSocket object whose readyState attribute's value was set to CLOSING (2) as of the last time the event loop reached step 1 must not be garbage collected if there are any event listeners registered for error or close events.

A WebSocket object with an established connection that has data queued to be transmitted to the network must not be garbage collected. [WSP]

If a WebSocket object is garbage collected while its connection is still open, the user agent must start the WebSocket closing handshake, with no status code for the Close message. [WSP]


If a user agent is to make disappear a WebSocket object (this happens when a Document object goes away), the user agent must follow the first appropriate set of steps from the following list:

If the WebSocket connection is not yet established [WSP]

Fail the WebSocket connection. [WSP]

If the WebSocket closing handshake has not yet been started [WSP]

Start the WebSocket closing handshake, with the status code to use in the WebSocket Close message being 1001. [WSP]

Otherwise

Do nothing.

9.4 跨文档通信

Window/postMessage

Support in all current engines.

Firefox8+Safari4+Chrome1+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android8+Safari iOS3.2+Chrome Android18+WebView Android≤37+Samsung Internet1.0+Opera Android10.1+

Web 浏览器由于安全和隐私等原因禁止不同域的文档见互相影响,也就是说不允许跨站脚本。

虽然这是一个非常重要的安全特性,但它也阻止了不同域的页面之间进行非恶意的通信。 本章引入了一个消息系统来允许不同源的文档间通信,这一设计不会引起跨站脚本攻击。

postMessage() API 可以用作 跟踪向量

9.4.1 概述

This section is non-normative.

例如,如果文档 A 包含一个 iframe 元素,其中包含文档 B, A 中的脚本调用了 B 的 Window 对象上的 postMessage(), 然后这个对象上会产生一个消息事件,标记为源自文档 A 的 Window。 文档 A 中的脚本可能像这样:

var o = document.getElementsByTagName('iframe')[0];
o.contentWindow.postMessage('Hello world', 'https://b.example.org/');

脚本通过 addEventListener()(或类似机制) 为传入的事件注册事件处理器。例如文档 B 中的脚本可能像这样:

window.addEventListener('message', receiver, false);
function receiver(e) {
  if (e.origin == 'https://example.com') {
    if (e.data == 'Hello world') {
      e.source.postMessage('Hello', e.origin);
    } else {
      alert(e.data);
    }
  }
}

该脚本先检查域是否符合预期, 然后再检查消息,把它显示给用户或者把它发送回首先发送消息的文档。

9.4.2 安全

9.4.2.1 作者

使用此 API 需要格外小心, 以防止恶意实体为达到自己的目的在网站上滥用。

作者应该检查 origin 属性以确保只从他们期望的域接收消息。否则,作者的消息处理代码中的错误可能会被恶意网站利用。

此外,即使在检查 origin 属性后,作者也应该检查相关数据的格式。否则,如果事件的源被跨站脚本攻击,对通过 postMessage() 方法发送的消息的未经检查的处理可能会把攻击传播到接收者。

对于任何包含机密信息的消息中,作者不应在 targetOrigin 参数中使用通配符关键字(*),否则无法保证消息仅传递给它希望的接收方。


鼓励接受任何来源消息的作者考虑 DoS 攻击的风险。攻击者可能会发送大量的消息; 如果接收页面执行了耗时的计算或为每个此类消息产生网络流量, 则攻击者的消息可能会被成倍放大,从而导致 DoS 攻击。 鼓励作者采用速率限制(每分钟只接受一定数量的消息)以使这种攻击不可行。

9.4.2.2 用户代理

本 API 的完整性基于一个 的脚本无法向其他(不同的)域 (使用 dispatchEvent() 或其他方法)发送任意事件。

强烈建议实现方在实现这项功能时要格外小心。 它允许作者将信息从一个域传送到另一个域,通常出于安全原因这是不允许的。 它还要求 UA 小心地允许访问某些属性,但禁止其他的。


也鼓励用户代理考虑对不同 之间的消息进行速率限制,来保护简单的网站不受 DoS 攻击。

9.4.3 发布消息

window . postMessage(message [, options ] )

Window/postMessage

Support in all current engines.

Firefox8+Safari4+Chrome1+
Opera9.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android8+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+

像指定的 window 发送消息。消息可以是结构化的对象, 例如嵌套对象和数组,可以包含 JavaScript 值(字符串、数字、Date、对象等等), 也可以包含数据对象比如 File BlobFileList, 以及 ArrayBuffer 对象。

optionstransfer 成员中的对象会被转移(不是克隆), 意味着它们在发送侧不再可用。

可以用 optionstargetOrigin 成员来指定目标源。 如果没有指定,默认为 "/"。这个默认值限制了消息只能发送到同源目标。

为避免信息泄露,如果目标窗口的源不匹配给定的源消息会被丢弃。如果要无视目标源直接发送消息,需要设置目标源为 "*"。

如果 transfer 数组包含重复的对象,或者 message 不可克隆时, 抛出一个 "DataCloneError" DOMException

window . postMessage(message, targetOrigin [, transfer ] )

这是 postMessage() 的另一个版本,以目标源作为参数。调用 window.postMessage(message, target, transfer) 等价于 window.postMessage(message, {targetOrigin, transfer})

给刚导航到新 Documentbrowsing context 上的 Window 发布消息时,消息可能无法到达接收者: 目标 浏览上下文 中的脚本必须有时间设置消息监听器。 因此,如果要发送消息给一个刚创建的子 iframeWindow, 建议作者在子 Document 中发送消息给父级来声明它已经准备好接收消息了, 父级则等待该消息到来后再开发发送消息。

给定 targetWindow, messageoptions窗口发送消息步骤 如下:

  1. targetRealmtargetWindowRealm

  2. incumbentSettings当前设置对象

  3. targetOriginoptions["targetOrigin"]。

  4. 如果 targetOrigin 是一个 U+002F SOLIDUS 字符 (/),则将 targetOrigin 设置为 incumbentSettingsorigin

  5. 否则,如果 targetOrigin 不是一个 U+002A ASTERISK 字符 (*),则:

    1. parsedURL 为在 targetOrigin 上执行 URL 解析 的结果。

    2. 如果 parsedURL 是失败,则抛出 "SyntaxError" DOMException

    3. 设置 targetOriginparsedURLorigin

  6. transferoptions["transfer"]。

  7. serializeWithTransferResultStructuredSerializeWithTransfer(message, transfer)。 重新抛出任何异常。

  8. 已发送消息任务源 上给定 targetWindow 入队一个全局任务 来执行以下步骤:

    1. 如果 targetOrigin 参数不是单个 U+002A ASTERISK 字符 (*) 且 targetWindow关联 Document 不 与 targetOrigin 同源,则返回。

    2. originincumbentSettingsorigin序列化

    3. sourceWindowProxy 对象对应的 incumbentSettings全局对象 (一个 Window 对象)。

    4. deserializeRecordStructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm)。

      如果这抛出了异常,捕获它并使用 MessageEventtargetWindow产生 一个名为 messageerror 的事件, 并把 origin 属性初始化为 originsource 属性初始化为 source, 然后返回。

    5. messageClonedeserializeRecord.[[Deserialized]]。

    6. newPorts 为一个新的 frozen array,包含 deserializeRecord.[[TransferredValues]] 中所有的 MessagePort 对象(如果有的话), 并保持它们的相对顺序。

    7. 使用 MessageEventtargetWindow 上 产生 一个名为 message 的事件, 其 origin 属性初始化为 originsource 属性初始化为 sourcedata 属性初始化为 messageCloneports 属性初始化为 newPorts

Window 上调用 postMessage(message, options) 方法时,必须执行以下步骤:

  1. targetWindow 为这个 Window 对象。

  2. 给定 targetWindowmessageoptions, 执行 窗口发送消息步骤

Window 上调用 postMessage(message, targetOrigin, transfer) 方法时,必须执行以下步骤:

  1. targetWindow 为这个 Window 对象。

  2. options 为 «[ "targetOrigin" → targetOrigin, "transfer" → transfer ]»。

  3. 给定 targetWindowmessageoptions, 执行 窗口发送消息步骤

9.5 通道

9.5.1 概述

This section is non-normative.

为了使独立的代码片段之间可以相互通信(例如运行在不同 浏览上下文 的代码直接通信), 作者可以使用 Channel 通信

该机制下的通信 Channel 实现为双向管道,两端各一个端口。 从一个端口发送的消息被传递到另一个端口,反之亦然。 消息被作为 DOM 事件传递,不会中断或阻塞正在执行的 任务

创建连接(两个关联的端口)使用 MessageChannel() 构造函数:

var channel = new MessageChannel();

其中一个端口作为本地端口保存,另一个发送到了远程代码,例如 使用 postMessage():

otherWindow.postMessage('hello', 'https://example.com', [channel.port2]);

发送消息使用端口上的 postMessage() 方法:

channel.port1.postMessage('hello');

接收消息需要监听 message 事件:

channel.port1.onmessage = handleMessage;
function handleMessage(event) {
  // message is in event.data
  // ...
}

发送到端口的数据可以是结构化的;例如向 MessagePort 传递字符串数组:

port1.postMessage(['hello', 'world']);
9.5.1.1 示例

This section is non-normative.

在这个例子中,两个 JavaScript 库通过 MessagePort 相互连接。 这允许它们托管在不同的框架或 Worker 对象中而不需要改变 API。

<script src="contacts.js"></script> <!-- exposes a contacts object -->
<script src="compose-mail.js"></script> <!-- exposes a composer object -->
<script>
 var channel = new MessageChannel();
 composer.addContactsProvider(channel.port1);
 contacts.registerConsumer(channel.port2);
</script>

Here's what the "addContactsProvider()" function's implementation could look like:

function addContactsProvider(port) {
  port.onmessage = function (event) {
    switch (event.data.messageType) {
      'search-result': handleSearchResult(event.data.results); break;
      'search-done': handleSearchDone(); break;
      'search-error': handleSearchError(event.data.message); break;
      // ...
    }
  };
};

或者也可以这样实现:

function addContactsProvider(port) {
  port.addEventListener('message', function (event) {
    if (event.data.messageType == 'search-result')
      handleSearchResult(event.data.results);
  });
  port.addEventListener('message', function (event) {
    if (event.data.messageType == 'search-done')
      handleSearchDone();
  });
  port.addEventListener('message', function (event) {
    if (event.data.messageType == 'search-error')
      handleSearchError(event.data.message);
  });
  // ...
  port.start();
};

关键的区别在于,当使用 addEventListener() 时,必须调用 start() 方法。当使用 onmessage 时,已经默认调用了 start()

无论显式或隐式地(通过设置 onmessage) 调用 start() 方法,都会启动消息流: 发送到消息端口的消息初始是暂停的,这样就不会在脚本还没能建立监听器之前被丢掉。

9.5.1.2 端口作为 Web 上对象能力模型的基础

This section is non-normative.

可以把端口当做为系统中其他角色提供有限能力的一种方式(在对象能力模型的意义上), 这可能是一个弱能力的系统,用端口只是为了在源内通信的方便, 也可能是一个强能力的系统,由一个源 provider 提供,作为唯一的机制给另一个源 consumer 来从 provider 获取信息或造成改变。

例如,考虑一个社交网站嵌入了一个 iframe 它是用户的邮件联系人提供者(一个联系人网站,来自第二个源), 以及第二个 iframe(一个游戏网站,来自第三个源) 外面的社交网站和第二个 iframe 中的游戏无法访问第一个 iframe 中的任何东西;它们只能:

联系人提供者使用这些方法(尤其是第三个)来给其他域提供操作用户地址簿的 API。 例如,响应 "add-contact Guillaume Tell <tell@pomme.example.net>" 时,在用户的地址簿中新增指定的人和 e-mail。

为了避免 Web 上任何站点都可以操作用户的地址簿,联系人提供者可能只允许确定的信任站点调用, 比如这个社交网站。

现在假设这个游戏希望添加联系人到用户的地址簿,而且这个社交网站也愿意允许它这样做, 实质上是“共享”联系人提供者对社交网站的信任。实现这一共享有很多方式, 最简单的是在游戏站点和联系人站点之间代理消息。 然而该方案有一些困难:它需要社交网站完全信任游戏网站不会滥用特权, 或者要求社交网站对每个请求进行验证来确保请求是否被允许 (例如添加多个联系人、读取联系人、删除联系人等)。 如果可能有多个游戏同时与联系人提供者通信,还需要额外的复杂性。

然而,使用消息 Channel 和 MessagePort 对象可以解决所有这些问题。 当游戏告诉设计网络它需要添加联系人时,社交网站可以请求联系人提供者添加单个联系人的 能力,而非直接请求添加一个联系人。 然后联系人提供者提供一对 MessagePort 对象,把其中一个返回给社交网站, 社交网站再把它转交给游戏。游戏和联系人提供者就有了直接的连接, 因此联系人提供者知道只对它开放 "添加联系人" 的请求。 换句话说,这个游戏被赋予了添加单个联系人的能力。

9.5.1.3 端口作为抽象服务实现的基础

This section is non-normative.

继续上一部分提到的例子,特别考虑联系人提供者。 初始的实现可能是简单地在服务的 iframe 中使用 XMLHttpRequest 对象, 一个改进版本可能会使用 共享 worker 和一个 WebSocket 连接。

如果初始的设计使用了 MessagePort 对象来赋予能力,或者甚至仅仅是为了支持多个并发的独立会话, 这个服务的实现就可以直接从 "每个 iframe 中一个 XMLHttpRequest" 模型迁移到 "共享 WebSocket" 模型, 完全不需要改变 API:服务提供者一侧的端口可以全部转发到共享 Worker,完全不影响 API 的用户。

9.5.2 消息通道

[Exposed=(Window,Worker)]
interface MessageChannel {
  constructor();

  readonly attribute MessagePort port1;
  readonly attribute MessagePort port2;
};
channel = new MessageChannel()

MessageChannel/MessageChannel

Support in all current engines.

Firefox41+Safari5+Chrome1+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android41+Safari iOS4.2+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+

返回有两个新的 MessagePort 对象的,一个新的 MessageChannel 对象。

channel . port1

MessageChannel/port1

Support in all current engines.

Firefox41+Safari5+Chrome1+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android41+Safari iOS4.2+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+

返回第一个 MessagePort 对象。

channel . port2

MessageChannel/port2

Support in all current engines.

Firefox41+Safari5+Chrome1+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android41+Safari iOS4.2+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+

返回第二个 MessagePort 对象。

MessageChannel 对象有一个关联的 port 1port 2,都是 MessagePort 对象。

new MessageChannel() 构造步骤为:

  1. 设置 thisport 1 为在 this相关 Realm 中的 new MessagePort

  2. 设置 thisport 2 为在 this相关 Realm 中的 new MessagePort

  3. 绑定 thisport 1thisport 2

port1 获取步骤为返回 thisport 1

port2 获取步骤为返回 thisport 2

9.5.3 消息端口

每个通道都有两个消息端口。从一个端口发送的数据会从另一个端口收到,反之亦然。

[Exposed=(Window,Worker,AudioWorklet), Transferable]
interface MessagePort : EventTarget {
  undefined postMessage(any message, optional sequence<object> transfer = []);
  undefined postMessage(any message, optional PostMessageOptions options = {});
  undefined start();
  undefined close();

  // event handlers
  attribute EventHandler onmessage;
  attribute EventHandler onmessageerror;
};

dictionary PostMessageOptions {
  sequence<object> transfer = [];
};
port . postMessage(message [, transfer] )

MessagePort/postMessage

Support in all current engines.

Firefox41+Safari5+Chrome1+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android41+Safari iOS4.2+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
port . postMessage(message [, { transfer }] )

通过通道发布一条消息。列在 transfer 中的对象已经被传输(不仅是克隆), 意味着在发送侧无法使用了。

如果 transfer 数组包含重复的对象、源或目标端口时, 或者 message 不可克隆, 抛出一个 "DataCloneError" DOMException

port . start()

MessagePort/start

Support in all current engines.

Firefox41+Safari5+Chrome1+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android41+Safari iOS4.2+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+

开始派发端口上收到的消息。

port . close()

MessagePort/close

Support in all current engines.

Firefox41+Safari5+Chrome1+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android41+Safari iOS4.2+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+

断开端口,端口不再处于激活状态。

每个 MessagePort 对象可以与另一个关联(对称关系)。 每个 MessagePort 对象也可以有一个 任务源 称为 端口消息队列,初始为空。 端口消息队列 可以被启用和禁用,初始禁用。 一旦被启用,就不能再被禁用了 (虽然队列中的消息可以移动到其他队列或者全部移除,也可以达到一样的效果), MessagePort 还有一个 已经被转移 标志, 初始必须为 false。

当端口的 端口消息队列 被启用时, 事件循环 不许使用它作为其中一个 任务源。当端口的 相关全局对象Window 时, 在它的 端口消息队列 中的所有 任务 必须与该端口的 相关全局对象关联 Document 相关联。

如果该文档是 完全激活的, 但事件监听器的脚本的 设置对象 指定的 负责文档 完全激活的,消息会在这些文档 完全激活的 时才收到。

每个 事件循环 有一个 任务源 称为 未转移的端口消息队列。 这是一个虚拟的 任务源,它的必须表现地就像它包含满足以下条件的的每个 MessagePort端口消息队列 的所有 任务 一样: 1. 已经被转移 标志位 false; 2. 启用了 端口消息队列; 3. 相关代理事件循环 为该 事件循环。 顺序为它们被添加到对应的 任务源 的顺序。 当 任务未转移的端口消息队列 移除时, 它必须也从它的 端口消息队列 中移除。

MessagePort已被转移 标志为 false 时, 事件循环 必须忽略它的 端口消息队列 (此时使用 未转移的端口消息队列)。

当一个端口、其关联端口、或者它克隆自的对象被传输时, 已被转移 标志位设为 true 当 MessagePort已被转移 标志为 true 时, 其 端口消息队列 是一级 任务源,不受任何 未转移的端口消息队列 影响。

当用户代理 关联 两个 MessagePort 对象时, 必须执行以下步骤:

  1. 如果其中给一个端口已经关联,则把它与之前关联的端口解关联。

    如果那两个之前关联的端口是同一个 MessageChannel 对象的两个端口,则那个 MessageChannel 对象不再表示任何真正的端口:它的两个端口已经不再关联。

  2. 关联这两个端口,让它们组成新通道的两部分。 (没有 MessageChannel 对象表示这个通道)

    经过这个步骤的两个端口 AB 被称为关联的;其中一个关联到了另一个,反之亦然。

    尽管本标准把这个过程描述为瞬间的,但它们更有可能通过消息传递来实现。 就像其他所有算法一样,关键是只要最终结果无法与规范区分(在黑盒的意义上)。


MessagePort 对象是 可传输对象。 给定 valuedataHolder, 它们的 传输步骤 是:

  1. 设置 value已被转移 标志为 true。

  2. 设置 dataHolder.[[PortMessageQueue]] 到 value端口消息队列

  3. 如果 value 与另一个端口 remotePort 关联,则:

    1. 设置 remotePort已被转移 标志为 true。

    2. 设置 dataHolder.[[RemotePort]] 为 remotePort

  4. 否则,设置 dataHolder.[[RemotePort]] 为 null。

给定 dataHoldervalue, 它们的 传输-接收步骤 是:

  1. 设置 value已被转移 标志为 true。

  2. 把所有要在 dataHolder.[[PortMessageQueue]] 上触发 message 事件的 tasks(如果有的话) 移动到 value端口消息队列 上, 保持 value端口消息队列 处于初始的禁用状态, 如果 value相关全局对象Window, 将移动后的 任务value相关全局对象关联 Document 相关联。

  3. 如果 dataHolder.[[RemotePort]] 非 null,则 关联 dataHolder.[[RemotePort]] 和 value。(这将会把 dataHolder.[[RemotePort]] 与它之前关联的被转移的端口解关联)。


给定 targetPortmessageoptions消息端口发消息的步骤 如下:

  1. transferoptions["transfer"]。

  2. 如果在 transfer 中的任何一个对象是这个 MessagePort, 则抛出一个 "DataCloneError" DOMException

  3. doomed 为 false。

  4. 如果 targetPort 非 null 且 transfer 中有任何对象是 targetPort,则设置 doomed 为 true,并(可选地)在开发终端中报告 目标端口被发送到了它自己,导致通道丢失。

  5. serializeWithTransferResultStructuredSerializeWithTransfer(message, transfer)。 重新抛出任何异常。

  6. 如果没有 targetPort (比如这个 MessagePort 未关联), 或者如果 doomed 为 true,则返回。

  7. targetPort端口消息队列 中添加一个 任务 执行以下步骤:

    1. finalTargetPort 为在当前任务所在的 端口消息队列MessagePort

      这可能与 targetPort 不同,如果 targetPort 自己被传输,它的所有任务都跟着移动。

    2. targetRealmfinalTargetPort相关 Realm

    3. deserializeRecordStructuredDeserializeWithTransfer(serializeWithTransferResult, targetRealm)。

      如果这抛出了异常,捕获它并在 finalTargetPort 上用 MessageEvent 触发一个 名为 messageerror 的事件,然后返回。

    4. messageClonedeserializeRecord.[[Deserialized]]。

    5. newPorts 为一个新的 冻结的数组 该数组包含所有 deserializeRecord.[[TransferredValues]] 中的 MessagePort 对象(如果有的话),保持它们的相对顺序。

    6. finalTargetPort 上用 MessageEvent, 触发一个 名为 message 的事件,其 data 属性初始化为 messageCloneports 属性初始化为newPorts

MessagePort 对象上调用 postMessage(message, options) 方法时,执行以下步骤:

  1. targetPortMessagePort 绑定的端口(如果有的话), 如果没有就令它为 null。

  2. targetPortmessageoptions 执行 消息端口发送消息步骤

MessagePort 对象上调用 postMessage(message, transfer) 方法时必须执行以下步骤:

  1. targetPortMessagePort 绑定的端口(如果有的话), 如果没有就令它为 null。

  2. options 为 «[ "transfer" → transfer ]»。

  3. targetPortmessageoptions 执行 消息端口发送消息步骤


start() 方法必须启用其端口的 端口消息队列,如果还没有启用的话。


在已关联的端口 local port 上调用 close() 方法时, 用户代理必须解关联这两个端口。 如果该方法在一个未关联的端口上调用时,该方法必须什么都不做。


下面是所有实现 MessagePort 接口的对象 必须 支持的 事件处理器 (以及它们相应的事件处理器事件类型), 作为 事件处理器 IDL 属性

事件处理器 事件处理器事件类型
onmessage

MessagePort/message_event

Support in all current engines.

Firefox41+Safari5+Chrome1+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android41+Safari iOS4.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11.5+
message
onmessageerror

MessagePort/messageerror_event

Firefox57+SafariNoChrome60+
Opera47+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android57+Safari iOSNoChrome Android60+WebView Android60+Samsung Internet8.0+Opera Android47+
messageerror

第一次设置 MessagePort 对象的 onmessage IDL 属性时, 端口的 端口消息队列 必须被启用, 就像调用了 start() 方法一样。

9.5.4 广播给多个端口

This section is non-normative.

B广播给多个端口原则上相对简单:维护一个要发消息的 MessagePort 对象数组,发消息时遍历这个数组。 然而这有一个不好的效果:它会阻止端口的垃圾回收,即使另一端已经走了。 为了避免这个问题,实现一个简单的协议让对方确认它还存在。 如果它在某段时间没有确认,就假设它已经不在了,关闭 MessagePort 对象并让它被回收。

9.5.5 端口与垃圾回收

当一个 MessagePort 对象 o 被关联时,用户代理的表现必须像是 o 的关联 MessagePort 对象有一个 o 的强引用。 或者就像 o相关全局对象 有一个 o 的强引用。

这样给定一个事件监听器,它收到一个消息端口后可以忘掉它。 只要该事件监听器还可能收到消息,这个通道就仍然被维护着。

当然这在通道的两侧都会发生,只要它们不能从活跃的代码到达,两个端口就都会被垃圾回收。 即使它们之间还有对方的强引用。

进一步地,当 任务队列 中的 任务 仍然有一个要派发在 MessagePort 上的事件时, 或者这个 MessagePort 对象的 端口消息队列 处于启用状态且非空时, MessagePort 对象不得被垃圾回收。

强烈鼓励作者显式地关闭 MessagePort 对象来解关联它们, 这样它们的资源可以被重新回收。 创建很多歌 MessagePort 对象并直接丢弃它们而不关闭可能导致瞬时内存使用率高, 因为垃圾收集不一定能够及时执行,尤其是对于垃圾收集可能涉及跨进程协调的 MessagePort 而言。

9.6 向其他浏览上下文广播

同一个用户,同一个用户代理,同一个 , 但不同 浏览上下文 的页面有时需要相互发送通知, 例如 “嘿,用户在我这里登录了,重新检查你的信任状态”。

对于复杂情况,例如管理共享状态的锁定,管理服务器和多个本地客户端之间的资源同步, 共享与远程主机的 WebSocket 连接等等, 共享 Worker 是最合适的解决方案。

但对于简单情况,共享 Worker 可能是不合理的开销, 作者可以使用这一章描述的简单的基于通道的广播机制。

[Constructor(DOMString name), Exposed=(Window,Worker)]
interface BroadcastChannel : EventTarget {
  readonly attribute DOMString name;
  void postMessage(any message);
  void close();
  attribute EventHandler onmessage;
  attribute EventHandler onmessageerror;
};
broadcastChannel = new BroadcastChannel(name)

BroadcastChannel/BroadcastChannel

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera41+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android38+Safari iOS15.4+Chrome Android54+WebView Android54+Samsung Internet6.0+Opera Android41+

返回一个新的 BroadcastChannel 对象,通过它可以像指定的通道名发送和接收消息。

broadcastChannel . name

BroadcastChannel/name

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera41+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android38+Safari iOS15.4+Chrome Android54+WebView Android54+Samsung Internet6.0+Opera Android41+

返回通道名(传递给构造函数的)。

broadcastChannel . postMessage(message)

BroadcastChannel/postMessage

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera41+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android38+Safari iOS15.4+Chrome Android54+WebView Android54+Samsung Internet6.0+Opera Android41+

向为这个通道建立的 BroadcastChannel 对象发送给定的消息。 消息可以是结构化对象,例如嵌套对象和数组。

broadcastChannel . close()

BroadcastChannel/close

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera41+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android38+Safari iOS15.4+Chrome Android54+WebView Android54+Samsung Internet6.0+Opera Android41+

关闭 BroadcastChannel 对象,让它可以被垃圾回收。

BroadcastChannel 对象有一个 通道名, 一个 BroadcastChannel 设置对象, 以及一个 关闭标志

BroadcastChannel() 构造函数被调用时, 必须创建和返回一个 BroadcastChannel 对象, 其 通道名 为构造函数的第一个参数, 其 BroadcastChannel 设置对象当前设置对象, 其 关闭标志 为 false。

name 属性必须返回 通道名

postMessage(message) 方法在 BroadcastChannel 对象上被调用时,必须执行以下步骤:

  1. source 为这个 BroadcastChannel

  2. sourceSettingssourceBroadcastChannel 设置对象

  3. 如果 source关闭标志 为 true,则抛出一个 "InvalidStateError" DOMException

  4. sourceChannelsource通道名

  5. targetRealm 为用户代理定义的 Realm。

  6. serializedStructuredSerialize(message)。 重新抛出任何异常。

  7. destinations 为符合以下要求的 BroadcastChannel 对象的列表:

  8. destinations 移除 source

  9. destinations 排序,使得所有 BroadcastChannel 设置对象 指定了同样 负责事件循环BroadcastChannel 对象按照创建顺序排序,老的在先。 (这并没有定义完全排序。在这个约束下,用户代理可以按任意方式排序)

  10. destinations 中的每一个 BroadcastChannel 对象 destination排一个任务 执行以下步骤:

    1. targetRealmdestination相关 Realm

    2. dataStructuredDeserialize(serialized, targetRealm)。

      如果抛出了异常,捕获它,在 destination 上使用 MessageEvent 发生 一个名为 messageerror 的事件, origin 属性初始化为 sourceSettingsorigin序列化,然后返回。

    3. destination 上使用 MessageEvent 发生 一个名为 message 的事件,其 data 属性初始化为 dataorigin 属性初始化为 sourceSettingsorigin序列化

    任务 必须使用 DOM 操作任务源, 而且对于那些目标 BroadcastChannel 对象的 BroadcastChannel 设置对象 指定的 事件循环 是一个 浏览上下文 事件循环 的任务,必须与 那个目标的 BroadcastChannel 对象的 BroadcastChannel 设置对象 指定的 负责文档 相关联。

已关闭标志 为 false 的 BroadcastChannel 对象还有事件处理器注册在 message 事件上时,BroadcastChannel 对象的 BroadcastChannel 设置对象 指定的 全局对象 上必须有一个强引用指向 BroadcastChannel 对象自己。

close() 方法必须 把调用它的 BroadcastChannel 对象的 已关闭标志 设置为 true。

强烈鼓励作者在不需要它们时,显式地关闭 BroadcastChannel 对象, 这样它们就可以被垃圾回收了。 创建很多 BroadcastChannel 对象并在留有一个事件监听器时抛弃但不关闭他们, 会导致明显的内存泄露,因为只要它们有事件处理器(或页面或 Worker 别关闭),这些对象就会继续活着。


下面的例子是所有实现 BroadcastChannel 接口的对象 必须 以 事件处理器 IDL 属性 方式支持的 事件处理器 (以及对应的 事件处理器事件类型):

事件处理器 事件处理器事件类型
onmessage

BroadcastChannel/message_event

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera41+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android38+Safari iOS15.4+Chrome Android54+WebView Android54+Samsung Internet6.0+Opera Android41+
message
onmessageerror

BroadcastChannel/messageerror_event

Support in all current engines.

Firefox57+Safari15.4+Chrome60+
Opera47+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android57+Safari iOS15.4+Chrome Android60+WebView Android60+Samsung Internet8.0+Opera Android47+
messageerror

假设一个页面想要知道用户登出,包括从其他标签页登出:

var authChannel = new BroadcastChannel('auth');
authChannel.onmessage = function (event) {
  if (event.data == 'logout')
    showLogout();
}

function logoutRequested() {
  // called when the user asks us to log them out
  doLogout();
  showLogout();
  authChannel.postMessage('logout');
}

function doLogout() {
  // actually log the user out (e.g. clearing cookies)
  // ...
}

function showLogout() {
  // update the UI to indicate we're logged out
  // ...
}

10 Web 工作线程

Web_Workers_API

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+

Web_Workers_API/Using_web_workers

10.1 概述

10.1.1 涵盖范围

This section is non-normative.

本标准定义了独立于任何 UI 脚本在后台运行脚本的 API。

这使得长时间运行的脚本成为可能,它们不会因响应用户点击或其他交互而中断。 也使得耗时任务成为可能,它们不必为了保持页面可响应而立即返回。

Workers (这里指这些后台脚本)相对重量级,不适合大量使用。 例如,为400万像素图片的每一像素启动一个 Worker 就可能不太合适。 下面的例子演示了一些合适的 workers 使用方式。

通常 workers 应该有较长的生命期,较高的启动性能消耗,而且每个实例都会产生较高的内存消耗。

10.1.2 示例

This section is non-normative.

Worker 有着广泛的用途,下面的几节展示了其中的一些。

10.1.2.1 数字密集型计算的后台 worker

This section is non-normative.

workers 最简单的使用方式是在不打断 UI 的情况下执行计算密集型的任务。

本例子中,主文档启动(spawns )了一个 worker 来(naïvely)计算质数, 然后逐渐地显示新发现的质数。

主页面如下:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Worker example: One-core computation</title>
 </head>
 <body>
  <p>The highest prime number discovered so far is: <output id="result"></output></p>
  <script>
   var worker = new Worker('worker.js');
   worker.onmessage = function (event) {
     document.getElementById('result').textContent = event.data;
   };
  </script>
 </body>
</html>

Worker() 构造函数的调用创建了一个 worker, 并返回一个表示该 worker 的 Worker 对象,该对象用来与 worker 进行通信。 该对象的 onmessage 事件处理函数允许 从 worker 接受消息。

worker 本身如下:

var n = 1;
search: while (true) {
  n += 1;
  for (var i = 2; i <= Math.sqrt(n); i += 1)
    if (n % i == 0)
     continue search;
  // found a prime!
  postMessage(n);
}

这些代码就是未经优化的寻找质数算法。找到质数时使用 postMessage() 方法来 向页面发送消息。

在线浏览该示例

10.1.2.2 使用 JavaScript 模块作为 worker

This section is non-normative.

目前我们所有例子的 workers 都在运行 经典脚本 。Workers 也可以用 模块脚本 实例化, 通常有如下好处:使用 JavaScript import 声明来引入其他模块的能力; 默认的严格模式;顶层声明不会污染 worker 的全局作用域。

注意相比于经典脚本,基于模块的 workers 遵循不同的跨域内容限制, 不同于经典 workers,模块 workers 可以使用跨域脚本实例化,只要使用 CORS 协议把该脚本暴露出来。 另外,在模块 worker 中 importScripts() 方法将自动失效;JavaScript import 声明通常是更好的选择。

本例子中,主文档使用了一个 worker 来做主线程外的图像操作。 它引入了另一个模块中的过滤器。

主页面如下:

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>Worker example: image decoding</title>

<p>
  <label>
    Type an image URL to decode
    <input type="url" id="image-url" list="image-list">
    <datalist id="image-list">
      <option value="https://html.spec.whatwg.org/images/drawImage.png">
      <option value="https://html.spec.whatwg.org/images/robots.jpeg">
      <option value="https://html.spec.whatwg.org/images/arcTo2.png">
    </datalist>
  </label>
</p>

<p>
  <label>
    Choose a filter to apply
    <select id="filter">
      <option value="none">none</option>
      <option value="grayscale">grayscale</option>
      <option value="brighten">brighten by 20%</option>
    </select>
  </label>
</p>

<canvas id="output"></canvas>

<script type="module">
  const worker = new Worker("worker.js", { type: "module" });
  worker.onmessage = receiveFromWorker;

  const url = document.querySelector("#image-url");
  const filter = document.querySelector("#filter");
  const output = document.querySelector("#output");

  url.oninput = updateImage;
  filter.oninput = sendToWorker;

  let imageData, context;

  function updateImage() {
    const img = new Image();
    img.src = url.value;

    img.onload = () => {
      output.innerHTML = "";

      const canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;

      context = canvas.getContext("2d");
      context.drawImage(img, 0, 0);
      imageData = context.getImageData(0, 0, canvas.width, canvas.height);

      sendToWorker();
      output.appendChild(canvas);
    };
  }

  function sendToWorker() {
    worker.postMessage({ imageData, filter: filter.value });
  }

  function receiveFromWorker(e) {
    context.putImageData(e.data, 0, 0);
  }
</script>

worker 文件如下:

import * as filters from "./filters.js";

self.onmessage = e => {
  const { imageData, filter } = e.data;
  filters[filter](imageData);
  self.postMessage(imageData, [imageData.data.buffer]);
};

它引入了文件 filters.js

export function none() {}

export function grayscale({ data: d }) {
  for (let i = 0; i < d.length; i += 4) {
    const [r, g, b] = [d[i], d[i + 1], d[i + 2]];

    // CIE luminance for the RGB
    // The human eye is bad at seeing red and blue, so we de-emphasize them.
    d[i] = d[i + 1] = d[i + 2] = 0.2126 * r + 0.7152 * g + 0.0722 * b;
  }
};

export function brighten({ data: d }) {
  for (let i = 0; i < d.length; ++i) {
    d[i] *= 1.2;
  }
};

在线浏览该示例

10.1.2.3 共享 worker 概述

SharedWorker

Firefox29+Safari5–7Chrome4+
Opera10.6+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android33+Safari iOS5–7Chrome AndroidNoWebView AndroidNoSamsung Internet4.0–5.0Opera Android11–14

This section is non-normative.

这一节通过一个 Hello World 例子来介绍共享 Worker。由于每个 Worker 可以有多个连接, 共享 Worker 的 API 略有不同。

第一个例子展示了如何连接到 worker 以及 worker 如何向连接的页面发回消息。 收到的消息显示在日志中。

这是 HTML 页面:

<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">
<title>Shared workers: demo 1</title>
<pre id="log">Log:</pre>
<script>
  var worker = new SharedWorker('test.js');
  var log = document.getElementById('log');
  worker.port.onmessage = function(e) { // note: not worker.onmessage!
    log.textContent += '\n' + e.data;
  }
</script>

这是 JavaScript worker:

onconnect = function(e) {
  var port = e.ports[0];
  port.postMessage('Hello World!');
}

在线查看本示例


第二个例子在两方面扩展了上一个例子:首先使用 addEventListener() 来接收事件,取代了 事件处理函数 IDL 属性。 其次,向 Worder 发送 一个事件使得 Worker 以另一个事件回复。 收到的消息仍然显示在日志中。

这是 HTML 页面:

<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">
<title>Shared workers: demo 2</title>
<pre id="log">Log:</pre>
<script>
  var worker = new SharedWorker('test.js');
  var log = document.getElementById('log');
  worker.port.addEventListener('message', function(e) {
    log.textContent += '\n' + e.data;
  }, false);
  worker.port.start(); // note: need this when using addEventListener
  worker.port.postMessage('ping');
</script>

这是 JavaScript worker:

onconnect = function(e) {
  var port = e.ports[0];
  port.postMessage('Hello World!');
  port.onmessage = function(e) {
    port.postMessage('pong'); // not e.ports[0].postMessage!
    // e.target.postMessage('pong'); would work also
  }
}

在线查看本示例


最后这个例子展示两个页面如何连接到同一个 Worker; 这里第二个页面仅仅是第一个页面中的 iframe,但同样的原则对 一个 顶级浏览环境 中的完全独立的页面仍然适用。

这是外部 HTML 页面:

<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">
<title>Shared workers: demo 3</title>
<pre id="log">Log:</pre>
<script>
  var worker = new SharedWorker('test.js');
  var log = document.getElementById('log');
  worker.port.addEventListener('message', function(e) {
    log.textContent += '\n' + e.data;
  }, false);
  worker.port.start();
  worker.port.postMessage('ping');
</script>
<iframe src="inner.html"></iframe>

这是内部 HTML 页面:

<!DOCTYPE HTML>
<html lang="en">
<meta charset="utf-8">
<title>Shared workers: demo 3 inner frame</title>
<pre id=log>Inner log:</pre>
<script>
  var worker = new SharedWorker('test.js');
  var log = document.getElementById('log');
  worker.port.onmessage = function(e) {
   log.textContent += '\n' + e.data;
  }
</script>

这是 JavaScript worker:

var count = 0;
onconnect = function(e) {
  count += 1;
  var port = e.ports[0];
  port.postMessage('Hello World! You are connection #' + count);
  port.onmessage = function(e) {
    port.postMessage('pong');
  }
}

在线查看本示例

10.1.2.4 通过共享 Worker 来共享状态

This section is non-normative.

本例子中,可以同时打开多个窗口(查看器)来浏览同一个地图。 在一个 Worker 的协调下,所有窗口共享同样的地图信息。 每个查看器都可以独立地随意移动,一旦在地图上设置了任何数据,其他查看器也都会更新。

主页面很普通,只是提供了打开查看器的入口:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Workers example: Multiviewer</title>
  <script>
   function openViewer() {
     window.open('viewer.html');
   }
  </script>
 </head>
 <body>
  <p><button type=button onclick="openViewer()">Open a new
  viewer</button></p>
  <p>Each viewer opens in a new window. You can have as many viewers
  as you like, they all view the same data.</p>
 </body>
</html>

查看器就有些意思了:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Workers example: Multiviewer viewer</title>
  <script>
   var worker = new SharedWorker('worker.js', 'core');

   // CONFIGURATION
   function configure(event) {
     if (event.data.substr(0, 4) != 'cfg ') return;
     var name = event.data.substr(4).split(' ', 1)[0];
     // update display to mention our name is name
     document.getElementsByTagName('h1')[0].textContent += ' ' + name;
     // no longer need this listener
     worker.port.removeEventListener('message', configure, false);
   }
   worker.port.addEventListener('message', configure, false);

   // MAP
   function paintMap(event) {
     if (event.data.substr(0, 4) != 'map ') return;
     var data = event.data.substr(4).split(',');
     // display tiles data[0] .. data[8]
     var canvas = document.getElementById('map');
     var context = canvas.getContext('2d');
     for (var y = 0; y < 3; y += 1) {
       for (var x = 0; x < 3; x += 1) {
         var tile = data[y * 3 + x];
         if (tile == '0')
           context.fillStyle = 'green';
         else
           context.fillStyle = 'maroon';
         context.fillRect(x * 50, y * 50, 50, 50);
       }
     }
   }
   worker.port.addEventListener('message', paintMap, false);

   // PUBLIC CHAT
   function updatePublicChat(event) {
     if (event.data.substr(0, 4) != 'txt ') return;
     var name = event.data.substr(4).split(' ', 1)[0];
     var message = event.data.substr(4 + name.length + 1);
     // display "<name> message" in public chat
     var public = document.getElementById('public');
     var p = document.createElement('p');
     var n = document.createElement('button');
     n.textContent = '<' + name + '> ';
     n.onclick = function () { worker.port.postMessage('msg ' + name); };
     p.appendChild(n);
     var m = document.createElement('span');
     m.textContent = message;
     p.appendChild(m);
     public.appendChild(p);
   }
   worker.port.addEventListener('message', updatePublicChat, false);

   // PRIVATE CHAT
   function startPrivateChat(event) {
     if (event.data.substr(0, 4) != 'msg ') return;
     var name = event.data.substr(4).split(' ', 1)[0];
     var port = event.ports[0];
     // display a private chat UI
     var ul = document.getElementById('private');
     var li = document.createElement('li');
     var h3 = document.createElement('h3');
     h3.textContent = 'Private chat with ' + name;
     li.appendChild(h3);
     var div = document.createElement('div');
     var addMessage = function(name, message) {
       var p = document.createElement('p');
       var n = document.createElement('strong');
       n.textContent = '<' + name + '> ';
       p.appendChild(n);
       var t = document.createElement('span');
       t.textContent = message;
       p.appendChild(t);
       div.appendChild(p);
     };
     port.onmessage = function (event) {
       addMessage(name, event.data);
     };
     li.appendChild(div);
     var form = document.createElement('form');
     var p = document.createElement('p');
     var input = document.createElement('input');
     input.size = 50;
     p.appendChild(input);
     p.appendChild(document.createTextNode(' '));
     var button = document.createElement('button');
     button.textContent = 'Post';
     p.appendChild(button);
     form.onsubmit = function () {
       port.postMessage(input.value);
       addMessage('me', input.value);
       input.value = '';
       return false;
     };
     form.appendChild(p);
     li.appendChild(form);
     ul.appendChild(li);
   }
   worker.port.addEventListener('message', startPrivateChat, false);

   worker.port.start();
  </script>
 </head>
 <body>
  <h1>Viewer</h1>
  <h2>Map</h2>
  <p><canvas id="map" height=150 width=150></canvas></p>
  <p>
   <button type=button onclick="worker.port.postMessage('mov left')">Left</button>
   <button type=button onclick="worker.port.postMessage('mov up')">Up</button>
   <button type=button onclick="worker.port.postMessage('mov down')">Down</button>
   <button type=button onclick="worker.port.postMessage('mov right')">Right</button>
   <button type=button onclick="worker.port.postMessage('set 0')">Set 0</button>
   <button type=button onclick="worker.port.postMessage('set 1')">Set 1</button>
  </p>
  <h2>Public Chat</h2>
  <div id="public"></div>
  <form onsubmit="worker.port.postMessage('txt ' + message.value); message.value = ''; return false;">
   <p>
    <input type="text" name="message" size="50">
    <button>Post</button>
   </p>
  </form>
  <h2>Private Chat</h2>
  <ul id="private"></ul>
 </body>
</html>

关于查看器的写法有几个值得一提的关键点。

多监听器。 上述代码加载了多个事件监听器,每个都会检查该消息是否和它相关。 本例子中没太大差别,但如果多个作者都希望使用同一接口与 Worker 通信, 该设计将产生较为独立的代码,否则所有的变更都得在同一事件处理函数中进行。

以这种方式注册事件处理函数也让你可以在处理完后注销特定的监听器, 就像本例子中的 configure() 方法一样。

这是最终的 Worker:

var nextName = 0;
function getNextName() {
  // this could use more friendly names
  // but for now just return a number
  return nextName++;
}

var map = [
 [0, 0, 0, 0, 0, 0, 0],
 [1, 1, 0, 1, 0, 1, 1],
 [0, 1, 0, 1, 0, 0, 0],
 [0, 1, 0, 1, 0, 1, 1],
 [0, 0, 0, 1, 0, 0, 0],
 [1, 0, 0, 1, 1, 1, 1],
 [1, 1, 0, 1, 1, 0, 1],
];

function wrapX(x) {
  if (x < 0) return wrapX(x + map[0].length);
  if (x >= map[0].length) return wrapX(x - map[0].length);
  return x;
}

function wrapY(y) {
  if (y < 0) return wrapY(y + map.length);
  if (y >= map[0].length) return wrapY(y - map.length);
  return y;
}

function wrap(val, min, max) {
  if (val < min)
    return val + (max-min)+1;
  if (val > max)
    return val - (max-min)-1;
  return val;
}

function sendMapData(viewer) {
  var data = '';
  for (var y = viewer.y-1; y <= viewer.y+1; y += 1) {
    for (var x = viewer.x-1; x <= viewer.x+1; x += 1) {
      if (data != '')
        data += ',';
      data += map[wrap(y, 0, map[0].length-1)][wrap(x, 0, map.length-1)];
    }
  }
  viewer.port.postMessage('map ' + data);
}

var viewers = {};
onconnect = function (event) {
  var name = getNextName();
  event.ports[0]._data = { port: event.ports[0], name: name, x: 0, y: 0, };
  viewers[name] = event.ports[0]._data;
  event.ports[0].postMessage('cfg ' + name);
  event.ports[0].onmessage = getMessage;
  sendMapData(event.ports[0]._data);
};

function getMessage(event) {
  switch (event.data.substr(0, 4)) {
    case 'mov ':
      var direction = event.data.substr(4);
      var dx = 0;
      var dy = 0;
      switch (direction) {
        case 'up': dy = -1; break;
        case 'down': dy = 1; break;
        case 'left': dx = -1; break;
        case 'right': dx = 1; break;
      }
      event.target._data.x = wrapX(event.target._data.x + dx);
      event.target._data.y = wrapY(event.target._data.y + dy);
      sendMapData(event.target._data);
      break;
    case 'set ':
      var value = event.data.substr(4);
      map[event.target._data.y][event.target._data.x] = value;
      for (var viewer in viewers)
        sendMapData(viewers[viewer]);
      break;
    case 'txt ':
      var name = event.target._data.name;
      var message = event.data.substr(4);
      for (var viewer in viewers)
        viewers[viewer].port.postMessage('txt ' + name + ' ' + message);
      break;
    case 'msg ':
      var party1 = event.target._data;
      var party2 = viewers[event.data.substr(4).split(' ', 1)[0]];
      if (party2) {
        var channel = new MessageChannel();
        party1.port.postMessage('msg ' + party2.name, [channel.port1]);
        party2.port.postMessage('msg ' + party1.name, [channel.port2]);
      }
      break;
  }
}

连接到多个页面。 脚本中使用 onconnect 时间监听器来监听多个连接。

直接通道。 当 Worker 从查看器收到一条带有另一个查看器名称的"msg"消息时, 它会在这两者之间建立一个直接的连接,使得这两个查看器可以不经由 Worker 代理而直接通信。

在线查看该示例

10.1.2.5 委托

This section is non-normative.

随着多核 CPU 的流行,可以将计算密集型任务分割到多个 Worder 中来得到更好的性能。 在本示例中,一个对1到10,000,000的所有数字进行操作的计算密集型的任务移交给了10个子 worker。

主页面如下,它只是产出结果报告:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Worker example: Multicore computation</title>
 </head>
 <body>
  <p>Result: <output id="result"></output></p>
  <script>
   var worker = new Worker('worker.js');
   worker.onmessage = function (event) {
     document.getElementById('result').textContent = event.data;
   };
  </script>
 </body>
</html>

Worker 本身如下:

// settings
var num_workers = 10;
var items_per_worker = 1000000;

// start the workers
var result = 0;
var pending_workers = num_workers;
for (var i = 0; i < num_workers; i += 1) {
  var worker = new Worker('core.js');
  worker.postMessage(i * items_per_worker);
  worker.postMessage((i+1) * items_per_worker);
  worker.onmessage = storeResult;
}

// handle the results
function storeResult(event) {
  result += 1*event.data;
  pending_workers -= 1;
  if (pending_workers <= 0)
    postMessage(result); // finished!
}

它包含了一个循环来启动子 Worker,然后定义另一个等待所有子 Worker 响应的处理函数。

子 Worker 的实现如下:

var start;
onmessage = getStart;
function getStart(event) {
  start = 1*event.data;
  onmessage = getEnd;
}

var end;
function getEnd(event) {
  end = 1*event.data;
  onmessage = null;
  work();
}

function work() {
  var result = 0;
  for (var i = start; i < end; i += 1) {
    // perform some complex calculation here
    result += 1;
  }
  postMessage(result);
  close();
}

它们在两个事件中接收到两个数字,在这两个数字指定的范围上执行计算,然后向父 Worker 报告结果。

在线查看该示例

10.1.2.6 Providing libraries

This section is non-normative.

Suppose that a cryptography library is made available that provides three tasks:

Generate a public/private key pair
Takes a port, on which it will send two messages, first the public key and then the private key.
Given a plaintext and a public key, return the corresponding ciphertext
Takes a port, to which any number of messages can be sent, the first giving the public key, and the remainder giving the plaintext, each of which is encrypted and then sent on that same channel as the ciphertext. The user can close the port when it is done encrypting content.
Given a ciphertext and a private key, return the corresponding plaintext
Takes a port, to which any number of messages can be sent, the first giving the private key, and the remainder giving the ciphertext, each of which is decrypted and then sent on that same channel as the plaintext. The user can close the port when it is done decrypting content.

The library itself is as follows:

function handleMessage(e) {
  if (e.data == "genkeys")
    genkeys(e.ports[0]);
  else if (e.data == "encrypt")
    encrypt(e.ports[0]);
  else if (e.data == "decrypt")
    decrypt(e.ports[0]);
}

function genkeys(p) {
  var keys = _generateKeyPair();
  p.postMessage(keys[0]);
  p.postMessage(keys[1]);
}

function encrypt(p) {
  var key, state = 0;
  p.onmessage = function (e) {
    if (state == 0) {
      key = e.data;
      state = 1;
    } else {
      p.postMessage(_encrypt(key, e.data));
    }
  };
}

function decrypt(p) {
  var key, state = 0;
  p.onmessage = function (e) {
    if (state == 0) {
      key = e.data;
      state = 1;
    } else {
      p.postMessage(_decrypt(key, e.data));
    }
  };
}

// support being used as a shared worker as well as a dedicated worker
if ('onmessage' in this) // dedicated worker
  onmessage = handleMessage;
else // shared worker
  onconnect = function (e) { e.port.onmessage = handleMessage; }


// the "crypto" functions:

function _generateKeyPair() {
  return [Math.random(), Math.random()];
}

function _encrypt(k, s) {
  return 'encrypted-' + k + ' ' + s;
}

function _decrypt(k, s) {
  return s.substr(s.indexOf(' ')+1);
}

Note that the crypto functions here are just stubs and don't do real cryptography.

This library could be used as follows:

<!DOCTYPE HTML>
<html lang="en">
 <head>
  <meta charset="utf-8">
  <title>Worker example: Crypto library</title>
  <script>
   const cryptoLib = new Worker('libcrypto-v1.js'); // or could use 'libcrypto-v2.js'
   function startConversation(source, message) {
     const messageChannel = new MessageChannel();
     source.postMessage(message, [messageChannel.port2]);
     return messageChannel.port1;
   }
   function getKeys() {
     let state = 0;
     startConversation(cryptoLib, "genkeys").onmessage = function (e) {
       if (state === 0)
         document.getElementById('public').value = e.data;
       else if (state === 1)
         document.getElementById('private').value = e.data;
       state += 1;
     };
   }
   function enc() {
     const port = startConversation(cryptoLib, "encrypt");
     port.postMessage(document.getElementById('public').value);
     port.postMessage(document.getElementById('input').value);
     port.onmessage = function (e) {
       document.getElementById('input').value = e.data;
       port.close();
     };
   }
   function dec() {
     const port = startConversation(cryptoLib, "decrypt");
     port.postMessage(document.getElementById('private').value);
     port.postMessage(document.getElementById('input').value);
     port.onmessage = function (e) {
       document.getElementById('input').value = e.data;
       port.close();
     };
   }
  </script>
  <style>
   textarea { display: block; }
  </style>
 </head>
 <body onload="getKeys()">
  <fieldset>
   <legend>Keys</legend>
   <p><label>Public Key: <textarea id="public"></textarea></label></p>
   <p><label>Private Key: <textarea id="private"></textarea></label></p>
  </fieldset>
  <p><label>Input: <textarea id="input"></textarea></label></p>
  <p><button onclick="enc()">Encrypt</button> <button onclick="dec()">Decrypt</button></p>
 </body>
</html>

A later version of the API, though, might want to offload all the crypto work onto subworkers. This could be done as follows:

function handleMessage(e) {
  if (e.data == "genkeys")
    genkeys(e.ports[0]);
  else if (e.data == "encrypt")
    encrypt(e.ports[0]);
  else if (e.data == "decrypt")
    decrypt(e.ports[0]);
}

function genkeys(p) {
  var generator = new Worker('libcrypto-v2-generator.js');
  generator.postMessage('', [p]);
}

function encrypt(p) {
  p.onmessage = function (e) {
    var key = e.data;
    var encryptor = new Worker('libcrypto-v2-encryptor.js');
    encryptor.postMessage(key, [p]);
  };
}

function encrypt(p) {
  p.onmessage = function (e) {
    var key = e.data;
    var decryptor = new Worker('libcrypto-v2-decryptor.js');
    decryptor.postMessage(key, [p]);
  };
}

// support being used as a shared worker as well as a dedicated worker
if ('onmessage' in this) // dedicated worker
  onmessage = handleMessage;
else // shared worker
  onconnect = function (e) { e.ports[0].onmessage = handleMessage };

The little subworkers would then be as follows.

For generating key pairs:

onmessage = function (e) {
  var k = _generateKeyPair();
  e.ports[0].postMessage(k[0]);
  e.ports[0].postMessage(k[1]);
  close();
}

function _generateKeyPair() {
  return [Math.random(), Math.random()];
}

For encrypting:

onmessage = function (e) {
  var key = e.data;
  e.ports[0].onmessage = function (e) {
    var s = e.data;
    postMessage(_encrypt(key, s));
  }
}

function _encrypt(k, s) {
  return 'encrypted-' + k + ' ' + s;
}

For decrypting:

onmessage = function (e) {
  var key = e.data;
  e.ports[0].onmessage = function (e) {
    var s = e.data;
    postMessage(_decrypt(key, s));
  }
}

function _decrypt(k, s) {
  return s.substr(s.indexOf(' ')+1);
}

Notice how the users of the API don't have to even know that this is happening — the API hasn't changed; the library can delegate to subworkers without changing its API, even though it is accepting data using message channels.

View this example online.

10.1.3 教程

10.1.3.1 创建专用工作线程

This section is non-normative.

创建专用 Worker 需要一个指向 JavaScript 文件的 URL。使用该 URL 作为唯一一个参数来调用Worker() 构造函数,这时会创建并返回一个 Worker:

var worker = new Worker('helper.js');

为了使你的 Worker 脚本被解析为 模块脚本 而不是 经典脚本,你需要使用一个略微不同的函数签名:

var worker = new Worker('helper.js', { type: "module" });
10.1.3.2 与专用 Worker 通信

This section is non-normative.

专用 Worker 其实是 MessagePort 对象,因此支持MessagePort的所有特性。 比如发送结构化数据、传输二进制数据、以及传输其他 Port。

使用 Worker 对象上的 onmessage 事件处理器 IDL 属性 来接收专用 Worker 的消息:

worker.onmessage = function (event) { ... };

你也可以使用 addEventListener() 方法。

在创建专用 Worker 时,它隐式使用的 MessagePortport message queue 会被默认开启。所以没有Worker 接口上没有等价于 MessagePort 接口的 start() 的方法。

使用 postMessage() 方法来 向 Worker 发送 数据。该通信通道可以发送结构化数据, 如果要高效地发送 ArrayBuffer 对象 (通过直接传输它们而不是克隆后发送),在第二个参数上提供它们的列表。

worker.postMessage({
  operation: 'find-edges',
  input: buffer, // an ArrayBuffer object
  threshold: 0.6,
}, [buffer]);

使用 onmessage 事件处理器 IDL 属性在 Worker 中接受消息。

onmessage = function (event) { ... };

你也可以使用 addEventListener() 方法。

上述两种方式中,数据总是在事件对象的 data 属性中提供。

使用 postMessage() 来回复消息,它同样支持结构化数据。

postMessage(event.data.input, [event.data.input]); // transfer the buffer back
10.1.3.3 共享工作线程

This section is non-normative.

共享 worker 是通过创建时的脚本 URL 来识别的。也可以显式地指定名字, 这会使得共享 Worker 可以启动多个实例。

共享 worker 作用域限制在 origin 下。使用同一 Worker 名字的两个站点不会冲突。 然而同一站点中,尝试使用相同的 Worker 名来引用不同的脚本 URL 将会失败。

使用 SharedWorker() 构造函数来创建共享 Worker。 该构造函数使用脚本 URL 作为第一个参数, Worker 名(如果有的话)作为第二个参数。

var worker = new SharedWorker('service.js');

与共享 worker 通信需要显式地使用 MessagePort 对象。 SharedWorker() 构造函数返回的对象的 port属性保有一个对 port 的引用。

worker.port.onmessage = function (event) { ... };
worker.port.postMessage('some message');
worker.port.postMessage({ foo: 'structured', bar: ['data', 'also', 'possible']});

在共享 worker 内,新的客户会使用 connect 事件 来声明,新来的客户的 port 由事件对象的 source 属性给出。

onconnect = function (event) {
  var newPort = event.source;
  // set up a listener
  newPort.onmessage = function (event) { ... };
  // send a message back to the port
  newPort.postMessage('ready!'); // can also send structured data, of course
};

10.2 基础设施

Worker 共有两种:专用 Worker 和共享 Worker。 前者一经创建就会链接到其创建者,但在专用 Worker 中可以使用消息端口与其他浏览环境或 Worker 进行通信。 然而共享 Worker 是有名字的,一经创建任何同的脚本都可以获取该 Worker 的引用并与之通信。

10.2.1 全局作用域

全局作用域是即 worker 的内部。

10.2.1.1 WorkerGlobalScope 通用接口
[Exposed=Worker] 
interface WorkerGlobalScope : EventTarget {
  readonly attribute WorkerGlobalScope self;
  readonly attribute WorkerLocation location;
  readonly attribute WorkerNavigator navigator;
  undefined importScripts(USVString... urls);

  attribute OnErrorEventHandler onerror;
  attribute EventHandler onlanguagechange;
  attribute EventHandler onoffline;
  attribute EventHandler ononline;
  attribute EventHandler onrejectionhandled;
  attribute EventHandler onunhandledrejection;
};

WorkerGlobalScope 对象有一个与之关联的 owner setDocumentWorkerGlobalScope 对象的 集合)。 初始为空,当创建或获取 Worker 时填充。

拥有者不止一个,它是一个 集合 来适应 SharedWorkerGlobalScope 对象。

WorkerGlobalScope 对象有一个与之关联的 worker setWorkerGlobalScope 对象的 集合)。 它初始为空,当创建或获取其他 Worker 时填充。

WorkerGlobalScope 对象有一个与之关联的 type ("classic" 或 "module")。在创建时设置。

WorkerGlobalScope 对象有一个与之关联的 url (null 或一个 URL)。初始值为 null。

WorkerGlobalScope 对象有一个与之关联的 名称(一个字符串)。在创建过程中设置。

名称 可以对每个 WorkerGlobalScope 的子类有不同的语义。 对于 DedicatedWorkerGlobalScope 的实例, 它就是一个简单的开发者提供的名字,主要用于调试用途。 对于 SharedWorkerGlobalScope 的实例,它允许通过 SharedWorker() 构造器获得一个通用共享 Worker 的引用。 对于 ServiceWorkerGlobalScope 对象,名字没有意义(同样地,它也根本没有通过 JavaScript API 暴露出来)。

WorkerGlobalScope 对象有一个与之关联的 referrer 策略 (一个 referrer 策略)。初始值为空字符串。

WorkerGlobalScope 对象有一个与之关联的 嵌入策略 (一个 嵌入策略)。

WorkerGlobalScope 对象有一个与之关联的 CSP 列表。 初始值为空列表。

WorkerGlobalScope 对象有一个与之关联的 模块映射。 初始值为空的 模块映射

WorkerGlobalScope 对象有一个与之关联的 跨域隔离能力 布尔,初始为 false。

workerGlobal . self

WorkerGlobalScope/self

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android34+Safari iOS5+Chrome Android40+WebView Android4.4+Samsung Internet4.0+Opera Android27+
返回 workerGlobal
workerGlobal . location

WorkerGlobalScope/location

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android40+WebView Android4.4+Samsung Internet4.0+Opera Android27+
返回 workerGlobalWorkerLocation 对象。
workerGlobal . navigator

WorkerGlobalScope/navigator

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera11.5+Edge79+
Edge (Legacy)17+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android40+WebView Android4.4+Samsung Internet4.0+Opera Android27+
返回 workerGlobalWorkerNavigator object。
workerGlobal . importScripts(urls...)

WorkerGlobalScope/importScripts

Support in all current engines.

Firefox4+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
获取 urls 中的每一个 URL,按照传入的顺序一个接一个地执行它们并返回 (如果有错误则抛出异常)。

self 属性必须返回 WorkerGlobalScope 对象自己。

location 属性必须 返回与之关联的 WorkerGlobalScope 对象WorkerGlobalScope 对象的 WorkerLocation 对象。

虽然 WorkerLocation 对象在 WorkerGlobalScope 对象之后创建, 但是因它对脚本不可见所以不会产生问题。


下面是实现 WorkerGlobalScope 接口的对象必须 (以 事件处理器 IDL 属性 的方式) 支持的 事件处理器 (以及它们对应的事件处理器事件类型):

事件处理器 事件处理器事件类型
onerror

WorkerGlobalScope/error_event

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android40+WebView Android4.4+Samsung Internet4.0+Opera Android27+
error
onlanguagechange

WorkerGlobalScope/languagechange_event

Support in all current engines.

Firefox74+Safari4+Chrome4+
Opera11.5+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS5+Chrome Android40+WebView Android37+Samsung Internet4.0+Opera Android27+
languagechange
onoffline

WorkerGlobalScope/offline_event

Firefox29+Safari8+ChromeNo
OperaNoEdgeNo
Edge (Legacy)NoInternet ExplorerNo
Firefox Android29+Safari iOS8+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo
offline
ononline

WorkerGlobalScope/online_event

Firefox29+Safari8+ChromeNo
OperaNoEdgeNo
Edge (Legacy)NoInternet ExplorerNo
Firefox Android29+Safari iOS8+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo
online
onrejectionhandled rejectionhandled
onunhandledrejection unhandledrejection
10.2.1.2 专用 Worker 与 DedicatedWorkerGlobalScope 接口
[Global=(Worker,DedicatedWorker),Exposed=DedicatedWorker]
interface DedicatedWorkerGlobalScope : WorkerGlobalScope {
  void postMessage(any message, optional sequence<object> transfer = []);

  void close();

  attribute EventHandler onmessage;
};

DedicatedWorkerGlobalScope 对象的表现就像它有一个与之关联的隐式 MessagePort 一样。该端口是创建 Worker 时建立的通道的一部分,但没有暴露出来。 禁止在DedicatedWorkerGlobalScope之前垃圾回收该对象。

该端口收到的所有消息必须立即传给 DedicatedWorkerGlobalScope 对象。

dedicatedWorkerGlobal . postMessage(message [, transfer ])

DedicatedWorkerGlobalScope/postMessage

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
克隆 message 并传送给与 dedicatedWorkerGlobal 关联的 Worker 对象。transfer 可以传一个不需克隆而直接传输的对象列表。
dedicatedWorkerGlobal . close()

DedicatedWorkerGlobalScope/close

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
终止 dedicatedWorkerGlobal

DedicatedWorkerGlobalScope 对象上的 postMessage() 方法被调用时必须表现得就像立即使用同样的参数列表调用了该端口上的 同名方法 一样, 并且返回同样的返回值。

给定 workerGlobal关闭 worker 的步骤如下:

  1. 忽略所有已添加到 workerGlobal事件循环任务列表 中的 任务

  2. 设置 workerGlobalclosing 标志为 true。(这将阻止后续的任务入队。)

close() 方法被调用时, 必须 关闭 DedicatedWorkerGlobalScope 上的 Worker。


下面是实现 DedicatedWorkerGlobalScope 接口的对象必须 (以 事件处理器 IDL 属性 的方式) 支持的 事件处理器 (以及它们对应的事件处理器事件类型):

事件处理器 事件处理器事件类型
onmessage

DedicatedWorkerGlobalScope/message_event

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11.5+
message
onmessageerror

DedicatedWorkerGlobalScope/messageerror_event

Firefox57+SafariNoChrome60+
Opera47+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android57+Safari iOSNoChrome Android60+WebView Android60+Samsung Internet8.0+Opera Android47+
messageerror

出于 application cache 网络模型的目的,专用 worker 是 创建它的 cache host 的一个扩展。

10.2.1.3 共享 worker 与 SharedWorkerGlobalScope 接口
[Global=(Worker,SharedWorker),Exposed=SharedWorker]
interface SharedWorkerGlobalScope : WorkerGlobalScope {
  readonly attribute DOMString name;

  undefined close();

  attribute EventHandler onconnect;
};

SharedWorkerGlobalScope 对象有与之相关联的 构造器 origin构造器 url,以及 credentials。它们在创建 SharedWorkerGlobalScope 对象时初始化,是 运行 Worker 算法的一部分。

共享 worker 通过它们的 SharedWorkerGlobalScope 对象上的 connect 事件接受每个连接的消息端口。

sharedWorkerGlobal . name

SharedWorkerGlobalScope/name

Firefox29+SafariNoChrome4+
Opera10.6+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android29+Safari iOSNoChrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
返回 sharedWorkerGlobalname,即给到 SharedWorker 构造函数的值。 通过复用同一个名字,多个 SharedWorker 对象可以对应于同一个共享工作线程(以及 SharedWorkerGlobalScope)。
sharedWorkerGlobal . close()

SharedWorkerGlobalScope/close

Support in all current engines.

Firefox29+Safari5+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android29+Safari iOS7+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
终止 sharedWorkerGlobal

name 属性必须返回 SharedWorkerGlobalScope 对象的 name。使用 SharedWorker 构造器, 可以通过 name 的值获取该 worker 的引用。

close() 方法被调用时,必须 关闭SharedWorkerGlobalScope 对象上的 worker。


下面是实现 SharedWorkerGlobalScope 接口的对象必须 (以 事件处理器 IDL 属性 的方式) 支持的 事件处理器 (以及它们对应的事件处理器事件类型):

事件处理器 事件处理器事件类型
onconnect

SharedWorkerGlobalScope/connect_event

Firefox29+SafariNoChrome4+
Opera10.6+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android29+Safari iOSNoChrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
connect

10.2.2 事件循环

工作线程事件循环任务队列任务 只有事件、回调和网络活动。 这些 工作线程事件循环运行一个工作线程 算法创建。

每个 WorkerGlobalScope 对象也有一个 closing 标志,初始值 必须为 false, 但在 可以 被下面的处理模型一节中的算法 设为 true。

一旦 WorkerGlobalScopeclosing 标志被设为 true, 事件循环任务队列 必须 忽略后续添加的 任务 (已经在队列中的任务不受影响,除非另有说明)。 也就是说一旦 closing 标志位 true, 定时器会停止触发,所有正在进行的后台操作的通知会被扔掉。

10.2.3 The worker's lifetime

Workers communicate with other workers and with browsing contexts through message channels and their MessagePort objects.

Each WorkerGlobalScope object worker global scope has a list of the worker's ports, which consists of all the MessagePort objects that are entangled with another port and that have one (but only one) port owned by worker global scope. This list includes the implicit MessagePort in the case of dedicated workers.

Given an environment settings object o when creating or obtaining a worker, the relevant owner to add depends on the type of global object specified by o. If o specifies a global object that is a WorkerGlobalScope object (i.e., if we are creating a nested dedicated worker), then the relevant owner is that global object. Otherwise, o specifies a global object that is a Window object, and the relevant owner is the responsible document specified by o.


A worker is said to be a permissible worker if its WorkerGlobalScope's owner set is not empty or:

The second part of this definition allows a shared worker to survive for a short time while a page is loading, in case that page is going to contact the shared worker again. This can be used by user agents as a way to avoid the cost of restarting a shared worker used by a site when the user is navigating from page to page within that site.

A worker is said to be an active needed worker if any its owners are either Document objects that are fully active or active needed workers.

A worker is said to be a protected worker if it is an active needed worker and either it has outstanding timers, database transactions, or network connections, or its list of the worker's ports is not empty, or its WorkerGlobalScope is actually a SharedWorkerGlobalScope object (i.e., the worker is a shared worker).

A worker is said to be a suspendable worker if it is not an active needed worker but it is a permissible worker.

10.2.4 Processing model

When a user agent is to run a worker for a script with Worker or SharedWorker object worker, URL url, environment settings object outside settings, MessagePort outside port, and a WorkerOptions dictionary options, it must run the following steps.

  1. Let is shared be true if worker is a SharedWorker object, and false otherwise.

  2. Let owner be the relevant owner to add given outside settings.

  3. Let parent worker global scope be null.

  4. If owner is a WorkerGlobalScope object (i.e., we are creating a nested dedicated worker), then set parent worker global scope to owner.

  5. Let agent be the result of obtaining a dedicated/shared worker agent given outside settings and is shared. Run the rest of these steps in that agent.

    For the purposes of timing APIs, this is the official moment of creation of the worker.

  6. Let realm execution context be the result of creating a new JavaScript realm given agent and the following customizations:

  7. Let worker global scope be the global object of realm execution context's Realm component.

    This is the DedicatedWorkerGlobalScope or SharedWorkerGlobalScope object created in the previous step.

  8. Set up a worker environment settings object with realm execution context and outside settings, and let inside settings be the result.

  9. Set worker global scope's name to the value of options's name member.

  10. Append owner to worker global scope's owner set.

  11. If parent worker global scope is not null, then append worker global scope to parent worker global scope's worker set.

  12. If is shared is true, then:

    1. Set worker global scope's constructor origin to outside settings's origin.

    2. Set worker global scope's constructor url to url.

    3. Set worker global scope's type to the value of options's type member.

    4. Set worker global scope's credentials to the value of options's credentials member.

  13. Let destination be "sharedworker" if is shared is true, and "worker" otherwise.

  14. Obtain script by switching on the value of options's type member:

    "classic"
    Fetch a classic worker script given url, outside settings, destination, and inside settings.
    "module"
    Fetch a module worker script graph given url, outside settings, destination, the value of the credentials member of options, and inside settings.

    In both cases, to perform the fetch given request, perform the following steps if the is top-level flag is set:

    1. Set request's reserved client to inside settings.
    2. Fetch request, and asynchronously wait to run the remaining steps as part of fetch's process response for the response response.

    3. Set worker global scope's url to response's url.

    4. Set worker global scope's referrer policy to the result of parsing the `Referrer-Policy` header of response.

    5. If response's url's scheme is a local scheme, then set worker global scope's embedder policy to owner's embedder policy.

    6. Otherwise, set worker global scope's embedder policy to the result of obtaining an embedder policy from response.

    7. If worker global scope's embedder policy is "require-corp" and is shared is true, then set agent's agent cluster's cross-origin isolated to true.

      This really ought to be set when the agent cluster is created, which requires a redesign of this section.

    8. If the result of checking a global object's embedder policy with worker global scope, owner, and response is false, then set response to a network error.

    9. Set worker global scope's cross-origin isolated capability to agent's agent cluster's cross-origin isolated.

    10. If is shared is false and owner's cross-origin isolated capability is false, then set worker global scope's cross-origin isolated capability to false.

    11. If is shared is false and response's url's scheme is "data", then set worker global scope's cross-origin isolated capability to false.

      This is a conservative default for now, while we figure out how workers in general, and data: URL workers in particular (which are cross-origin from their owner), will be treated in the context of permissions policies. See w3c/webappsec-permissions-policy issue #207 for more details.

    12. Initialize a global object's CSP list given worker global scope and response. [CSP]

    13. Asynchronously complete the perform the fetch steps with response.

    If the algorithm asynchronously completes with null or with a script whose error to rethrow is non-null, then:

    1. Queue a global task on the DOM manipulation task source given worker's relevant global object to fire an event named error at worker.

    2. Run the environment discarding steps for inside settings.

    3. Return.

    Otherwise, continue the rest of these steps after the algorithm's asynchronous completion, with script being the asynchronous completion value.

  15. Associate worker with worker global scope.

  16. Let inside port be a new MessagePort object in inside settings's Realm.

  17. Associate inside port with worker global scope.

  18. Entangle outside port and inside port.

  19. Create a new WorkerLocation object and associate it with worker global scope.

  20. Closing orphan workers: Start monitoring the worker such that no sooner than it stops being a protected worker, and no later than it stops being a permissible worker, worker global scope's closing flag is set to true.

  21. Suspending workers: Start monitoring the worker, such that whenever worker global scope's closing flag is false and the worker is a suspendable worker, the user agent suspends execution of script in that worker until such time as either the closing flag switches to true or the worker stops being a suspendable worker.

  22. Set inside settings's execution ready flag.

  23. If script is a classic script, then run the classic script script. Otherwise, it is a module script; run the module script script.

    In addition to the usual possibilities of returning a value or failing due to an exception, this could be prematurely aborted by the terminate a worker algorithm defined below.

  24. Enable outside port's port message queue.

  25. If is shared is false, enable the port message queue of the worker's implicit port.

  26. If is shared is true, then queue a global task on DOM manipulation task source given worker global scope to fire an event named connect at worker global scope, using MessageEvent, with the data attribute initialized to the empty string, the ports attribute initialized to a new frozen array containing inside port, and the source attribute initialized to inside port.

  27. Enable the client message queue of the ServiceWorkerContainer object whose associated service worker client is worker global scope's relevant settings object.

  28. Event loop: Run the responsible event loop specified by inside settings until it is destroyed.

    The handling of events or the execution of callbacks by tasks run by the event loop might get prematurely aborted by the terminate a worker algorithm defined below.

    The worker processing model remains on this step until the event loop is destroyed, which happens after the closing flag is set to true, as described in the event loop processing model.

  29. Empty the worker global scope's list of active timers.

  30. Disentangle all the ports in the list of the worker's ports.

  31. Empty worker global scope's owner set.


When a user agent is to terminate a worker it must run the following steps in parallel with the worker's main loop (the "run a worker" processing model defined above):

  1. Set the worker's WorkerGlobalScope object's closing flag to true.

  2. If there are any tasks queued in the WorkerGlobalScope object's relevant agent's event loop's task queues, discard them without processing them.

  3. Abort the script currently running in the worker.

  4. If the worker's WorkerGlobalScope object is actually a DedicatedWorkerGlobalScope object (i.e. the worker is a dedicated worker), then empty the port message queue of the port that the worker's implicit port is entangled with.

User agents may invoke the terminate a worker algorithm when a worker stops being an active needed worker and the worker continues executing even after its closing flag was set to true.

10.2.5 Runtime script errors

Whenever an uncaught runtime script error occurs in one of the worker's scripts, if the error did not occur while handling a previous script error, the user agent must report the error for that script, with the position (line number and column number) where the error occurred, using the WorkerGlobalScope object as the target.

For shared workers, if the error is still not handled afterwards, the error may be reported to a developer console.

For dedicated workers, if the error is still not handled afterwards, the user agent must queue a task to run these steps:

  1. Let notHandled be the result of firing an event named error at the Worker object associated with the worker, using ErrorEvent, with the cancelable attribute initialized to true, the message, filename, lineno, and colno attributes initialized appropriately, and the error attribute initialized to null.

  2. If notHandled is true, then the user agent must act as if the uncaught runtime script error had occurred in the global scope that the Worker object is in, thus repeating the entire runtime script error reporting process one level up.

If the implicit port connecting the worker to its Worker object has been disentangled (i.e. if the parent worker has been terminated), then the user agent must act as if the Worker object had no error event handler and as if that worker's onerror attribute was null, but must otherwise act as described above.

Thus, error reports propagate up to the chain of dedicated workers up to the original Document, even if some of the workers along this chain have been terminated and garbage collected.

The task source for the task mentioned above is the DOM manipulation task source.

10.2.6 创建 Worker

10.2.6.1 The AbstractWorker mixin
interface mixin AbstractWorker {
  attribute EventHandler onerror;
};

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by objects implementing the AbstractWorker interface:

Event handler Event handler event type
onerror

ServiceWorker/error_event

Support in all current engines.

Firefox44+Safari11.1+Chrome40+
Opera27+Edge79+
Edge (Legacy)17+Internet ExplorerNo
Firefox Android44+Safari iOS11.3+Chrome Android40+WebView Android40+Samsung Internet4.0+Opera Android27+

SharedWorker/error_event

Firefox29+Safari5–7Chrome4+
Opera10.6+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android33+Safari iOS5–7Chrome AndroidNoWebView AndroidNoSamsung Internet4.0–5.0Opera Android11–14

Worker/error_event

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
error
10.2.6.2 Script settings for workers

To set up a worker environment settings object, given a JavaScript execution context execution context and environment settings object outside settings:

  1. Let inherited origin be outside settings's origin.

  2. Let realm be the value of execution context's Realm component.

  3. Let worker global scope be realm's global object.

  4. Let settings object be a new environment settings object whose algorithms are defined as follows:

    The realm execution context

    Return execution context.

    The module map

    Return worker global scope's module map.

    The responsible document

    Not applicable (the responsible event loop is not a window event loop).

    The API URL character encoding

    Return UTF-8.

    The API base URL

    Return worker global scope's url.

    The origin

    Return a unique opaque origin if worker global scope's url's scheme is "data", and inherited origin otherwise.

    The referrer policy

    Return worker global scope's referrer policy.

    The embedder policy

    Return worker global scope's embedder policy.

    The cross-origin isolated capability

    Return worker global scope's cross-origin isolated capability.

  5. Set settings object's id to a new unique opaque string, creation URL to worker global scope's url, top-level creation URL to null, target browsing context to null, and active service worker to null.

  6. If worker global scope is a DedicatedWorkerGlobalScope object, then set settings object's top-level origin to outside settings's top-level origin.

  7. Otherwise, set settings object's top-level origin to an implementation-defined value.

    See Client-Side Storage Partitioning for the latest on properly defining this.

  8. Set realm's [[HostDefined]] field to settings object.

  9. Return settings object.

10.2.6.3 Dedicated workers and the Worker interface

Worker

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
[Exposed=(Window,DedicatedWorker,SharedWorker)]
interface Worker : EventTarget {
  constructor(USVString scriptURL, optional WorkerOptions options = {});

  undefined terminate();

  undefined postMessage(any message, sequence<object> transfer);
  undefined postMessage(any message, optional PostMessageOptions options = {});
  attribute EventHandler onmessage;
  attribute EventHandler onmessageerror;
};

dictionary WorkerOptions {
  WorkerType type = "classic";
  RequestCredentials credentials = "same-origin"; // credentials is only used if type is "module"
  DOMString name = "";
};

enum WorkerType { "classic", "module" };

Worker includes AbstractWorker;
worker = new Worker(scriptURL [, options ])

Worker/Worker

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
Returns a new Worker object. scriptURL will be fetched and executed in the background, creating a new global environment for which worker represents the communication channel. options can be used to define the name of that global environment via the name option, primarily for debugging purposes. It can also ensure this new global environment supports JavaScript modules (specify type: "module"), and if that is specified, can also be used to specify how scriptURL is fetched through the credentials option.
worker . terminate()

Worker/terminate

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
Aborts worker's associated global environment.
worker . postMessage(message [, transfer ] )

Worker/postMessage

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11+
worker . postMessage(message [, { transfer } ] )
Clones message and transmits it to worker's global environment. transfer can be passed as a list of objects that are to be transferred rather than cloned.

The terminate() method, when invoked, must cause the terminate a worker algorithm to be run on the worker with which the object is associated.

Worker objects act as if they had an implicit MessagePort associated with them. This port is part of a channel that is set up when the worker is created, but it is not exposed. This object must never be garbage collected before the Worker object.

All messages received by that port must immediately be retargeted at the Worker object.

The postMessage(message, transfer) and postMessage(message, options) methods on Worker objects act as if, when invoked, they immediately invoked the respective postMessage(message, transfer) and postMessage(message, options) on the port, with the same arguments, and returned the same return value.

The postMessage() method's first argument can be structured data:

worker.postMessage({opcode: 'activate', device: 1938, parameters: [23, 102]});

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by objects implementing the Worker interface:

Event handler Event handler event type
onmessage message
onmessageerror messageerror

When the Worker(scriptURL, options) constructor is invoked, the user agent must run the following steps:

  1. The user agent may throw a "SecurityError" DOMException if the request violates a policy decision (e.g. if the user agent is configured to not allow the page to start dedicated workers).

  2. Let outside settings be the current settings object.

  3. Parse the scriptURL argument relative to outside settings.

  4. If this fails, throw a "SyntaxError" DOMException.

  5. Let worker URL be the resulting URL record.

    Any same-origin URL (including blob: URLs) can be used. data: URLs can also be used, but they create a worker with an opaque origin.

  6. Let worker be a new Worker object.

  7. Let outside port be a new MessagePort in outside settings's Realm.

  8. Associate the outside port with worker.

  9. Run this step in parallel:

    1. Run a worker given worker, worker URL, outside settings, outside port, and options.

  10. Return worker.

10.2.6.4 Shared workers and the SharedWorker interface

SharedWorker

Firefox29+Safari5–7Chrome4+
Opera10.6+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android33+Safari iOS5–7Chrome AndroidNoWebView AndroidNoSamsung Internet4.0–5.0Opera Android11–14
[Exposed=Window]
interface SharedWorker : EventTarget {
  constructor(USVString scriptURL, optional (DOMString or WorkerOptions) options = {});

  readonly attribute MessagePort port;
};
SharedWorker includes AbstractWorker;
sharedWorker = new SharedWorker(scriptURL [, name ])

SharedWorker/SharedWorker

Firefox29+Safari5–7Chrome4+
Opera10.6+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android33+Safari iOS5–7Chrome AndroidNoWebView AndroidNoSamsung Internet4.0–5.0Opera Android11–14
Returns a new SharedWorker object. scriptURL will be fetched and executed in the background, creating a new global environment for which sharedWorker represents the communication channel. name can be used to define the name of that global environment.
sharedWorker = new SharedWorker(scriptURL [, options ])
Returns a new SharedWorker object. scriptURL will be fetched and executed in the background, creating a new global environment for which sharedWorker represents the communication channel. options can be used to define the name of that global environment via the name option. It can also ensure this new global environment supports JavaScript modules (specify type: "module"), and if that is specified, can also be used to specify how scriptURL is fetched through the credentials option. Note that attempting to construct a shared worker with options whose type or credentials values mismatch an existing shared worker will cause the returned sharedWorker to fire an error event and not connect to the existing shared worker.
sharedWorker . port

SharedWorker/port

Firefox29+Safari5–7Chrome4+
Opera10.6+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android33+Safari iOS5–7Chrome AndroidNoWebView AndroidNoSamsung Internet4.0–5.0Opera Android11–14
Returns sharedWorker's MessagePort object which can be used to communicate with the global environment.

The port attribute must return the value it was assigned by the object's constructor. It represents the MessagePort for communicating with the shared worker.

A user agent has an associated shared worker manager which is the result of starting a new parallel queue.

Each user agent has a single shared worker manager for simplicity. Implementations could use one per origin; that would not be observably different and enables more concurrency.

When the SharedWorker(scriptURL, options) constructor is invoked:

  1. Optionally, throw a "SecurityError" DOMException if the request violates a policy decision (e.g. if the user agent is configured to not allow the page to start shared workers).

  2. If options is a DOMString, set options to a new WorkerOptions dictionary whose name member is set to the value of options and whose other members are set to their default values.

  3. Let outside settings be the current settings object.

  4. Parse scriptURL relative to outside settings.

  5. If this fails, throw a "SyntaxError" DOMException.

  6. Otherwise, let urlRecord be the resulting URL record.

    Any same-origin URL (including blob: URLs) can be used. data: URLs can also be used, but they create a worker with an opaque origin.

  7. Let worker be a new SharedWorker object.

  8. Let outside port be a new MessagePort in outside settings's Realm.

  9. Assign outside port to the port attribute of worker.

  10. Let callerIsSecureContext be true if outside settings is a secure context; otherwise, false.

  11. Enqueue the following steps to the shared worker manager:

    1. Let worker global scope be null.

    2. If there exists a SharedWorkerGlobalScope object whose closing flag is false, constructor origin is same origin with outside settings's origin, constructor url equals urlRecord, and name equals the value of options's name member, then set worker global scope to that SharedWorkerGlobalScope object.

      data: URLs create a worker with an opaque origin. Both the constructor origin and constructor url are compared so the same data: URL can be used within an origin to get to the same SharedWorkerGlobalScope object, but cannot be used to bypass the same origin restriction.

    3. If worker global scope is not null, but the user agent has been configured to disallow communication between the worker represented by the worker global scope and the scripts whose settings object is outside settings, then set worker global scope to null.

      For example, a user agent could have a development mode that isolates a particular top-level browsing context from all other pages, and scripts in that development mode could be blocked from connecting to shared workers running in the normal browser mode.

    4. If worker global scope is not null, then check if worker global scope's type and credentials match the options values. If not, queue a task to fire an event named error and abort these steps.

    5. If worker global scope is not null, then run these subsubsteps:

      1. Let settings object be the relevant settings object for worker global scope.

      2. Let workerIsSecureContext be true if settings object is a secure context; otherwise, false.

      3. If workerIsSecureContext is not callerIsSecureContext, then queue a task to fire an event named error at worker and abort these steps. [SECURE-CONTEXTS]

      4. Associate worker with worker global scope.

      5. Let inside port be a new MessagePort in settings object's Realm.

      6. Entangle outside port and inside port.

      7. Queue a task, using the DOM manipulation task source, to fire an event named connect at worker global scope, using MessageEvent, with the data attribute initialized to the empty string, the ports attribute initialized to a new frozen array containing only inside port, and the source attribute initialized to inside port.

      8. Append the relevant owner to add given outside settings to worker global scope's owner set.

    6. Otherwise, in parallel, run a worker given worker, urlRecord, outside settings, outside port, and options.

  12. Return worker.

interface mixin NavigatorConcurrentHardware {
  readonly attribute unsigned long long hardwareConcurrency;
};
self . navigator . hardwareConcurrency

Navigator/hardwareConcurrency

Firefox48+Safari10.1–11Chrome37+
Opera24+Edge79+
Edge (Legacy)15+Internet ExplorerNo
Firefox Android48+Safari iOS10.3–11Chrome Android37+WebView Android37+Samsung Internet3.0+Opera Android24+

Navigator/hardwareConcurrency

Firefox48+Safari10.1–11Chrome37+
Opera24+Edge79+
Edge (Legacy)15+Internet ExplorerNo
Firefox Android48+Safari iOS10.3–11Chrome Android37+WebView Android37+Samsung Internet3.0+Opera Android24+

Returns the number of logical processors potentially available to the user agent.

(This is a tracking vector.) The navigator.hardwareConcurrency attribute's getter must return a number between 1 and the number of logical processors potentially available to the user agent. If this cannot be determined, the getter must return 1.

User agents should err toward exposing the number of logical processors available, using lower values only in cases where there are user-agent specific limits in place (such as a limitation on the number of workers that can be created) or when the user agent desires to limit fingerprinting possibilities.

10.3 Worker 中可用的 API

10.3.1 Importing scripts and libraries

When a script invokes the importScripts(urls) method on a WorkerGlobalScope object, the user agent must import scripts into worker global scope given this WorkerGlobalScope object and urls.

To import scripts into worker global scope, given a WorkerGlobalScope object worker global scope and a sequence<DOMString> urls, run these steps. The algorithm may optionally be customized by supplying custom perform the fetch hooks, which if provided will be used when invoking fetch a classic worker-imported script.

  1. If worker global scope's type is "module", throw a TypeError exception.

  2. Let settings object be the current settings object.

  3. If urls is empty, return.

  4. Parse each value in urls relative to settings object. If any fail, throw a "SyntaxError" DOMException.

  5. For each url in the resulting URL records, run these substeps:

    1. Fetch a classic worker-imported script given url and settings object, passing along any custom perform the fetch steps provided. If this succeeds, let script be the result. Otherwise, rethrow the exception.

    2. Run the classic script script, with the rethrow errors argument set to true.

      script will run until it either returns, fails to parse, fails to catch an exception, or gets prematurely aborted by the terminate a worker algorithm defined above.

      If an exception was thrown or if the script was prematurely aborted, then abort all these steps, letting the exception or aborting continue to be processed by the calling script.

Service Workers is an example of a specification that runs this algorithm with its own options for the perform the fetch hook. [SW]

10.3.2 The WorkerNavigator interface

WorkerNavigator

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The navigator attribute of the WorkerGlobalScope interface must return an instance of the WorkerNavigator interface, which represents the identity and state of the user agent (the client):

[Exposed=Worker]
interface WorkerNavigator {};
WorkerNavigator includes NavigatorID;
WorkerNavigator includes NavigatorLanguage;
WorkerNavigator includes NavigatorOnLine;
WorkerNavigator includes NavigatorConcurrentHardware;

10.3.3 The WorkerLocation interface

WorkerLocation

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

WorkerLocation/toString

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
[Exposed=Worker]
interface WorkerLocation {
  stringifier readonly attribute USVString href;
  readonly attribute USVString origin;
  readonly attribute USVString protocol;
  readonly attribute USVString host;
  readonly attribute USVString hostname;
  readonly attribute USVString port;
  readonly attribute USVString pathname;
  readonly attribute USVString search;
  readonly attribute USVString hash;
};

A WorkerLocation object has an associated WorkerGlobalScope object (a WorkerGlobalScope object).

WorkerLocation/href

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The href attribute's getter must return the associated WorkerGlobalScope object's url, serialized.

WorkerLocation/origin

Support in all current engines.

Firefox29+Safari10+Chrome38+
Opera25+Edge79+
Edge (Legacy)14+Internet ExplorerNo
Firefox Android29+Safari iOS10+Chrome Android38+WebView Android38+Samsung Internet3.0+Opera Android25+

The origin attribute's getter must return the serialization of the associated WorkerGlobalScope object's url's origin.

WorkerLocation/protocol

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The protocol attribute's getter must return the associated WorkerGlobalScope object's url's scheme, followed by ":".

WorkerLocation/host

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The host attribute's getter must run these steps:

  1. Let url be the associated WorkerGlobalScope object's url.

  2. If url's host is null, return the empty string.

  3. If url's port is null, return url's host, serialized.

  4. Return url's host, serialized, followed by ":" and url's port, serialized.

WorkerLocation/hostname

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The hostname attribute's getter must run these steps:

  1. Let host be the associated WorkerGlobalScope object's url's host.

  2. If host is null, return the empty string.

  3. Return host, serialized.

WorkerLocation/port

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The port attribute's getter must run these steps:

  1. Let port be the associated WorkerGlobalScope object's url's port.

  2. If port is null, return the empty string.

  3. Return port, serialized.

WorkerLocation/pathname

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The pathname attribute's getter must run these steps:

  1. Let url be the associated WorkerGlobalScope object's url.

  2. If url's cannot-be-a-base-URL flag is set, return the first string in url's path.

  3. Return "/", followed by the strings in url's path (including empty strings), separated from each other by "/".

WorkerLocation/search

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The search attribute's getter must run these steps:

  1. Let query be the associated WorkerGlobalScope object's url's query.

  2. If query is either null or the empty string, return the empty string.

  3. Return "?", followed by query.

WorkerLocation/hash

Support in all current engines.

Firefox3.5+Safari4+Chrome3+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12.1+

The hash attribute's getter must run these steps:

  1. Let fragment be the associated WorkerGlobalScope object's url's fragment.

  2. If fragment is either null or the empty string, return the empty string.

  3. Return "#", followed by fragment.

11 Worklets

11.1 Introduction

This section is non-normative.

Worklets are a piece of specification infrastructure which can be used for running scripts independent of the main JavaScript execution environment, while not requiring any particular implementation model.

The worklet infrastructure specified here cannot be used directly by web developers. Instead, other specifications build upon it to create directly-usable worklet types, specialized for running in particular parts of the browser implementation pipeline.

11.1.1 Motivations

This section is non-normative.

Allowing extension points to rendering, or other sensitive parts of the implementation pipeline such as audio output, is difficult. If extension points were done with full access to the APIs available on Window, engines would need to abandon previously-held assumptions for what could happen in the middle of those phases. For example, during the layout phase, rendering engines assume that no DOM will be modified.

Additionaly, defining extension points in the Window environment would restrict user agents to performing work in the same thread as the Window object. (Unless implementations added complex, high-overhead infrastructure to allow thread-safe APIs, as well as thread-joining guarantees.)

Worklets are designed to allow extension points, while keeping guarantees that user agents currently rely on. This is done through new global environments, based on subclasses of WorkletGlobalScope.

Worklets are similar to web workers. However, they:

As worklets have relatively high overhead, they are best used sparingly. Due to this, a given WorkletGlobalScope is expected to be shared between multiple separate scripts. (This is similar to how a single Window is shared between multiple separate scripts.)

Worklets are a general technology that serve different use cases. Some worklets, such as those defined in CSS Painting API, provide extension points intended for stateless, idempotent, and short-running computations, which have special considerations as described in the next couple of sections. Others, such as those defined in Web Audio API, are used for stateful, long-running operations. [CSSPAINT] [WEBAUDIO]

11.1.2 Code idempotence

Some specifications which use worklets are intended to allow user agents to parallelize work over multiple threads, or to move work between threads as required. In these specifications, user agents might invoke methods on a web-developer-provided class in an implementation-defined order.

As a result of this, to prevent interoperability issues, authors who register classes on such WorkletGlobalScopes should make their code idempotent. That is, a method or set of methods on the class should produce the same output given a particular input.

This specification uses the following techniques in order to encourage authors to write code in an idempotent way:

Together, these restrictions help prevent two different scripts from sharing state using properties of the global object.

Additionally, specifications which use worklets and intend to allow implementation-defined behavior must obey the following:

11.1.3 Speculative evaluation

Some specifications which use worklets can invoke methods on a web-developer-provided class based on the state of the user agent. To increase concurrency between threads, a user agent may invoke a method speculatively, based on potential future states.

In these specifications, user agents might invoke such methods at any time, and with any arguments, not just ones corresponding to the current state of the user agent. The reuslts of such speculative evaluations are not displayed immediately, but can be cached for use if the user agent state matches the speculated state. This can increase the concurrency between the user agent and worklet threads.

As a result of this, to prevent interoperability risks between user agents, authors who register classes on such WorkletGlobalScopes should make their code stateless. That is, the only effect of invoking a method should be its result, and not any side effects such as updating mutable state.

The same techniques which encourage code idempotence also encourage authors to write stateless code.

11.2 Examples

This section is non-normative.

For these examples, we'll use a fake worklet. The Window object provides two Worklet instances, which each run code in their own collection of FakeWorkletGlobalScopes:

partial interface Window {
  [SameObject, SecureContext] readonly attribute Worklet fakeWorklet1;
  [SameObject, SecureContext] readonly attribute Worklet fakeWorklet2;
};

Each Window has two Worklet instances, fake worklet 1 and fake worklet 2. Both of these have their worklet global scope type set to FakeWorkletGlobalScope, and their worklet destination type set to "fakeworklet". User agents should create at least two FakeWorkletGlobalScope instances per worklet.

"fakeworklet" is not actually a valid destination per Fetch. But this illustrates how real worklets would generally have their own worklet-type-specific destination. [FETCH]

The fakeWorklet1 getter steps are to return this's fake worklet 1.

The fakeWorklet2 getter steps are to return this's fake worklet 2.


[Global=(Worklet,FakeWorklet),
 Exposed=FakeWorklet,
 SecureContext]
interface FakeWorkletGlobalScope {
  undefined registerFake(DOMString type, Function classConstructor);
};

Each FakeWorkletGlobalScope has a registered class constructors map, which is an ordered map, initially empty.

The registerFake(type, classConstructor) method steps are to set this's registered class constructors map[type] to classConstructor.

11.2.1 Loading scripts

This section is non-normative.

To load scripts into fake worklet 1, a web developer would write:

window.fakeWorklet1.addModule('script1.mjs');
window.fakeWorklet1.addModule('script2.mjs');

Note that which script finishes fetching and runs first is dependent on network timing: it could be either script1.mjs or script2.mjs. This generally won't matter for well-written scripts intended to be loaded in worklets, if they follow the suggestions about preparing for speculative evaluation.

If a web developer wants to perform a task only after the scripts have successfully run and loaded into some worklets, they could write:

Promise.all([
    window.fakeWorklet1.addModule('script1.mjs'),
    window.fakeWorklet2.addModule('script2.mjs')
]).then(() => {
    // Do something which relies on those scripts being loaded.
});

Another important point about script-loading is that loaded scripts can be run in multiple WorkletGlobalScopes per Worklet, as discussed in the section on code idempotence. In particular, the specification above for fake worklet 1 and fake worklet 2 require this. So, consider a scenario such as the following:

// script.mjs
console.log("Hello from a FakeWorkletGlobalScope!");
// app.mjs
window.fakeWorklet1.addModule("script.mjs");

This could result in output such as the following from a user agent's console:

[fakeWorklet1#1] Hello from a FakeWorkletGlobalScope!
[fakeWorklet1#4] Hello from a FakeWorkletGlobalScope!
[fakeWorklet1#2] Hello from a FakeWorkletGlobalScope!
[fakeWorklet1#3] Hello from a FakeWorkletGlobalScope!

If the user agent at some point decided to kill and restart the third instance of FakeWorkletGlobalScope, the console would again print [fakeWorklet1#3] Hello from a FakeWorkletGlobalScope! when this occurs.

11.2.2 Registering a class and invoking its methods

This section is non-normative.

Let's say that one of the intended usages of our fake worklet by web developers is to allow them to customize the highly-complex process of boolean negation. They might register their customization as follows:

// script.mjs
registerFake('negation-processor', class {
  process(arg) {
    return !arg;
  }
});
// app.mjs
window.fakeWorklet1.addModule("script.mjs");

To make use of such registered classes, the specification for fake worklets could define a find the opposite of true algorithm, given a Worklet worklet:

  1. Optionally, create a worklet global scope for worklet.

  2. Let workletGlobalScope be one of worklet's global scopes, chosen in an implementation-defined manner.

  3. Let classConstructor be workletGlobalScope's registered class constructors map["negation-processor"].

  4. Let classInstance be the result of constructing classConstructor, with no arguments.

  5. Let function be Get(classInstance, "process"). Rethrow any exceptions.

  6. Let callback be the result of converting function to a Web IDL Function instance.

  7. Return the result of invoking callback with the arguments « true » and with classInstance as the callback this value.

Another, perhaps better, specification architecture would be to extract the "process" property and convert it into a Function at registration time, as part of the registerFake() method steps.

11.3 Infrastructure

11.3.1 The global scope

Subclasses of WorkletGlobalScope are used to create global objects wherein code loaded into a particular Worklet can execute.

[Exposed=Worklet, SecureContext]
interface WorkletGlobalScope {};

Other specifications are intended to subclass WorkletGlobalScope, adding APIs to register a class, as well as other APIs specific for their worklet type.

Each WorkletGlobalScope has an associated module map. It is a module map, initially empty.

11.3.1.1 Agents and event loops

This section is non-normative.

Each WorkletGlobalScope is contained in its own worklet agent, which has its corresponding event loop. However, in practice, implementation of these agents and event loops is expected to be different from most others.

A worklet agent exists for each WorkletGlobalScope since, in theory, an implementation could use a separate thread for each WorkletGlobalScope instance, and allowing this level of parallelism is best done using agents. However, because their [[CanBlock]] value is false, there is no requirement that agents and threads are one-to-one. This allows implementations the freedom to execute scripts loaded into a worklet on any thread, including one running code from other agents with [[CanBlock]] of false, such as the thread of a similar-origin window agent ("the main thread"). Contrast this with dedicated worker agents, whose true value for [[CanBlock]] effectively requires them to get a dedicated operating system thread.

Worklet event loops are also somewhat special. They are only used for tasks associated with addModule(), tasks wherein the user agent invokes author-defined methods, and microtasks. Thus, even though the event loop processing model specifies that all event loops run continuously, implementations can achieve observably-equivalent results using a simpler strategy, which just invokes author-provided methods and then relies on that process to perform a microtask checkpoint.

11.3.1.2 Creation and termination

To create a worklet global scope for a Worklet worklet:

  1. Let outsideSettings be worklet's relevant settings object.

  2. Let agent be the result of obtaining a worklet agent given outsideSettings. Run the rest of these steps in that agent.

  3. Let realmExecutionContext be the result of creating a new JavaScript realm given agent and the following customizations:

  4. Let workletGlobalScope be the global object of realmExecutionContext's Realm component.

  5. Let insideSettings be the result of setting up a worklet environment settings object given realmExecutionContext and outsideSettings.

  6. Initialize a global object's CSP list given workletGlobalScope. [CSP]

  7. For each moduleURL of worklet's added modules list:

    1. Fetch a worklet script graph given moduleURL, insideSettings, worklet's worklet destination type, what credentials mode?, insideSettings, and worklet's module responses map. Wait until the algorithm asynchronously completes with script.

      This will not actually perform a network request, as it will just reuse responses from worklet's module responses map. The main purpose of this step is to create a new workletGlobalScope-specific module script from the response.

    2. Assert: script is not null, since the fetch succeeded and the source text was successfully parsed when worklet's module responses map was initially populated with moduleURL.

    3. Run a module script given script.

  8. Append workletGlobalScope to outsideSettings's global object's associated Document's worklet global scopes.

  9. Append workletGlobalScope to worklet's global scopes.

  10. Run the responsible event loop specified by insideSettings.

To terminate a worklet global scope given a WorkletGlobalScope workletGlobalScope:

  1. Let eventLoop be workletGlobalScope's relevant agent's event loop.

  2. If there are any tasks queued in eventLoop's task queues, discard them without processing them.

  3. Wait for eventLoop to complete the currently running task.

  4. If the previous step doesn't complete within an implementation-defined period of time, then abort the script currently running in the worklet.

  5. Destroy eventLoop.

  6. Remove workletGlobalScope from the global scopes of the Worklet whose global scopes contains workletGlobalScope.

  7. Remove workletGlobalScope from the worklet global scopes of the Document whose worklet global scopes contains workletGlobalScope.

11.3.1.3 Script settings for worklets

To set up a worklet environment settings object, given a JavaScript execution context executionContext and an environment settings object outsideSettings:

  1. Let origin be a unique opaque origin.

  2. Let inheritedAPIBaseURL be outsideSettings's API base URL.

  3. Let inheritedReferrerPolicy be outsideSettings's referrer policy.

  4. Let inheritedEmbedderPolicy be outsideSettings's embedder policy.

  5. Let realm be the value of executionContext's Realm component.

  6. Let workletGlobalScope be realm's global object.

  7. Let settingsObject be a new environment settings object whose algorithms are defined as follows:

    The realm execution context

    Return executionContext.

    The module map

    Return workletGlobalScope's module map.

    The responsible document

    Not applicable (the responsible event loop is not a window event loop).

    The API URL character encoding

    Return UTF-8.

    The API base URL

    Return inheritedAPIBaseURL.

    Unlike workers or other globals derived from a single resource, worklets have no primary resource; instead, multiple scripts, each with their own URL, are loaded into the global scope via worklet.addModule(). So this API base URL is rather unlike that of other globals. However, so far this doesn't matter, as no APIs available to worklet code make use of the API base URL.

    The origin

    Return origin.

    The referrer policy

    Return inheritedReferrerPolicy.

    The embedder policy

    Return inheritedEmbedderPolicy.

    The cross-origin isolated capability

    Return TODO.

  8. Set settingsObject's id to a new unique opaque string, creation URL to inheritedAPIBaseURL, top-level creation URL to null, top-level origin to outsideSettings's top-level origin, target browsing context to null, and active service worker to null.

  9. Set realm's [[HostDefined]] field to settingsObject.

  10. Return settingsObject.

11.3.2 The Worklet class

Worklet

Support in all current engines.

Firefox76+Safari14.1+Chrome65+
Opera52+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS14.5+Chrome Android65+WebView Android65+Samsung Internet9.0+Opera Android47+

The Worklet class provides the capability to add module scripts into its associated WorkletGlobalScopes. The user agent can then create classes registered on the WorkletGlobalScopes and invoke their methods.

[Exposed=Window, SecureContext]
interface Worklet {
  [NewObject] Promise<undefined> addModule(USVString moduleURL, optional WorkletOptions options = {});
};

dictionary WorkletOptions {
  RequestCredentials credentials = "same-origin";
};

Specifications that create Worklet instances must specify the following for a given instance:

await worklet . addModule(moduleURL[, { credentials }])

Worklet/addModule

Firefox76+SafariNoChrome65+
Opera52+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOSNoChrome Android65+WebView Android65+Samsung Internet9.0+Opera Android47+

Loads and executes the module script given by moduleURL into all of worklet's global scopes. It can also create additional global scopes as part of this process, depending on the worklet type. The returned promise will fulfill once the script has been successfully loaded and run in all global scopes.

The credentials option can be set to a credentials mode to modify the script-fetching process. It defaults to "same-origin".

Any failures in fetching the script or its dependencies will cause the returned promise to be rejected with an "AbortError" DOMException. Any errors in parsing the script or its dependencies will cause the returned promise to be rejected with the exception generated during parsing.

A Worklet has a list of global scopes, which contains instances of the Worklet's worklet global scope type. It is initially empty.

A Worklet has an added modules list, which is a list of URLs, initially empty. Access to this list should be thread-safe.

A Worklet has a module responses map, which is an ordered map from URLs to responses, initially empty. Access to this map should be thread-safe.

The added modules list and module responses map exist to ensure that WorkletGlobalScopes created at different times get equivalent module scripts run in them, based on the same source text. This allows the creation of additional WorkletGlobalScopes to be transparent to the author.

In practice, user agents are not expected to implement these data structures, and the algorithms that consult them, using thread-safe programming techniques. Instead, when addModule() is called, user agents can fetch the module graph on the main thread, and send the fetched source text (i.e., the important data contained in the module responses map) to each thread which has a WorkletGlobalScope.

Then, when a user agent creates a new WorkletGlobalScope for a given Worklet, it can simply send the map of fetched source text and the list of entry points from the main thread to the thread containing the new WorkletGlobalScope.

The addModule(moduleURL, options) method steps are:

  1. Let outsideSettings be the relevant settings object of this.

  2. Parse moduleURL relative to outsideSettings.

  3. If this fails, then return a promise rejected with a "SyntaxError" DOMException.

  4. Let moduleURLRecord be the resulting URL record.

  5. Let promise be a new promise.

  6. Run the following steps in parallel:

    1. If this's global scopes is empty, then:

      1. Create a worklet global scope given this.

      2. Optionally, create additional global scope instances given this, depending on the specific worklet in question and its specification.

      3. Wait for all steps of the creation process(es) — including those taking place within the worklet agents — to complete, before moving on.

    2. Let pendingTasks be this's global scopes's size.

    3. Let addedSuccessfully be false.

    4. For each workletGlobalScope of this's global scopes, queue a global task on the networking task source given workletGlobalScope to perform the following steps:

      1. Fetch a worklet script graph given moduleURLRecord, outsideSettings, this's worklet destination type, options["credentials"], workletGlobalScope's relevant settings object, and this's module responses map. Wait until the algorithm asynchronously completes with script.

        Only the first of these fetches will actually perform a network request; the ones for other WorkletGlobalScopes will reuse reuse responses from this's module responses map.

      2. If script is null, then:

        1. Queue a global task on the networking task source given this's relevant global object to perform the following steps:

          1. If pendingTasks is not −1, then:

            1. Set pendingTasks to −1.

            2. Reject promise with an "AbortError" DOMException.

        2. Abort these steps.

      3. If script's error to rethrow is not null, then:

        1. Queue a global task on the networking task source given this's relevant global object to perform the following steps:

          1. If pendingTasks is not −1, then:

            1. Set pendingTasks to −1.

            2. Reject promise with script's error to rethrow.

        2. Abort these steps.

      4. If addedSuccessfully is false, then:

        1. Append moduleURLRecord to this's added modules list.

        2. Set addedSuccessfully to true.

      5. Run a module script given script.

      6. Queue a global task on the networking task source given this's relevant global object to perform the following steps:

        1. If pendingTasks is not −1, then:

          1. Set pendingTasks to pendingTasks − 1.

          2. If pendingTasks is 0, then resolve promise.

  7. Return promise.

11.3.3 The worklet's lifetime

The lifetime of a Worklet has no special considerations; it is tied to the object it belongs to, such as the Window.

Each Document has a worklet global scopes, which is a set of WorkletGlobalScopes, initially empty.

The lifetime of a WorkletGlobalScope is, at a minimum, tied to the Document whose worklet global scopes contain it. In particular, discarding the Document will terminate the corresponding WorkletGlobalScope and allow it to be garbage-collected.

Additionally, user agents may, at any time, terminate a given WorkletGlobalScope, unless the specification defining the corresponding worklet type says otherwise. For example, they might terminate them if the worklet agent's event loop has no tasks queued, or if the user agent has no pending operations planning to make use of the worklet, or if the user agent detects abnormal operations such as infinite loops or callbacks exceeding imposed time limits.

Finally, specifications for specific worklet types can give more specific details on when to create WorkletGlobalScopes for a given worklet type. For example, they might create them during specific processes that call upon worklet code, as in the example.

12 Web 存储

Web_Storage_API

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

Web_Storage_API/Using_the_Web_Storage_API

12.1 Introduction

This section is non-normative.

This specification introduces two related mechanisms, similar to HTTP session cookies, for storing name-value pairs on the client side. [COOKIES]

The first is designed for scenarios where the user is carrying out a single transaction, but could be carrying out multiple transactions in different windows at the same time.

Cookies don't really handle this case well. For example, a user could be buying plane tickets in two different windows, using the same site. If the site used cookies to keep track of which ticket the user was buying, then as the user clicked from page to page in both windows, the ticket currently being purchased would "leak" from one window to the other, potentially causing the user to buy two tickets for the same flight without really noticing.

To address this, this specification introduces the sessionStorage getter. Sites can add data to the session storage, and it will be accessible to any page from the same site opened in that window.

For example, a page could have a checkbox that the user ticks to indicate that they want insurance:

<label>
 <input type="checkbox" onchange="sessionStorage.insurance = checked ? 'true' : ''">
  I want insurance on this trip.
</label>

A later page could then check, from script, whether the user had checked the checkbox or not:

if (sessionStorage.insurance) { ... }

If the user had multiple windows opened on the site, each one would have its own individual copy of the session storage object.

The second storage mechanism is designed for storage that spans multiple windows, and lasts beyond the current session. In particular, web applications might wish to store megabytes of user data, such as entire user-authored documents or a user's mailbox, on the client side for performance reasons.

Again, cookies do not handle this case well, because they are transmitted with every request.

The localStorage getter is used to access a page's local storage area.

The site at example.com can display a count of how many times the user has loaded its page by putting the following at the bottom of its page:

<p>
  You have viewed this page
  <span id="count">an untold number of</span>
  time(s).
</p>
<script>
  if (!localStorage.pageLoadCount)
    localStorage.pageLoadCount = 0;
  localStorage.pageLoadCount = parseInt(localStorage.pageLoadCount) + 1;
  document.getElementById('count').textContent = localStorage.pageLoadCount;
</script>

Each site has its own separate storage area.

The localStorage getter provides access to shared state. This specification does not define the interaction with other browsing contexts in a multiprocess user agent, and authors are encouraged to assume that there is no locking mechanism. A site could, for instance, try to read the value of a key, increment its value, then write it back out, using the new value as a unique identifier for the session; if the site does this twice in two different browser windows at the same time, it might end up using the same "unique" identifier for both sessions, with potentially disastrous effects.

12.2 API

Storage

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

12.2.1 The Storage interface

[Exposed=Window]
interface Storage {
  readonly attribute unsigned long length;
  DOMString? key(unsigned long index);
  getter DOMString? getItem(DOMString key);
  setter undefined setItem(DOMString key, DOMString value);
  deleter undefined removeItem(DOMString key);
  undefined clear();
};
storage . length

Storage/length

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

Returns the number of key/value pairs.

storage . key ( n )

Storage/key

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

Returns the name of the nth key, or null if n is greater than or equal to the number of key/value pairs.

value = storage . getItem ( key )

Storage/getItem

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
value = storage[key]

Returns the current value associated with the given key, or null if the given key does not exist.

storage . setItem ( key, value )

Storage/setItem

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
storage[key] = value

Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.

Throws a "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.)

Dispatches a storage event on Window objects holding an equivalent Storage object.

storage . removeItem ( key )

Storage/removeItem

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
delete storage[key]

Removes the key/value pair with the given key, if a key/value pair with the given key exists.

Dispatches a storage event on Window objects holding an equivalent Storage object.

storage . clear()

Storage/clear

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android6+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

Removes all key/value pairs, if there are any.

Dispatches a storage event on Window objects holding an equivalent Storage object.

A Storage object has an associated:

map
A storage proxy map.
type
"local" or "session".

To reorder a Storage object storage, reorder storage's map's entries in an implementation-defined manner.

Unfortunate as it is, iteration order is not defined and can change upon most mutations.

To broadcast a Storage object storage, given a key, oldValue, and newValue, run these steps:

  1. Let url be storage's relevant global object's associated Document's URL.

  2. Let remoteStorages be all Storage objects excluding storage whose:

    and, if type is "session", whose relevant settings object's browsing session is storage's relevant settings object's browsing session.

  3. For each remoteStorage of remoteStorages: queue a global task on the DOM manipulation task source given remoteStorage's relevant global object to fire an event named storage at remoteStorage's relevant global object, using StorageEvent, with key initialized to key, oldValue initialized to oldValue, newValue initialized to newValue, url initialized to url, and storageArea initialized to remoteStorage.

    The Document object associated with the resulting task is not necessarily fully active, but events fired on such objects are ignored by the event loop until the Document becomes fully active again.


The length getter steps are to return this's map's size.

The key(n) method steps are:

  1. If n is greater than or equal to this's map's size, then return null.

  2. Let keys be the result of running get the keys on this's map.

  3. Return keys[n].

The supported property names on a Storage object storage are the result of running get the keys on storage's map.

The getItem(key) method steps are:

  1. If this's map[key] does not exist, then return null.

  2. Return this's map[key].

The setItem(key, value) method are:

  1. Let oldValue be null.

  2. Let reorder be true.

  3. If this's map[key] exists:

    1. Set oldValue to this's map[key].

    2. If oldValue is value, then return.

    3. Set reorder to false.

  4. If value cannot be stored, then throw a "QuotaExceededError" DOMException exception.

  5. Set this's map[key] to value.

  6. If reorder is true, then reorder this.

  7. Broadcast this with key, oldValue, and value.

The removeItem(key) method steps are:

  1. If this's map[key] does not exist, then return null.

  2. Set oldValue to this's map[key].

  3. Remove this's map[key].

  4. Reorder this.

  5. Broadcast this with key, oldValue, and null.

The clear() method steps are:

  1. Clear this's map.

  2. Broadcast this with null, null, and null.

12.2.2 The sessionStorage getter

interface mixin WindowSessionStorage {
  readonly attribute Storage sessionStorage;
};
Window includes WindowSessionStorage;
window . sessionStorage

Window/sessionStorage

Support in all current engines.

Firefox2+Safari4+Chrome5+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

Returns the Storage object associated with that window's origin's session storage area.

Throws a "SecurityError" DOMException if the Document's origin is an opaque origin or if the request violates a policy decision (e.g., if the user agent is configured to not allow the page to persist data).

A Document object has an associated session storage holder, which is null or a Storage object. It is initially null.

(This is a tracking vector.) The sessionStorage getter steps are:

  1. If this's associated Document's session storage holder is non-null, then return this's associated Document's session storage holder.

  2. Let map be the result of running obtain a session storage bottle map with this's relevant settings object and "sessionStorage".

  3. If map is failure, then throw a "SecurityError" DOMException.

  4. Let storage be a new Storage object whose map is map.

  5. Set this's associated Document's session storage holder to storage.

  6. Return storage.

While creating a new auxiliary browsing context, the session storage is copied over.

12.2.3 The localStorage getter

interface mixin WindowLocalStorage {
  readonly attribute Storage localStorage;
};
Window includes WindowLocalStorage;
window . localStorage

Window/localStorage

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.5+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS3.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+

Returns the Storage object associated with window's origin's local storage area.

Throws a "SecurityError" DOMException if the Document's origin is an opaque origin or if the request violates a policy decision (e.g., if the user agent is configured to not allow the page to persist data).

A Document object has an associated local storage holder, which is null or a Storage object. It is initially null.

(This is a tracking vector.) The localStorage getter steps are:

  1. If this's associated Document's local storage holder is non-null, then return this's associated Document's local storage holder.

  2. Let map be the result of running obtain a local storage bottle map with this's relevant settings object and "localStorage".

  3. If map is failure, then throw a "SecurityError" DOMException.

  4. Let storage be a new Storage object whose map is map.

  5. Set this's associated Document's local storage holder to storage.

  6. Return storage.

12.2.4 The StorageEvent interface

StorageEvent

Support in all current engines.

Firefox13+Safari4+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android14+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
[Exposed=Window]
interface StorageEvent : Event {
  constructor(DOMString type, optional StorageEventInit eventInitDict = {});

  readonly attribute DOMString? key;
  readonly attribute DOMString? oldValue;
  readonly attribute DOMString? newValue;
  readonly attribute USVString url;
  readonly attribute Storage? storageArea;

  undefined initStorageEvent(DOMString type, optional boolean bubbles = false, optional boolean cancelable = false, optional DOMString? key = null, optional DOMString? oldValue = null, optional DOMString? newValue = null, optional USVString url = "", optional Storage? storageArea = null);
};

dictionary StorageEventInit : EventInit {
  DOMString? key = null;
  DOMString? oldValue = null;
  DOMString? newValue = null;
  USVString url = "";
  Storage? storageArea = null;
};
event . key

Returns the key of the storage item being changed.

event . oldValue

Returns the old value of the key of the storage item whose value is being changed.

event . newValue

Returns the new value of the key of the storage item whose value is being changed.

event . url

Returns the URL of the document whose storage item changed.

event . storageArea

Returns the Storage object that was affected.

The key, oldValue, newValue, url, and storageArea attributes must return the values they were initialized to.

StorageEvent/initStorageEvent

Support in all current engines.

Firefox13+Safari4+Chrome4+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android14+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+

The initStorageEvent() method must initialize the event in a manner analogous to the similarly-named initEvent() method. [DOM]

12.3 隐私

12.3.1 User tracking

A third-party advertiser (or any entity capable of getting content distributed to multiple sites) could use a unique identifier stored in its local storage area to track a user across multiple sessions, building a profile of the user's interests to allow for highly targeted advertising. In conjunction with a site that is aware of the user's real identity (for example an e-commerce site that requires authenticated credentials), this could allow oppressive groups to target individuals with greater accuracy than in a world with purely anonymous web usage.

There are a number of techniques that can be used to mitigate the risk of user tracking:

Blocking third-party storage

User agents may restrict access to the localStorage objects to scripts originating at the domain of the active document of the top-level browsing context, for instance denying access to the API for pages from other domains running in iframes.

Expiring stored data

User agents may, possibly in a manner configured by the user, automatically delete stored data after a period of time.

For example, a user agent could be configured to treat third-party local storage areas as session-only storage, deleting the data once the user had closed all the browsing contexts that could access it.

This can restrict the ability of a site to track a user, as the site would then only be able to track the user across multiple sessions when they authenticate with the site itself (e.g. by making a purchase or logging in to a service).

However, this also reduces the usefulness of the API as a long-term storage mechanism. It can also put the user's data at risk, if the user does not fully understand the implications of data expiration.

Treating persistent storage as cookies

If users attempt to protect their privacy by clearing cookies without also clearing data stored in the local storage area, sites can defeat those attempts by using the two features as redundant backup for each other. User agents should present the interfaces for clearing these in a way that helps users to understand this possibility and enables them to delete data in all persistent storage features simultaneously. [COOKIES]

Site-specific safelisting of access to local storage areas

User agents may allow sites to access session storage areas in an unrestricted manner, but require the user to authorize access to local storage areas.

Origin-tracking of stored data

User agents may record the origins of sites that contained content from third-party origins that caused data to be stored.

If this information is then used to present the view of data currently in persistent storage, it would allow the user to make informed decisions about which parts of the persistent storage to prune. Combined with a blocklist ("delete this data and prevent this domain from ever storing data again"), the user can restrict the use of persistent storage to sites that they trust.

Shared blocklists

User agents may allow users to share their persistent storage domain blocklists.

This would allow communities to act together to protect their privacy.

While these suggestions prevent trivial use of this API for user tracking, they do not block it altogether. Within a single domain, a site can continue to track the user during a session, and can then pass all this information to the third party along with any identifying information (names, credit card numbers, addresses) obtained by the site. If a third party cooperates with multiple sites to obtain such information, a profile can still be created.

However, user tracking is to some extent possible even with no cooperation from the user agent whatsoever, for instance by using session identifiers in URLs, a technique already commonly used for innocuous purposes but easily repurposed for user tracking (even retroactively). This information can then be shared with other sites, using visitors' IP addresses and other user-specific data (e.g. user-agent headers and configuration settings) to combine separate sessions into coherent user profiles.

12.3.2 Sensitivity of data

User agents should treat persistently stored data as potentially sensitive; it's quite possible for emails, calendar appointments, health records, or other confidential documents to be stored in this mechanism.

To this end, user agents should ensure that when deleting data, it is promptly deleted from the underlying storage.

12.4 安全

12.4.1 DNS 欺骗攻击

由于可能受到 DNS 欺骗攻击,人们不能保证声称在某个域中的主机确实来自该域。 为缓解这种情况网页可以使用 TLS。 使用 TLS 的页面可以确保只有用户,代表用户的软件以及使用 TLS 的其他页面 (具有标识为来自同一个域的证书)可以访问其存储区域。

12.4.2 Cross-directory attacks

Different authors sharing one host name, for example users hosting content on the now defunct geocities.com, all share one local storage object. There is no feature to restrict the access by pathname. Authors on shared hosts are therefore urged to avoid using these features, as it would be trivial for other authors to read the data and overwrite it.

Even if a path-restriction feature was made available, the usual DOM scripting security model would make it trivial to bypass this protection and access the data from any path.

12.4.3 Implementation risks

The two primary risks when implementing these persistent storage features are letting hostile sites read information from other domains, and letting hostile sites write information that is then read from other domains.

Letting third-party sites read data that is not supposed to be read from their domain causes information leakage, For example, a user's shopping wishlist on one domain could be used by another domain for targeted advertising; or a user's work-in-progress confidential documents stored by a word-processing site could be examined by the site of a competing company.

Letting third-party sites write data to the persistent storage of other domains can result in information spoofing, which is equally dangerous. For example, a hostile site could add items to a user's wishlist; or a hostile site could set a user's session identifier to a known ID that the hostile site can then use to track the user's actions on the victim site.

Thus, strictly following the origin model described in this specification is important for user security.

13 HTML 语法

本章只描述有 HTML MIME type 标注的资源的语法规则。XML 资源的规则在下一章 " XML 语法" 中讨论。

13.1 Writing HTML documents

This section only applies to documents, authoring tools, and markup generators. In particular, it does not apply to conformance checkers; conformance checkers must use the requirements given in the next section ("parsing HTML documents").

Documents must consist of the following parts, in the given order:

  1. Optionally, a single U+FEFF BYTE ORDER MARK (BOM) character.
  2. Any number of comments and ASCII whitespace.
  3. A DOCTYPE.
  4. Any number of comments and ASCII whitespace.
  5. The document element, in the form of an html element.
  6. Any number of comments and ASCII whitespace.

The various types of content mentioned above are described in the next few sections.

In addition, there are some restrictions on how character encoding declarations are to be serialized, as discussed in the section on that topic.

ASCII whitespace before the html element, at the start of the html element and before the head element, will be dropped when the document is parsed; ASCII whitespace after the html element will be parsed as if it were at the end of the body element. Thus, ASCII whitespace around the document element does not round-trip.

It is suggested that newlines be inserted after the DOCTYPE, after any comments that are before the document element, after the html element's start tag (if it is not omitted), and after any comments that are inside the html element but before the head element.

Many strings in the HTML syntax (e.g. the names of elements and their attributes) are case-insensitive, but only for ASCII upper alphas and ASCII lower alphas. For convenience, in this section this is just referred to as "case-insensitive".

13.1.1 The DOCTYPE

A DOCTYPE is a required preamble.

DOCTYPEs are required for legacy reasons. When omitted, browsers tend to use a different rendering mode that is incompatible with some specifications. Including the DOCTYPE in a document ensures that the browser makes a best-effort attempt at following the relevant specifications.

A DOCTYPE must consist of the following components, in this order:

  1. A string that is an ASCII case-insensitive match for the string "<!DOCTYPE".
  2. One or more ASCII whitespace.
  3. A string that is an ASCII case-insensitive match for the string "html".
  4. Optionally, a DOCTYPE legacy string.
  5. Zero or more ASCII whitespace.
  6. A U+003E GREATER-THAN SIGN character (>).

In other words, <!DOCTYPE html>, case-insensitively.


For the purposes of HTML generators that cannot output HTML markup with the short DOCTYPE "<!DOCTYPE html>", a DOCTYPE legacy string may be inserted into the DOCTYPE (in the position defined above). This string must consist of:

  1. One or more ASCII whitespace.
  2. A string that is an ASCII case-insensitive match for the string "SYSTEM".
  3. One or more ASCII whitespace.
  4. A U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (the quote mark).
  5. The literal string "about:legacy-compat".
  6. A matching U+0022 QUOTATION MARK or U+0027 APOSTROPHE character (i.e. the same character as in the earlier step labeled quote mark).

In other words, <!DOCTYPE html SYSTEM "about:legacy-compat"> or <!DOCTYPE html SYSTEM 'about:legacy-compat'>, case-insensitively except for the part in single or double quotes.

The DOCTYPE legacy string should not be used unless the document is generated from a system that cannot output the shorter string.

13.1.2 Elements

There are six different kinds of elements: void elements, the template element, raw text elements, escapable raw text elements, foreign elements, and normal elements.

Void elements
area, base, br, col, embed, hr, img, input, link, meta, param, source, track, wbr
The template element
template
Raw text elements
script, style
Escapable raw text elements
textarea, title
Foreign elements
Elements from the MathML namespace and the SVG namespace.
Normal elements
All other allowed HTML elements are normal elements.

Tags are used to delimit the start and end of elements in the markup. Raw text, escapable raw text, and normal elements have a start tag to indicate where they begin, and an end tag to indicate where they end. The start and end tags of certain normal elements can be omitted, as described below in the section on optional tags. Those that cannot be omitted must not be omitted. Void elements only have a start tag; end tags must not be specified for void elements. Foreign elements must either have a start tag and an end tag, or a start tag that is marked as self-closing, in which case they must not have an end tag.

The contents of the element must be placed between just after the start tag (which might be implied, in certain cases) and just before the end tag (which again, might be implied in certain cases). The exact allowed contents of each individual element depend on the content model of that element, as described earlier in this specification. Elements must not contain content that their content model disallows. In addition to the restrictions placed on the contents by those content models, however, the five types of elements have additional syntactic requirements.

Void elements can't have any contents (since there's no end tag, no content can be put between the start tag and the end tag).

The template element can have template contents, but such template contents are not children of the template element itself. Instead, they are stored in a DocumentFragment associated with a different Document — without a browsing context — so as to avoid the template contents interfering with the main Document. The markup for the template contents of a template element is placed just after the template element's start tag and just before template element's end tag (as with other elements), and may consist of any text, character references, elements, and comments, but the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand.

Raw text elements can have text, though it has restrictions described below.

Escapable raw text elements can have text and character references, but the text must not contain an ambiguous ampersand. There are also further restrictions described below.

Foreign elements whose start tag is marked as self-closing can't have any contents (since, again, as there's no end tag, no content can be put between the start tag and the end tag). Foreign elements whose start tag is not marked as self-closing can have text, character references, CDATA sections, other elements, and comments, but the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand.

The HTML syntax does not support namespace declarations, even in foreign elements.

For instance, consider the following HTML fragment:

<p>
 <svg>
  <metadata>
   <!-- this is invalid -->
   <cdr:license xmlns:cdr="https://www.example.com/cdr/metadata" name="MIT"/>
  </metadata>
 </svg>
</p>

The innermost element, cdr:license, is actually in the SVG namespace, as the "xmlns:cdr" attribute has no effect (unlike in XML). In fact, as the comment in the fragment above says, the fragment is actually non-conforming. This is because SVG 2 does not define any elements called "cdr:license" in the SVG namespace.

Normal elements can have text, character references, other elements, and comments, but the text must not contain the character U+003C LESS-THAN SIGN (<) or an ambiguous ampersand. Some normal elements also have yet more restrictions on what content they are allowed to hold, beyond the restrictions imposed by the content model and those described in this paragraph. Those restrictions are described below.

Tags contain a tag name, giving the element's name. HTML elements all have names that only use ASCII alphanumerics. In the HTML syntax, tag names, even those for foreign elements, may be written with any mix of lower- and uppercase letters that, when converted to all-lowercase, matches the element's tag name; tag names are case-insensitive.

13.1.2.1 Start tags

Start tags must have the following format:

  1. The first character of a start tag must be a U+003C LESS-THAN SIGN character (<).
  2. The next few characters of a start tag must be the element's tag name.
  3. If there are to be any attributes in the next step, there must first be one or more ASCII whitespace.
  4. Then, the start tag may have a number of attributes, the syntax for which is described below. Attributes must be separated from each other by one or more ASCII whitespace.
  5. After the attributes, or after the tag name if there are no attributes, there may be one or more ASCII whitespace. (Some attributes are required to be followed by a space. See the attributes section below.)
  6. Then, if the element is one of the void elements, or if the element is a foreign element, then there may be a single U+002F SOLIDUS character (/). This character has no effect on void elements, but on foreign elements it marks the start tag as self-closing.
  7. Finally, start tags must be closed by a U+003E GREATER-THAN SIGN character (>).
13.1.2.2 End tags

End tags must have the following format:

  1. The first character of an end tag must be a U+003C LESS-THAN SIGN character (<).
  2. The second character of an end tag must be a U+002F SOLIDUS character (/).
  3. The next few characters of an end tag must be the element's tag name.
  4. After the tag name, there may be one or more ASCII whitespace.
  5. Finally, end tags must be closed by a U+003E GREATER-THAN SIGN character (>).
13.1.2.3 Attributes

Attributes for an element are expressed inside the element's start tag.

Attributes have a name and a value. Attribute names must consist of one or more characters other than controls, U+0020 SPACE, U+0022 ("), U+0027 ('), U+003E (>), U+002F (/), U+003D (=), and noncharacters. In the HTML syntax, attribute names, even those for foreign elements, may be written with any mix of ASCII lower and ASCII upper alphas.

Attribute values are a mixture of text and character references, except with the additional restriction that the text cannot contain an ambiguous ampersand.

Attributes can be specified in four different ways:

Empty attribute syntax

Just the attribute name. The value is implicitly the empty string.

In the following example, the disabled attribute is given with the empty attribute syntax:

<input disabled>

If an attribute using the empty attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two.

Unquoted attribute value syntax

The attribute name, followed by zero or more ASCII whitespace, followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace, followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal ASCII whitespace, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.

In the following example, the value attribute is given with the unquoted attribute value syntax:

<input value=yes>

If an attribute using the unquoted attribute syntax is to be followed by another attribute or by the optional U+002F SOLIDUS character (/) allowed in step 6 of the start tag syntax above, then there must be ASCII whitespace separating the two.

Single-quoted attribute value syntax

The attribute name, followed by zero or more ASCII whitespace, followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace, followed by a single U+0027 APOSTROPHE character ('), followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal U+0027 APOSTROPHE characters ('), and finally followed by a second single U+0027 APOSTROPHE character (').

In the following example, the type attribute is given with the single-quoted attribute value syntax:

<input type='checkbox'>

If an attribute using the single-quoted attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two.

Double-quoted attribute value syntax

The attribute name, followed by zero or more ASCII whitespace, followed by a single U+003D EQUALS SIGN character, followed by zero or more ASCII whitespace, followed by a single U+0022 QUOTATION MARK character ("), followed by the attribute value, which, in addition to the requirements given above for attribute values, must not contain any literal U+0022 QUOTATION MARK characters ("), and finally followed by a second single U+0022 QUOTATION MARK character (").

In the following example, the name attribute is given with the double-quoted attribute value syntax:

<input name="be evil">

If an attribute using the double-quoted attribute syntax is to be followed by another attribute, then there must be ASCII whitespace separating the two.

There must never be two or more attributes on the same start tag whose names are an ASCII case-insensitive match for each other.


When a foreign element has one of the namespaced attributes given by the local name and namespace of the first and second cells of a row from the following table, it must be written using the name given by the third cell from the same row.

Local name Namespace Attribute name
actuate XLink namespace xlink:actuate
arcrole XLink namespace xlink:arcrole
href XLink namespace xlink:href
role XLink namespace xlink:role
show XLink namespace xlink:show
title XLink namespace xlink:title
type XLink namespace xlink:type
lang XML namespace xml:lang
space XML namespace xml:space
xmlns XMLNS namespace xmlns
xlink XMLNS namespace xmlns:xlink

No other namespaced attribute can be expressed in the HTML syntax.

Whether the attributes in the table above are conforming or not is defined by other specifications (e.g. SVG 2 and MathML); this section only describes the syntax rules if the attributes are serialized using the HTML syntax.

13.1.2.4 Optional tags

Certain tags can be omitted.

Omitting an element's start tag in the situations described below does not mean the element is not present; it is implied, but it is still there. For example, an HTML document always has a root html element, even if the string <html> doesn't appear anywhere in the markup.

An html element's start tag may be omitted if the first thing inside the html element is not a comment.

For example, in the following case it's ok to remove the "<html>" tag:

<!DOCTYPE HTML>
<html>
  <head>
    <title>Hello</title>
  </head>
  <body>
    <p>Welcome to this example.</p>
  </body>
</html>

Doing so would make the document look like this:

<!DOCTYPE HTML>

  <head>
    <title>Hello</title>
  </head>
  <body>
    <p>Welcome to this example.</p>
  </body>
</html>

This has the exact same DOM. In particular, note that whitespace around the document element is ignored by the parser. The following example would also have the exact same DOM:

<!DOCTYPE HTML><head>
    <title>Hello</title>
  </head>
  <body>
    <p>Welcome to this example.</p>
  </body>
</html>

However, in the following example, removing the start tag moves the comment to before the html element:

<!DOCTYPE HTML>
<html>
  <!-- where is this comment in the DOM? -->
  <head>
    <title>Hello</title>
  </head>
  <body>
    <p>Welcome to this example.</p>
  </body>
</html>

With the tag removed, the document actually turns into the same as this:

<!DOCTYPE HTML>
<!-- where is this comment in the DOM? -->
<html>
  <head>
    <title>Hello</title>
  </head>
  <body>
    <p>Welcome to this example.</p>
  </body>
</html>

This is why the tag can only be removed if it is not followed by a comment: removing the tag when there is a comment there changes the document's resulting parse tree. Of course, if the position of the comment does not matter, then the tag can be omitted, as if the comment had been moved to before the start tag in the first place.

An html element's end tag may be omitted if the html element is not immediately followed by a comment.

A head element's start tag may be omitted if the element is empty, or if the first thing inside the head element is an element.

A head element's end tag may be omitted if the head element is not immediately followed by ASCII whitespace or a comment.

A body element's start tag may be omitted if the element is empty, or if the first thing inside the body element is not ASCII whitespace or a comment, except if the first thing inside the body element is a meta, link, script, style, or template element.

A body element's end tag may be omitted if the body element is not immediately followed by a comment.

Note that in the example above, the head element start and end tags, and the body element start tag, can't be omitted, because they are surrounded by whitespace:

<!DOCTYPE HTML>
<html>
  <head>
    <title>Hello</title>
  </head>
  <body>
    <p>Welcome to this example.</p>
  </body>
</html>

(The body and html element end tags could be omitted without trouble; any spaces after those get parsed into the body element anyway.)

Usually, however, whitespace isn't an issue. If we first remove the whitespace we don't care about:

<!DOCTYPE HTML><html><head><title>Hello</title></head><body><p>Welcome to this example.</p></body></html>

Then we can omit a number of tags without affecting the DOM:

<!DOCTYPE HTML><title>Hello</title><p>Welcome to this example.</p>

At that point, we can also add some whitespace back:

<!DOCTYPE HTML>
<title>Hello</title>
<p>Welcome to this example.</p>

This would be equivalent to this document, with the omitted tags shown in their parser-implied positions; the only whitespace text node that results from this is the newline at the end of the head element:

<!DOCTYPE HTML>
<html><head><title>Hello</title>
</head><body><p>Welcome to this example.</p></body></html>

An li element's end tag may be omitted if the li element is immediately followed by another li element or if there is no more content in the parent element.

A dt element's end tag may be omitted if the dt element is immediately followed by another dt element or a dd element.

A dd element's end tag may be omitted if the dd element is immediately followed by another dd element or a dt element, or if there is no more content in the parent element.

A p element's end tag may be omitted if the p element is immediately followed by an address, article, aside, blockquote, details, div, dl, fieldset, figcaption, figure, footer, form, h1, h2, h3, h4, h5, h6, header, hgroup, hr, main, menu, nav, ol, p, pre, section, table, or ul element, or if there is no more content in the parent element and the parent element is an HTML element that is not an a, audio, del, ins, map, noscript, or video element, or an autonomous custom element.

We can thus simplify the earlier example further:

<!DOCTYPE HTML><title>Hello</title><p>Welcome to this example.

An rt element's end tag may be omitted if the rt element is immediately followed by an rt or rp element, or if there is no more content in the parent element.

An rp element's end tag may be omitted if the rp element is immediately followed by an rt or rp element, or if there is no more content in the parent element.

An optgroup element's end tag may be omitted if the optgroup element is immediately followed by another optgroup element, or if there is no more content in the parent element.

An option element's end tag may be omitted if the option element is immediately followed by another option element, or if it is immediately followed by an optgroup element, or if there is no more content in the parent element.

A colgroup element's start tag may be omitted if the first thing inside the colgroup element is a col element, and if the element is not immediately preceded by another colgroup element whose end tag has been omitted. (It can't be omitted if the element is empty.)

A colgroup element's end tag may be omitted if the colgroup element is not immediately followed by ASCII whitespace or a comment.

A caption element's end tag may be omitted if the caption element is not immediately followed by ASCII whitespace or a comment.

A thead element's end tag may be omitted if the thead element is immediately followed by a tbody or tfoot element.

A tbody element's start tag may be omitted if the first thing inside the tbody element is a tr element, and if the element is not immediately preceded by a tbody, thead, or tfoot element whose end tag has been omitted. (It can't be omitted if the element is empty.)

A tbody element's end tag may be omitted if the tbody element is immediately followed by a tbody or tfoot element, or if there is no more content in the parent element.

A tfoot element's end tag may be omitted if there is no more content in the parent element.

A tr element's end tag may be omitted if the tr element is immediately followed by another tr element, or if there is no more content in the parent element.

A td element's end tag may be omitted if the td element is immediately followed by a td or th element, or if there is no more content in the parent element.

A th element's end tag may be omitted if the th element is immediately followed by a td or th element, or if there is no more content in the parent element.

The ability to omit all these table-related tags makes table markup much terser.

Take this example:

<table>
 <caption>37547 TEE Electric Powered Rail Car Train Functions (Abbreviated)</caption>
 <colgroup><col><col><col></colgroup>
 <thead>
  <tr>
   <th>Function</th>
   <th>Control Unit</th>
   <th>Central Station</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>Headlights</td>
   <td>✔</td>
   <td>✔</td>
  </tr>
  <tr>
   <td>Interior Lights</td>
   <td>✔</td>
   <td>✔</td>
  </tr>
  <tr>
   <td>Electric locomotive operating sounds</td>
   <td>✔</td>
   <td>✔</td>
  </tr>
  <tr>
   <td>Engineer's cab lighting</td>
   <td></td>
   <td>✔</td>
  </tr>
  <tr>
   <td>Station Announcements - Swiss</td>
   <td></td>
   <td>✔</td>
  </tr>
 </tbody>
</table>

The exact same table, modulo some whitespace differences, could be marked up as follows:

<table>
 <caption>37547 TEE Electric Powered Rail Car Train Functions (Abbreviated)
 <colgroup><col><col><col>
 <thead>
  <tr>
   <th>Function
   <th>Control Unit
   <th>Central Station
 <tbody>
  <tr>
   <td>Headlights
   <td>✔
   <td>✔
  <tr>
   <td>Interior Lights
   <td>✔
   <td>✔
  <tr>
   <td>Electric locomotive operating sounds
   <td>✔
   <td>✔
  <tr>
   <td>Engineer's cab lighting
   <td>
   <td>✔
  <tr>
   <td>Station Announcements - Swiss
   <td>
   <td>✔
</table>

Since the cells take up much less room this way, this can be made even terser by having each row on one line:

<table>
 <caption>37547 TEE Electric Powered Rail Car Train Functions (Abbreviated)
 <colgroup><col><col><col>
 <thead>
  <tr> <th>Function                              <th>Control Unit     <th>Central Station
 <tbody>
  <tr> <td>Headlights                            <td>✔                <td>✔
  <tr> <td>Interior Lights                       <td>✔                <td>✔
  <tr> <td>Electric locomotive operating sounds  <td>✔                <td>✔
  <tr> <td>Engineer's cab lighting               <td>                 <td>✔
  <tr> <td>Station Announcements - Swiss         <td>                 <td>✔
</table>

The only differences between these tables, at the DOM level, is with the precise position of the (in any case semantically-neutral) whitespace.

However, a start tag must never be omitted if it has any attributes.

Returning to the earlier example with all the whitespace removed and then all the optional tags removed:

<!DOCTYPE HTML><title>Hello</title><p>Welcome to this example.

If the body element in this example had to have a class attribute and the html element had to have a lang attribute, the markup would have to become:

<!DOCTYPE HTML><html lang="en"><title>Hello</title><body class="demo"><p>Welcome to this example.

This section assumes that the document is conforming, in particular, that there are no content model violations. Omitting tags in the fashion described in this section in a document that does not conform to the content models described in this specification is likely to result in unexpected DOM differences (this is, in part, what the content models are designed to avoid).

13.1.2.5 内容模型限制

由于历史原因,某些元素在其内容模型之外还有额外的限制。

table 元素不得包含 tr 元素,虽然根据本规范描述的内容模型 这些元素技术上是允许在 table 里的。 (如果代码中在 table 里放一个 tr 元素, 实际上暗示着在它前面加一个 tbody 开始标签。)

单个 newline 可以紧挨着放在 pretextarea 元素的 开始标签 后面。 这不影响元素的处理。如果元素的内容本身以 换行 开头, 就 必须 包含这个可选的 换行 (否则内容中的前导换行符将被视为可选换行符并被忽略)。

下面两个 pre 块是等价的:

<pre>Hello</pre>
<pre>
Hello</pre>
13.1.2.6 对原始文本和可转义的原始文本元素的内容的限制

原始文本可转义的原始文本元素 中的内容不得出现任何 "</" (U+003C LESS-THAN SIGN, U+002F SOLIDUS) 加那个元素名的大小写不敏感匹配, 再加一个 U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>) 或 U+002F SOLIDUS (/) 字符。

13.1.3 文本

在元素内允许 文本,属性值和注释。 如其他部分所述,基于放置文本的位置,对文本中的内容和不允许的内容有额外的限制。

13.1.3.1 换行

HTML 中的 换行 可以表示为 U+000D CARRIAGE RETURN (CR) 字符, U+000A LINE FEED (LF) 字符,或一对 U+000D CARRIAGE RETURN (CR), U+000A LINE FEED (LF) 字符(按这个顺序)。

在允许 字符引用 的地方,一个 U+000A LINE FEED (LF) 字符(但U+000D CARRIAGE RETURN (CR) 字符不行) 的字符引用也表示一个 换行

13.1.4 Character references

In certain cases described in other sections, text may be mixed with character references. These can be used to escape characters that couldn't otherwise legally be included in text.

Character references must start with a U+0026 AMPERSAND character (&). Following this, there are three possible kinds of character references:

Named character references
The ampersand must be followed by one of the names given in the named character references section, using the same case. The name must be one that is terminated by a U+003B SEMICOLON character (;).
Decimal numeric character reference
The ampersand must be followed by a U+0023 NUMBER SIGN character (#), followed by one or more ASCII digits, representing a base-ten integer that corresponds to a code point that is allowed according to the definition below. The digits must then be followed by a U+003B SEMICOLON character (;).
Hexadecimal numeric character reference
The ampersand must be followed by a U+0023 NUMBER SIGN character (#), which must be followed by either a U+0078 LATIN SMALL LETTER X character (x) or a U+0058 LATIN CAPITAL LETTER X character (X), which must then be followed by one or more ASCII hex digits, representing a hexadecimal integer that corresponds to a code point that is allowed according to the definition below. The digits must then be followed by a U+003B SEMICOLON character (;).

The numeric character reference forms described above are allowed to reference any code point excluding U+000D CR, noncharacters, and controls other than ASCII whitespace.

An ambiguous ampersand is a U+0026 AMPERSAND character (&) that is followed by one or more ASCII alphanumerics, followed by a U+003B SEMICOLON character (;), where these characters do not match any of the names given in the named character references section.

13.1.5 CDATA 部分

CDATA 部分 必须按顺序包含以下部分:

  1. 字符串 "<![CDATA["。
  2. 可选地,不包含字符串 "]]>" 的 文本
  3. 字符串 "]]>"。

CDATA 部分职能用于外部内容(MathML 或 SVG)。在这个例子中, CDATA 部分用于转义 MathML ms 元素的内容:

<p>You can add a string to a number, but this stringifies the number:</p>
<math>
 <ms><![CDATA[x<y]]></ms>
 <mo>+</mo>
 <mn>3</mn>
 <mo>=</mo>
 <ms><![CDATA[x<y3]]></ms>
</math>

13.1.6 注释

注释 必须有如下格式:

  1. 字符串 "<!--"。
  2. 可选的 文本,额外的限制是该文本不得以字符串 ">" 或 "->" 起始。 也不的包含 "<!--", "-->" 或 "--!>",也不得以字符串 "<!-" 结尾。
  3. 字符串 "-->"。

text 允许以字符串 "<!" 结束,比如 <!--My favorite operators are > and <!-->

13.2 Parsing HTML documents

This section only applies to user agents, data mining tools, and conformance checkers.

The rules for parsing XML documents into DOM trees are covered by the next section, entitled "The XML syntax".

User agents must use the parsing rules described in this section to generate the DOM trees from text/html resources. Together, these rules define what is referred to as the HTML parser.

While the HTML syntax described in this specification bears a close resemblance to SGML and XML, it is a separate language with its own parsing rules.

Some earlier versions of HTML (in particular from HTML2 to HTML4) were based on SGML and used SGML parsing rules. However, few (if any) web browsers ever implemented true SGML parsing for HTML documents; the only user agents to strictly handle HTML as an SGML application have historically been validators. The resulting confusion — with validators claiming documents to have one representation while widely deployed web browsers interoperably implemented a different representation — has wasted decades of productivity. This version of HTML thus returns to a non-SGML basis.

Authors interested in using SGML tools in their authoring pipeline are encouraged to use XML tools and the XML serialization of HTML.

For the purposes of conformance checkers, if a resource is determined to be in the HTML syntax, then it is an HTML document.

As stated in the terminology section, references to element types that do not explicitly specify a namespace always refer to elements in the HTML namespace. For example, if the spec talks about "a menu element", then that is an element with the local name "menu", the namespace "http://www.w3.org/1999/xhtml", and the interface HTMLMenuElement. Where possible, references to such elements are hyperlinked to their definition.

13.2.1 Overview of the parsing model

The input to the HTML parsing process consists of a stream of code points, which is passed through a tokenization stage followed by a tree construction stage. The output is a Document object.

Implementations that do not support scripting do not have to actually create a DOM Document object, but the DOM tree in such cases is still used as the model for the rest of the specification.

In the common case, the data handled by the tokenization stage comes from the network, but it can also come from script running in the user agent, e.g. using the document.write() API.

There is only one set of states for the tokenizer stage and the tree construction stage, but the tree construction stage is reentrant, meaning that while the tree construction stage is handling one token, the tokenizer might be resumed, causing further tokens to be emitted and processed before the first token's processing is complete.

In the following example, the tree construction stage will be called upon to handle a "p" start tag token while handling the "script" end tag token:

...
<script>
 document.write('<p>');
</script>
...

To handle these cases, parsers have a script nesting level, which must be initially set to zero, and a parser pause flag, which must be initially set to false.

13.2.2 Parse errors

This specification defines the parsing rules for HTML documents, whether they are syntactically correct or not. Certain points in the parsing algorithm are said to be parse errors. The error handling for parse errors is well-defined (that's the processing rules described throughout this specification), but user agents, while parsing an HTML document, may abort the parser at the first parse error that they encounter for which they do not wish to apply the rules described in this specification.

Conformance checkers must report at least one parse error condition to the user if one or more parse error conditions exist in the document and must not report parse error conditions if none exist in the document. Conformance checkers may report more than one parse error condition if more than one parse error condition exists in the document.

Parse errors are only errors with the syntax of HTML. In addition to checking for parse errors, conformance checkers will also verify that the document obeys all the other conformance requirements described in this specification.

Some parse errors have dedicated codes outlined in the table below that should be used by conformance checkers in reports.

Error descriptions in the table below are non-normative.

Code Description
abrupt-closing-of-empty-comment

This error occurs if the parser encounters an empty comment that is abruptly closed by a U+003E (>) code point (i.e., <!--> or <!--->). The parser behaves as if the comment is closed correctly.

abrupt-doctype-public-identifier

This error occurs if the parser encounters a U+003E (>) code point in the DOCTYPE public identifier (e.g., <!DOCTYPE html PUBLIC "foo>). In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode.

abrupt-doctype-system-identifier

This error occurs if the parser encounters a U+003E (>) code point in the DOCTYPE system identifier (e.g., <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "foo>). In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode.

absence-of-digits-in-numeric-character-reference

This error occurs if the parser encounters a numeric character reference that doesn't contain any digits (e.g., &#qux;). In this case the parser doesn't resolve the character reference.

cdata-in-html-content

This error occurs if the parser encounters a CDATA section outside of foreign content (SVG or MathML). The parser treats such CDATA sections (including leading "[CDATA[" and trailing "]]" strings) as comments.

character-reference-outside-unicode-range

This error occurs if the parser encounters a numeric character reference that references a code point that is greater than the valid Unicode range. The parser resolves such a character reference to a U+FFFD REPLACEMENT CHARACTER.

control-character-in-input-stream

This error occurs if the input stream contains a control code point that is not ASCII whitespace or U+0000 NULL. Such code points are parsed as-is and usually, where parsing rules don't apply any additional restrictions, make their way into the DOM.

control-character-reference

This error occurs if the parser encounters a numeric character reference that references a control code point that is not ASCII whitespace or is a U+000D CARRIAGE RETURN. The parser resolves such character references as-is except C1 control references that are replaced according to the numeric character reference end state.

end-tag-with-attributes

This error occurs if the parser encounters an end tag with attributes. Attributes in end tags are completely ignored and do not make their way into the DOM.

duplicate-attribute

This error occurs if the parser encounters an attribute in a tag that already has an attribute with the same name. The parser ignores all such duplicate occurrences of the attribute.

end-tag-with-trailing-solidus

This error occurs if the parser encounters an end tag that has a U+002F (/) code point right before the closing U+003E (>) code point (e.g., </div/>). Such a tag is treated as a regular end tag.

eof-before-tag-name

This error occurs if the parser encounters the end of the input stream where a tag name is expected. In this case the parser treats the beginning of a start tag (i.e., <) or an end tag (i.e., </) as text content.

eof-in-cdata

This error occurs if the parser encounters the end of the input stream in a CDATA section. The parser treats such CDATA sections as if they are closed immediately before the end of the input stream.

eof-in-comment

This error occurs if the parser encounters the end of the input stream in a comment. The parser treats such comments as if they are closed immediately before the end of the input stream.

eof-in-doctype

This error occurs if the parser encounters the end of the input stream in a DOCTYPE. In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode.

eof-in-script-html-comment-like-text

This error occurs if the parser encounters the end of the input stream in text that resembles an HTML comment inside script element content (e.g., <script><!-- foo).

Syntactic structures that resemble HTML comments in script elements are parsed as text content. They can be a part of a scripting language-specific syntactic structure or be treated as an HTML-like comment, if the scripting language supports them (e.g., parsing rules for HTML-like comments can be found in Annex B of the JavaScript specification). The common reason for this error is a violation of the restrictions for contents of script elements. [JAVASCRIPT]

eof-in-tag

This error occurs if the parser encounters the end of the input stream in a start tag or an end tag (e.g., <div id=). Such a tag is completely ignored.

incorrectly-closed-comment

This error occurs if the parser encounters a comment that is closed by the "--!>" code point sequence. The parser treats such comments as if they are correctly closed by the "-->" code point sequence.

incorrectly-opened-comment

This error occurs if the parser encounters the "<!" code point sequence that is not immidiately followed by two U+002D (-) code points and that is not the start of a DOCTYPE or a CDATA section. All content that follows the "<!" code point sequence up to a U+003E (>) code point (if present) or to the end of the input stream is treated as a comment.

One possible cause of this error is using an XML markup declaration (e.g., <!ELEMENT br EMPTY>) in HTML.

invalid-character-sequence-after-doctype-name

This error occurs if the parser encounters any code point sequence other than "PUBLIC" and "SYSTEM" keywords after a DOCTYPE name. In such a case, the parser ignores any following public or system identifiers, and if the DOCTYPE is correctly placed as a document preamble, sets the Document to quirks mode.

invalid-first-character-of-tag-name

This error occurs if the parser encounters a code point that is not an ASCII alpha where first code point of a start tag name or an end tag name is expected. If a start tag was expected such code point and a preceding U+003C (<) is treated as text content, and all content that follows is treated as markup. Whereas, if an end tag was expected, such code point and all content that follows up to a U+003E (>) code point (if present) or to the end of the input stream is treated as a comment.

For example, consider the following markup:

<42></42>

This will be parsed into:

While the first code point of a tag name is limited to an ASCII alpha, a wide range of code points (including ASCII digits) is allowed in subsequent positions.

missing-attribute-value

This error occurs if the parser encounters a U+003E (>) code point where an attribute value is expected (e.g., <div id=>). The parser treats the attribute as having an empty value.

missing-doctype-name

This error occurs if the parser encounters a DOCTYPE that is missing a name (e.g., <!DOCTYPE>). In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode.

missing-doctype-public-identifier

This error occurs if the parser encounters a U+003E (>) code point where start of the DOCTYPE public identifier is expected (e.g., <!DOCTYPE html PUBLIC >). In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode.

missing-doctype-system-identifier

This error occurs if the parser encounters a U+003E (>) code point where start of the DOCTYPE system identifier is expected (e.g., <!DOCTYPE html SYSTEM >). In such a case, if the DOCTYPE is correctly placed as a document preamble, the parser sets the Document to quirks mode.

missing-end-tag-name

This error occurs if the parser encounters a U+003E (>) code point where an end tag name is expected, i.e., </>. The parser completely ignores whole "</>" code point sequence.

missing-quote-before-doctype-public-identifier

This error occurs if the parser encounters the DOCTYPE public identifier that is not preceded by a quote (e.g., <!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01//EN">). In such a case, the parser ignores the public identifier, and if the DOCTYPE is correctly placed as a document preamble, sets the Document to quirks mode.

missing-quote-before-doctype-system-identifier

This error occurs if the parser encounters the DOCTYPE system identifier that is not preceded by a quote (e.g., <!DOCTYPE html SYSTEM http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">). In such a case, the parser ignores the system identifier, and if the DOCTYPE is correctly placed as a document preamble, sets the Document to quirks mode.

missing-semicolon-after-character-reference

This error occurs if the parser encounters a character reference that is not terminated by a U+003B (;) code point. Usually the parser behaves as if character reference is terminated by the U+003B (;) code point; however, there are some ambiguous cases in which the parser includes subsequent code points in the character reference.

For example, &not;in will be parsed as "¬in" whereas &notin will be parsed as "".

missing-whitespace-after-doctype-public-keyword

This error occurs if the parser encounters a DOCTYPE whose "PUBLIC" keyword and public identifier are not separated by ASCII whitespace. In this case the parser behaves as if ASCII whitespace is present.

missing-whitespace-after-doctype-system-keyword

This error occurs if the parser encounters a DOCTYPE whose "SYSTEM" keyword and system identifier are not separated by ASCII whitespace. In this case the parser behaves as if ASCII whitespace is present.

missing-whitespace-before-doctype-name

This error occurs if the parser encounters a DOCTYPE whose "DOCTYPE" keyword and name are not separated by ASCII whitespace. In this case the parser behaves as if ASCII whitespace is present.

missing-whitespace-between-attributes

This error occurs if the parser encounters attributes that are not separated by ASCII whitespace (e.g., <div id="foo"class="bar">). In this case the parser behaves as if ASCII whitespace is present.

missing-whitespace-between-doctype-public-and-system-identifiers

This error occurs if the parser encounters a DOCTYPE whose public and system identifiers are not separated by ASCII whitespace. In this case the parser behaves as if ASCII whitespace is present.

nested-comment

This error occurs if the parser encounters a nested comment (e.g., <!-- <!-- nested --> -->). Such a comment will be closed by the first occuring "-->" code point sequence and everything that follows will be treated as markup.

noncharacter-character-reference

This error occurs if the parser encounters a numeric character reference that references a noncharacter. The parser resolves such character references as-is.

noncharacter-in-input-stream

This error occurs if the input stream contains a noncharacter. Such code points are parsed as-is and usually, where parsing rules don't apply any additional restrictions, make their way into the DOM.

non-void-html-element-start-tag-with-trailing-solidus

This error occurs if the parser encounters a start tag for an element that is not in the list of void elements or is not a part of foreign content (i.e., not an SVG or MathML element) that has a U+002F (/) code point right before the closing U+003E (>) code point. The parser behaves as if the U+002F (/) is not present.

For example, consider the following markup:

<div/><span></span><span></span>

This will be parsed into:

The trailing U+002F (/) in a start tag name can be used only in foreign content to specify self-closing tags. (Self-closing tags don't exist in HTML.) It is also allowed for void elements, but doesn't have any effect in this case.

null-character-reference

This error occurs if the parser encounters a numeric character reference that references a U+0000 NULL code point. The parser resolves such character references to a U+FFFD REPLACEMENT CHARACTER.

surrogate-character-reference

This error occurs if the parser encounters a numeric character reference that references a surrogate. The parser resolves such character references to a U+FFFD REPLACEMENT CHARACTER.

surrogate-in-input-stream

This error occurs if the input stream contains a surrogate. Such code points are parsed as-is and usually, where parsing rules don't apply any additional restrictions, make their way into the DOM.

Surrogates can only find their way into the input stream via script APIs such as document.write().

unexpected-character-after-doctype-system-identifier

This error occurs if the parser encounters any code points other than ASCII whitespace or closing U+003E (>) after the DOCTYPE system identifier. The parser ignores these code points.

unexpected-character-in-attribute-name

This error occurs if the parser encounters a U+0022 ("), U+0027 ('), or U+003C (<) code point in an attribute name. The parser includes such code points in the attribute name.

Code points that trigger this error are usually a part of another syntactic construct and can be a sign of a typo around the attribute name.

For example, consider the following markup:

<div foo<div>

Due to a forgotten U+003E (>) code point after foo the parser treats this markup as a single div element with a "foo<div" attribute.

As another example of this error, consider the following markup:

<div id'bar'>

Due to a forgotten U+003D (=) code point between an attribute name and value the parser treats this markup as a div element with the attribute "id'bar'" that has an empty value.

unexpected-character-in-unquoted-attribute-value

This error occurs if the parser encounters a U+0022 ("), U+0027 ('), U+003C (<), U+003D (=), or U+0060 (`) code point in an unquoted attribute value. The parser includes such code points in the attribute value.

Code points that trigger this error are usually a part of another syntactic construct and can be a sign of a typo around the attribute value.

U+0060 (`) is in the list of code points that trigger this error because certain legacy user agents treat it as a quote.

For example, consider the following markup:

<div foo=b'ar'>

Due to a misplaced U+0027 (') code point the parser sets the value of the "foo" attribute to "b'ar'".

unexpected-equals-sign-before-attribute-name

This error occurs if the parser encounters a U+003D (=) code point before an attribute name. In this case the parser treats U+003D (=) as the first code point of the attribute name.

The common reason for this error is a forgotten attribute name.

For example, consider the following markup:

<div foo="bar" ="baz">

Due to a forgotten attribute name the parser treats this markup as a div element with two attributes: a "foo" attribute with a "bar" value and a "="baz"" attribute with an empty value.

unexpected-null-character

This error occurs if the parser encounters a U+0000 NULL code point in the input stream in certain positions. In general, such code points are either completely ignored or, for security reasons, replaced with a U+FFFD REPLACEMENT CHARACTER.

unexpected-question-mark-instead-of-tag-name

This error occurs if the parser encounters a U+003F (?) code point where first code point of a start tag name is expected. The U+003F (?) and all content that follows up to a U+003E (>) code point (if present) or to the end of the input stream is treated as a comment.

For example, consider the following markup:

<?xml-stylesheet type="text/css" href="style.css"?>

This will be parsed into:

The common reason for this error is an XML processing instruction (e.g., <?xml-stylesheet type="text/css" href="style.css"?>) or an XML declaration (e.g., <?xml version="1.0" encoding="UTF-8"?>) being used in HTML.

unexpected-solidus-in-tag

This error occurs if the parser encounters a U+002F (/) code point that is not a part of a quoted attribute value and not immediately followed by a U+003E (>) code point in a tag (e.g., <div / id="foo">). In this case the parser behaves as if it encountered ASCII whitespace.

unknown-named-character-reference

This error occurs if the parser encounters an ambiguous ampersand. In this case the parser doesn't resolve the character reference.

13.2.3 输入字节流

作为 tokenization 阶段的输入的代码点流,最初是经过用户代理的, 被视为字节流(通常通过网络或本地文件系统)。 这些字节是根据特定 字符编码 对实际字符进行的编码,用户代理用该字符编码将字节解码为字符。

对于 XML 文档,用户代理确定字符编码的算法由 XML 规范给出。 本小节不适用于 XML 文档。 [XML]

通常使用下面定义的 编码探测算法 来确定字符编码。

给定一个字符编码,输入字节流 中的字节必须转换为给 tokenizer 输入流 的字符, 这其中需要传递 输入字节流 本身, 以及用来 解码 的字符编码。

前导 Byte Order Mark (BOM) 会使 tokenizer 忽略字符编码参数,并跳过这个 BOM。

不符合编码标准的(例如 UTF-8 输入字节流中的非法 UTF-8 字节序列) 原始字节流中的字节或字节序列也是一致性检查工具需要报告的错误。[ENCODING]

解码算法描述了如何处理非法输入; 为了安全起见,精确地遵守这些规则是很必要的。 对无效字节序列的处理的区别可能会导致脚本注入缺陷(虽然还有其他问题)。

当 HTML 解析器解码一个输入字节流时,它必须使用一个字符编码以及对应的 信心。 这个信息可能是 tentative, certainirrelevant。 无论信心是 tentativecertain 这个字符编码都会 用于解析 来决定是否 更改字符编码。 如果不需要字符编码, 例如因为解析器正在操作 Unicode 流根本不需要字符编码, 那么 信心 就是 irrelevant

有些算法给解析器的数据时,会直接 在 输入流 中添加字符, 而不是在 输入字节流 中添加字节。

13.2.3.1 使用已知字符编码进行解析

当 HTML 解析器要在有 已知确定编码 的输入字节流上操作时,字符编码就是那个编码, 信心certain

13.2.3.2 Determining the character encoding

In some cases, it might be impractical to unambiguously determine the encoding before parsing the document. Because of this, this specification provides for a two-pass mechanism with an optional pre-scan. Implementations are allowed, as described below, to apply a simplified parsing algorithm to whatever bytes they have available before beginning to parse the document. Then, the real parser is started, using a tentative encoding derived from this pre-parse and other out-of-band metadata. If, while the document is being loaded, the user agent discovers a character encoding declaration that conflicts with this information, then the parser can get reinvoked to perform a parse of the document with the real encoding.

User agents must use the following algorithm, called the encoding sniffing algorithm, to determine the character encoding to use when decoding a document in the first pass. This algorithm takes as input any out-of-band metadata available to the user agent (e.g. the Content-Type metadata of the document) and all the bytes available so far, and returns a character encoding and a confidence that is either tentative or certain.

  1. If the result of BOM sniffing is an encoding, return that encoding with confidence certain.

    Although the decode algorithm will itself change the encoding to use based on the presence of a byte order mark, this algorithm sniffs the BOM as well in order to set the correct document's character encoding and confidence.

  2. If the user has explicitly instructed the user agent to override the document's character encoding with a specific encoding, optionally return that encoding with the confidence certain.

    Typically, user agents remember such user requests across sessions, and in some cases apply them to documents in iframes as well.

  3. The user agent may wait for more bytes of the resource to be available, either in this step or at any later step in this algorithm. For instance, a user agent might wait 500ms or 1024 bytes, whichever came first. In general preparsing the source to find the encoding improves performance, as it reduces the need to throw away the data structures used when parsing upon finding the encoding information. However, if the user agent delays too long to obtain data to determine the encoding, then the cost of the delay could outweigh any performance improvements from the preparse.

    The authoring conformance requirements for character encoding declarations limit them to only appearing in the first 1024 bytes. User agents are therefore encouraged to use the prescan algorithm below (as invoked by these steps) on the first 1024 bytes, but not to stall beyond that.

  4. If the transport layer specifies a character encoding, and it is supported, return that encoding with the confidence certain.

  5. Optionally prescan the byte stream to determine its encoding. The end condition is that the user agent decides that scanning further bytes would not be efficient. User agents are encouraged to only prescan the first 1024 bytes. User agents may decide that scanning any bytes is not efficient, in which case these substeps are entirely skipped.

    The aforementioned algorithm either aborts unsuccessfully or returns a character encoding. If it returns a character encoding, then return the same encoding, with confidence tentative.

  6. If the HTML parser for which this algorithm is being run is associated with a Document d whose browsing context is non-null and a child browsing context, then:

    1. Let parentDocument be d's browsing context's container document.

    2. If parentDocument's origin is same origin with d's origin and parentDocument's character encoding is not UTF-16BE/LE, then return parentDocument's character encoding, with the confidence tentative.

  7. Otherwise, if the user agent has information on the likely encoding for this page, e.g. based on the encoding of the page when it was last visited, then return that encoding, with the confidence tentative.

  8. The user agent may attempt to autodetect the character encoding from applying frequency analysis or other algorithms to the data stream. Such algorithms may use information about the resource other than the resource's contents, including the address of the resource. If autodetection succeeds in determining a character encoding, and that encoding is a supported encoding, then return that encoding, with the confidence tentative. [UNIVCHARDET]

    User agents are generally discouraged from attempting to autodetect encodings for resources obtained over the network, since doing so involves inherently non-interoperable heuristics. Attempting to detect encodings based on an HTML document's preamble is especially tricky since HTML markup typically uses only ASCII characters, and HTML documents tend to begin with a lot of markup rather than with text content.

    The UTF-8 encoding has a highly detectable bit pattern. Files from the local file system that contain bytes with values greater than 0x7F which match the UTF-8 pattern are very likely to be UTF-8, while documents with byte sequences that do not match it are very likely not. When a user agent can examine the whole file, rather than just the preamble, detecting for UTF-8 specifically can be especially effective. [PPUTF8] [UTF8DET]

  9. Otherwise, return an implementation-defined or user-specified default character encoding, with the confidence tentative.

    In controlled environments or in environments where the encoding of documents can be prescribed (for example, for user agents intended for dedicated use in new networks), the comprehensive UTF-8 encoding is suggested.

    In other environments, the default encoding is typically dependent on the user's locale (an approximation of the languages, and thus often encodings, of the pages that the user is likely to frequent). The following table gives suggested defaults based on the user's locale, for compatibility with legacy content. Locales are identified by BCP 47 language tags. [BCP47] [ENCODING]

    Locale language Suggested default encoding
    ar Arabic windows-1256
    ba Bashkir windows-1251
    be Belarusian windows-1251
    bg Bulgarian windows-1251
    cs Czech windows-1250
    el Greek ISO-8859-7
    et Estonian windows-1257
    fa Persian windows-1256
    he Hebrew windows-1255
    hr Croatian windows-1250
    hu Hungarian ISO-8859-2
    ja Japanese Shift_JIS
    kk Kazakh windows-1251
    ko Korean EUC-KR
    ku Kurdish windows-1254
    ky Kyrgyz windows-1251
    lt Lithuanian windows-1257
    lv Latvian windows-1257
    mk Macedonian windows-1251
    pl Polish ISO-8859-2
    ru Russian windows-1251
    sah Yakut windows-1251
    sk Slovak windows-1250
    sl Slovenian ISO-8859-2
    sr Serbian windows-1251
    tg Tajik windows-1251
    th Thai windows-874
    tr Turkish windows-1254
    tt Tatar windows-1251
    uk Ukrainian windows-1251
    vi Vietnamese windows-1258
    zh-CN Chinese (People's Republic of China) gb18030
    zh-TW Chinese (Taiwan) Big5
    All other locales windows-1252

    The contents of this table are derived from the intersection of Windows, Chrome, and Firefox defaults.

The document's character encoding must immediately be set to the value returned from this algorithm, at the same time as the user agent uses the returned value to select the decoder to use for the input byte stream.


When an algorithm requires a user agent to prescan a byte stream to determine its encoding, given some defined end condition, then it must run the following steps. These steps either abort unsuccessfully or return a character encoding. If at any point during these steps (including during instances of the get an attribute algorithm invoked by this one) the user agent either runs out of bytes (meaning the position pointer created in the first step below goes beyond the end of the byte stream obtained so far) or reaches its end condition, then abort the prescan a byte stream to determine its encoding algorithm unsuccessfully.

  1. Let position be a pointer to a byte in the input byte stream, initially pointing at the first byte.

  2. Loop: If position points to:

    A sequence of bytes starting with: 0x3C 0x21 0x2D 0x2D (`<!--`)

    Advance the position pointer so that it points at the first 0x3E byte which is preceded by two 0x2D bytes (i.e. at the end of an ASCII '-->' sequence) and comes after the 0x3C byte that was found. (The two 0x2D bytes can be the same as those in the '<!--' sequence.)

    A sequence of bytes starting with: 0x3C, 0x4D or 0x6D, 0x45 or 0x65, 0x54 or 0x74, 0x41 or 0x61, and one of 0x09, 0x0A, 0x0C, 0x0D, 0x20, 0x2F (case-insensitive ASCII '<meta' followed by a space or slash)
    1. Advance the position pointer so that it points at the next 0x09, 0x0A, 0x0C, 0x0D, 0x20, or 0x2F byte (the one in sequence of characters matched above).

    2. Let attribute list be an empty list of strings.

    3. Let got pragma be false.

    4. Let need pragma be null.

    5. Let charset be the null value (which, for the purposes of this algorithm, is distinct from an unrecognized encoding or the empty string).

    6. Attributes: Get an attribute and its value. If no attribute was sniffed, then jump to the processing step below.

    7. If the attribute's name is already in attribute list, then return to the step labeled attributes.

    8. Add the attribute's name to attribute list.

    9. Run the appropriate step from the following list, if one applies:

      If the attribute's name is "http-equiv"

      If the attribute's value is "content-type", then set got pragma to true.

      If the attribute's name is "content"

      Apply the algorithm for extracting a character encoding from a meta element, giving the attribute's value as the string to parse. If a character encoding is returned, and if charset is still set to null, let charset be the encoding returned, and set need pragma to true.

      If the attribute's name is "charset"

      Let charset be the result of getting an encoding from the attribute's value, and set need pragma to false.

    10. Return to the step labeled attributes.

    11. Processing: If need pragma is null, then jump to the step below labeled next byte.

    12. If need pragma is true but got pragma is false, then jump to the step below labeled next byte.

    13. If charset is failure, then jump to the step below labeled next byte.

    14. If charset is UTF-16BE/LE, then set charset to UTF-8.

    15. If charset is x-user-defined, then set charset to windows-1252.

    16. Abort the prescan a byte stream to determine its encoding algorithm, returning the encoding given by charset.

    A sequence of bytes starting with a 0x3C byte (<), optionally a 0x2F byte (/), and finally a byte in the range 0x41-0x5A or 0x61-0x7A (A-Z or a-z)
    1. Advance the position pointer so that it points at the next 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), 0x20 (SP), or 0x3E (>) byte.

    2. Repeatedly get an attribute until no further attributes can be found, then jump to the step below labeled next byte.

    A sequence of bytes starting with: 0x3C 0x21 (`<!`)
    A sequence of bytes starting with: 0x3C 0x2F (`</`)
    A sequence of bytes starting with: 0x3C 0x3F (`<?`)

    Advance the position pointer so that it points at the first 0x3E byte (>) that comes after the 0x3C byte that was found.

    Any other byte

    Do nothing with that byte.

  3. Next byte: Move position so it points at the next byte in the input byte stream, and return to the step above labeled loop.

When the prescan a byte stream to determine its encoding algorithm says to get an attribute, it means doing this:

  1. If the byte at position is one of 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), 0x20 (SP), or 0x2F (/) then advance position to the next byte and redo this step.

  2. If the byte at position is 0x3E (>), then abort the get an attribute algorithm. There isn't one.

  3. Otherwise, the byte at position is the start of the attribute name. Let attribute name and attribute value be the empty string.

  4. Process the byte at position as follows:

    If it is 0x3D (=), and the attribute name is longer than the empty string
    Advance position to the next byte and jump to the step below labeled value.
    If it is 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), or 0x20 (SP)
    Jump to the step below labeled spaces.
    If it is 0x2F (/) or 0x3E (>)
    Abort the get an attribute algorithm. The attribute's name is the value of attribute name, its value is the empty string.
    If it is in the range 0x41 (A) to 0x5A (Z)
    Append the code point b+0x20 to attribute name (where b is the value of the byte at position). (This converts the input to lowercase.)
    Anything else
    Append the code point with the same value as the byte at position to attribute name. (It doesn't actually matter how bytes outside the ASCII range are handled here, since only ASCII bytes can contribute to the detection of a character encoding.)
  5. Advance position to the next byte and return to the previous step.

  6. Spaces: If the byte at position is one of 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), or 0x20 (SP) then advance position to the next byte, then, repeat this step.

  7. If the byte at position is not 0x3D (=), abort the get an attribute algorithm. The attribute's name is the value of attribute name, its value is the empty string.

  8. Advance position past the 0x3D (=) byte.

  9. Value: If the byte at position is one of 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), or 0x20 (SP) then advance position to the next byte, then, repeat this step.

  10. Process the byte at position as follows:

    If it is 0x22 (") or 0x27 (')
    1. Let b be the value of the byte at position.
    2. Quote loop: Advance position to the next byte.
    3. If the value of the byte at position is the value of b, then advance position to the next byte and abort the "get an attribute" algorithm. The attribute's name is the value of attribute name, and its value is the value of attribute value.
    4. Otherwise, if the value of the byte at position is in the range 0x41 (A) to 0x5A (Z), then append a code point to attribute value whose value is 0x20 more than the value of the byte at position.
    5. Otherwise, append a code point to attribute value whose value is the same as the value of the byte at position.
    6. Return to the step above labeled quote loop.
    If it is 0x3E (>)
    Abort the get an attribute algorithm. The attribute's name is the value of attribute name, its value is the empty string.
    If it is in the range 0x41 (A) to 0x5A (Z)
    Append a code point b+0x20 to attribute value (where b is the value of the byte at position). Advance position to the next byte.
    Anything else
    Append a code point with the same value as the byte at position to attribute value. Advance position to the next byte.
  11. Process the byte at position as follows:

    If it is 0x09 (HT), 0x0A (LF), 0x0C (FF), 0x0D (CR), 0x20 (SP), or 0x3E (>)
    Abort the get an attribute algorithm. The attribute's name is the value of attribute name and its value is the value of attribute value.
    If it is in the range 0x41 (A) to 0x5A (Z)
    Append a code point b+0x20 to attribute value (where b is the value of the byte at position).
    Anything else
    Append a code point with the same value as the byte at position to attribute value.
  12. Advance position to the next byte and return to the previous step.

For the sake of interoperability, user agents should not use a pre-scan algorithm that returns different results than the one described above. (But, if you do, please at least let us know, so that we can improve this algorithm and benefit everyone...)

13.2.3.3 字符编码

用户代理必须支持 WHATWG Encoding 标准中定义的编码,包括但不限于 UTF-8, ISO-8859-2, ISO-8859-7, ISO-8859-8, windows-874, windows-1250, windows-1251, windows-1252, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, gb18030, Big5, ISO-2022-JP, Shift_JIS, EUC-KR, UTF-16BE/LE, 和 x-user-defined。 用户代理不得支持其他编码。

上述禁止支持例如 CESU-8, UTF-7, BOCU-1, SCSU, EBCDIC, 和 UTF-32 这些编码。本规范的算法中不试图支持那些禁止编码; 支持和使用禁止的编码可能会导致不可预期的行为。 [CESU8] [UTF7] [BOCU1] [SCSU]

13.2.3.4 Changing the encoding while parsing

When the parser requires the user agent to change the encoding, it must run the following steps. This might happen if the encoding sniffing algorithm described above failed to find a character encoding, or if it found a character encoding that was not the actual encoding of the file.

  1. If the encoding that is already being used to interpret the input stream is UTF-16BE/LE, then set the confidence to certain and return. The new encoding is ignored; if it was anything but the same encoding, then it would be clearly incorrect.

  2. If the new encoding is UTF-16BE/LE, then change it to UTF-8.

  3. If the new encoding is x-user-defined, then change it to windows-1252.

  4. If the new encoding is identical or equivalent to the encoding that is already being used to interpret the input stream, then set the confidence to certain and return. This happens when the encoding information found in the file matches what the encoding sniffing algorithm determined to be the encoding, and in the second pass through the parser if the first pass found that the encoding sniffing algorithm described in the earlier section failed to find the right encoding.

  5. If all the bytes up to the last byte converted by the current decoder have the same Unicode interpretations in both the current encoding and the new encoding, and if the user agent supports changing the converter on the fly, then the user agent may change to the new converter for the encoding on the fly. Set the document's character encoding and the encoding used to convert the input stream to the new encoding, set the confidence to certain, and return.

  6. Otherwise, navigate to the document again, with historyHandling set to "replace", and using the same source browsing context, but this time skip the encoding sniffing algorithm and instead just set the encoding to the new encoding and the confidence to certain. Whenever possible, this should be done without actually contacting the network layer (the bytes should be re-parsed from memory), even if, e.g., the document is marked as not being cacheable. If this is not possible and contacting the network layer would involve repeating a request that uses a method other than `GET`, then instead set the confidence to certain and ignore the new encoding. The resource will be misinterpreted. User agents may notify the user of the situation, to aid in application development.

This algorithm is only invoked when a new encoding is found declared on a meta element.

13.2.3.5 Preprocessing the input stream

The input stream consists of the characters pushed into it as the input byte stream is decoded or from the various APIs that directly manipulate the input stream.

Any occurrences of surrogates are surrogate-in-input-stream parse errors. Any occurrences of noncharacters are noncharacter-in-input-stream parse errors and any occurrences of controls other than ASCII whitespace and U+0000 NULL characters are control-character-in-input-stream parse errors.

The handling of U+0000 NULL characters varies based on where the characters are found and happens at the later stages of the parsing. They are either ignored or, for security reasons, replaced with a U+FFFD REPLACEMENT CHARACTER. This handling is, by necessity, spread across both the tokenization stage and the tree construction stage.

Before the tokenization stage, the input stream must be preprocessed by normalizing newlines. Thus, newlines in HTML DOMs are represented by U+000A LF characters, and there are never any U+000D CR characters in the input to the tokenization stage.

The next input character is the first character in the input stream that has not yet been consumed or explicitly ignored by the requirements in this section. Initially, the next input character is the first character in the input. The current input character is the last character to have been consumed.

The insertion point is the position (just before a character or just before the end of the input stream) where content inserted using document.write() is actually inserted. The insertion point is relative to the position of the character immediately after it, it is not an absolute offset into the input stream. Initially, the insertion point is undefined.

The "EOF" character in the tables below is a conceptual character representing the end of the input stream. If the parser is a script-created parser, then the end of the input stream is reached when an explicit "EOF" character (inserted by the document.close() method) is consumed. Otherwise, the "EOF" character is not a real character in the stream, but rather the lack of any further characters.

13.2.4 解析状态

13.2.4.1 The insertion mode

The insertion mode is a state variable that controls the primary operation of the tree construction stage.

Initially, the insertion mode is "initial". It can change to "before html", "before head", "in head", "in head noscript", "after head", "in body", "text", "in table", "in table text", "in caption", "in column group", "in table body", "in row", "in cell", "in select", "in select in table", "in template", "after body", "in frameset", "after frameset", "after after body", and "after after frameset" during the course of the parsing, as described in the tree construction stage. The insertion mode affects how tokens are processed and whether CDATA sections are supported.

Several of these modes, namely "in head", "in body", "in table", and "in select", are special, in that the other modes defer to them at various times. When the algorithm below says that the user agent is to do something "using the rules for the m insertion mode", where m is one of these modes, the user agent must use the rules described under the m insertion mode's section, but must leave the insertion mode unchanged unless the rules in m themselves switch the insertion mode to a new value.

When the insertion mode is switched to "text" or "in table text", the original insertion mode is also set. This is the insertion mode to which the tree construction stage will return.

Similarly, to parse nested template elements, a stack of template insertion modes is used. It is initially empty. The current template insertion mode is the insertion mode that was most recently added to the stack of template insertion modes. The algorithms in the sections below will push insertion modes onto this stack, meaning that the specified insertion mode is to be added to the stack, and pop insertion modes from the stack, which means that the most recently added insertion mode must be removed from the stack.


When the steps below require the UA to reset the insertion mode appropriately, it means the UA must follow these steps:

  1. Let last be false.

  2. Let node be the last node in the stack of open elements.

  3. Loop: If node is the first node in the stack of open elements, then set last to true, and, if the parser was created as part of the HTML fragment parsing algorithm (fragment case), set node to the context element passed to that algorithm.

  4. If node is a select element, run these substeps:

    1. If last is true, jump to the step below labeled done.

    2. Let ancestor be node.

    3. Loop: If ancestor is the first node in the stack of open elements, jump to the step below labeled done.

    4. Let ancestor be the node before ancestor in the stack of open elements.

    5. If ancestor is a template node, jump to the step below labeled done.

    6. If ancestor is a table node, switch the insertion mode to "in select in table" and return.

    7. Jump back to the step labeled loop.

    8. Done: Switch the insertion mode to "in select" and return.

  5. If node is a td or th element and last is false, then switch the insertion mode to "in cell" and return.

  6. If node is a tr element, then switch the insertion mode to "in row" and return.

  7. If node is a tbody, thead, or tfoot element, then switch the insertion mode to "in table body" and return.

  8. If node is a caption element, then switch the insertion mode to "in caption" and return.

  9. If node is a colgroup element, then switch the insertion mode to "in column group" and return.

  10. If node is a table element, then switch the insertion mode to "in table" and return.

  11. If node is a template element, then switch the insertion mode to the current template insertion mode and return.

  12. If node is a head element and last is false, then switch the insertion mode to "in head" and return.

  13. If node is a body element, then switch the insertion mode to "in body" and return.

  14. If node is a frameset element, then switch the insertion mode to "in frameset" and return. (fragment case)

  15. If node is an html element, run these substeps:

    1. If the head element pointer is null, switch the insertion mode to "before head" and return. (fragment case)

    2. Otherwise, the head element pointer is not null, switch the insertion mode to "after head" and return.

  16. If last is true, then switch the insertion mode to "in body" and return. (fragment case)

  17. Let node now be the node before node in the stack of open elements.

  18. Return to the step labeled loop.

13.2.4.2 The stack of open elements

Initially, the stack of open elements is empty. The stack grows downwards; the topmost node on the stack is the first one added to the stack, and the bottommost node of the stack is the most recently added node in the stack (notwithstanding when the stack is manipulated in a random access fashion as part of the handling for misnested tags).

The "before html" insertion mode creates the html document element, which is then added to the stack.

In the fragment case, the stack of open elements is initialized to contain an html element that is created as part of that algorithm. (The fragment case skips the "before html" insertion mode.)

The html node, however it is created, is the topmost node of the stack. It only gets popped off the stack when the parser finishes.

The current node is the bottommost node in this stack of open elements.

The adjusted current node is the context element if the parser was created as part of the HTML fragment parsing algorithm and the stack of open elements has only one element in it (fragment case); otherwise, the adjusted current node is the current node.

Elements in the stack of open elements fall into the following categories:

Special

The following elements have varying levels of special parsing rules: HTML's address, applet, area, article, aside, base, basefont, bgsound, blockquote, body, br, button, caption, center, col, colgroup, dd, details, dir, div, dl, dt, embed, fieldset, figcaption, figure, footer, form, frame, frameset, h1, h2, h3, h4, h5, h6, head, header, hgroup, hr, html, iframe, img, input, keygen, li, link, listing, main, marquee, menu, meta, nav, noembed, noframes, noscript, object, ol, p, param, plaintext, pre, script, section, select, source, style, summary, table, tbody, td, template, textarea, tfoot, th, thead, title, tr, track, ul, wbr, xmp; MathML mi, MathML mo, MathML mn, MathML ms, MathML mtext, and MathML annotation-xml; and SVG foreignObject, SVG desc, and SVG title.

An image start tag token is handled by the tree builder, but it is not in this list because it is not an element; it gets turned into an img element.

Formatting

The following HTML elements are those that end up in the list of active formatting elements: a, b, big, code, em, font, i, nobr, s, small, strike, strong, tt, and u.

Ordinary

All other elements found while parsing an HTML document.

Typically, the special elements have the start and end tag tokens handled specifically, while ordinary elements' tokens fall into "any other start tag" and "any other end tag" clauses, and some parts of the tree builder check if a particular element in the stack of open elements is in the special category. However, some elements (e.g., the option element) have their start or end tag tokens handled specifically, but are still not in the special category, so that they get the ordinary handling elsewhere.

The stack of open elements is said to have an element target node in a specific scope consisting of a list of element types list when the following algorithm terminates in a match state:

  1. Initialize node to be the current node (the bottommost node of the stack).

  2. If node is the target node, terminate in a match state.

  3. Otherwise, if node is one of the element types in list, terminate in a failure state.

  4. Otherwise, set node to the previous entry in the stack of open elements and return to step 2. (This will never fail, since the loop will always terminate in the previous step if the top of the stack — an html element — is reached.)

The stack of open elements is said to have a particular element in scope when it has that element in the specific scope consisting of the following element types:

The stack of open elements is said to have a particular element in list item scope when it has that element in the specific scope consisting of the following element types:

The stack of open elements is said to have a particular element in button scope when it has that element in the specific scope consisting of the following element types:

The stack of open elements is said to have a particular element in table scope when it has that element in the specific scope consisting of the following element types:

The stack of open elements is said to have a particular element in select scope when it has that element in the specific scope consisting of all element types except the following:

Nothing happens if at any time any of the elements in the stack of open elements are moved to a new location in, or removed from, the Document tree. In particular, the stack is not changed in this situation. This can cause, amongst other strange effects, content to be appended to nodes that are no longer in the DOM.

In some cases (namely, when closing misnested formatting elements), the stack is manipulated in a random-access fashion.

13.2.4.3 活动格式化元素列表

活动格式化元素列表 初始为空。 它用来处理错误嵌套的 格式化元素标签

该列表包含 formatting 类别下的元素以及 标记。 当进入 applet, object, marquee, template, td, th, 和 caption 元素时会插入 标记。 用来防止格式化 "泄漏" applet, object, marquee, template, td, th, 和 caption 元素。

此外,每个 活动的格式化原始列表 中的元素都与创建它的标记相关联,这样在必要时可以为那个标记继续创建元素。

当下面的步骤要 UA 把一个元素 element 推入到活动格式化元素 时, UA 必须执行以下步骤:

  1. 如果在 活动的格式化原始列表 中 最后一个 标记 后已经有三个元素(如果没有标记,就匹配任意地方) 与 element 有同样的名字、命名空间和属性,就把最先的那个元素从 活动的格式化原始列表 移除。 比较属性时必须以元素刚被解析器创建出来的状态为准; 如果两个元素的所有属性可以配对,每一对属性有同样的属性名、命名空间和值(顺序不重要), 那么就说两个元素有相同的属性。

    这是诺亚方舟条款。。但每个家庭有三个人,而不是两个。

  2. element 添加到 活动的格式化原始列表

当下面的步骤要 UA 重新构造活动的格式化元素 时, UA 必须执行以下步骤:

  1. 如果 活动的格式化原始列表 中没有项目, 那就没什么要重新构造的,停止本算法。

  2. 如果 活动的格式化原始列表 的最后一项(最近添加的)是一个 标记, 或者如果它是 打开元素栈 中的元素, 那么也没有什么要重新构造的;停止本算法。

  3. entry活动的格式化原始列表 的最后一项(最近添加的)。

  4. Rewind:如果在 活动的格式化原始列表entry 之前没有项目,那就跳到标记为 create 的步骤。

  5. entry活动的格式化原始列表entry 的前一项。

  6. 如果 entry 既不是一个 标记, 也不是 打开元素栈 中的元素, 跳到标记为 rewind 的步骤。

  7. Advance: 令 entry活动的格式化原始列表entry 的后一项。

  8. Create: 为创建 entry 的标记 插入一个 HTML 元素,来得到 new element

  9. 把列表中的 entry 替换为一个 new element 的项目。

  10. 如果 活动的格式化原始列表new element 的项目不是列表的最后一项,返回到标记为 advance 的步骤。

这样的效果是重新打开所有在当前 body,cell 或 caption(任何最早的元素)格式化元素中的,没有显式关闭的元素。

本标准中,活动的格式化原始列表 总是由按时间排序的元素组成,最先添加的元素在最前面,最后添加的元素在最后 (当然上述算法中 7-10 的循环除外)。

当下面的步骤要 UA 清楚活动格式化元素列表到最后一个标记 时,UA 必须执行以下步骤:

  1. entry活动的格式化原始列表 中的最后一项(最近添加的)。

  2. 活动的格式化原始列表 中移除 entry

  3. 如果 entry 是一个 标记, 则立即停止本算法。该列表已经清除到了最后一个 标记

  4. 跳到步骤 1。

13.2.4.4 元素指针

head 元素指针form 元素指针 初始都为 null。

一旦 head 元素已经解析完成(不管是隐式地还是显式地) head 元素指针 都会设置为指向这一节点。

form 元素指针 指向仍然打开的还未看到关闭标签的最后一个 form 元素。 它用来让表单控件即使最坏的写法下也可以关联到表单。 在 template 元素中要忽略它。

13.2.4.5 其他解析状态标志

如果与该解析器关联的 Document脚本被启用脚本标志 就设为 "enabled",否则设为 "disabled"。

即使该解析器最初是为 HTML 片段解析算法 创建的,也可以启用 脚本标志, 即使 script 元素在这种情况下不会执行。

当解析器创建时,frameset-ok 标志 设为 "ok"。 当遇到某些标记时它会设为 "not ok"。

13.2.5 Tokenization

Implementations must act as if they used the following state machine to tokenize HTML. The state machine must start in the data state. Most states consume a single character, which may have various side-effects, and either switches the state machine to a new state to reconsume the current input character, or switches it to a new state to consume the next character, or stays in the same state to consume the next character. Some states have more complicated behavior and can consume several characters before switching to another state. In some cases, the tokenizer state is also changed by the tree construction stage.

When a state says to reconsume a matched character in a specified state, that means to switch to that state, but when it attempts to consume the next input character, provide it with the current input character instead.

The exact behavior of certain states depends on the insertion mode and the stack of open elements. Certain states also use a temporary buffer to track progress, and the character reference state uses a return state to return to the state it was invoked from.

The output of the tokenization step is a series of zero or more of the following tokens: DOCTYPE, start tag, end tag, comment, character, end-of-file. DOCTYPE tokens have a name, a public identifier, a system identifier, and a force-quirks flag. When a DOCTYPE token is created, its name, public identifier, and system identifier must be marked as missing (which is a distinct state from the empty string), and the force-quirks flag must be set to off (its other state is on). Start and end tag tokens have a tag name, a self-closing flag, and a list of attributes, each of which has a name and a value. When a start or end tag token is created, its self-closing flag must be unset (its other state is that it be set), and its attributes list must be empty. Comment and character tokens have data.

When a token is emitted, it must immediately be handled by the tree construction stage. The tree construction stage can affect the state of the tokenization stage, and can insert additional characters into the stream. (For example, the script element can result in scripts executing and using the dynamic markup insertion APIs to insert characters into the stream being tokenized.)

Creating a token and emitting it are distinct actions. It is possible for a token to be created but implicitly abandoned (never emitted), e.g. if the file ends unexpectedly while processing the characters that are being parsed into a start tag token.

When a start tag token is emitted with its self-closing flag set, if the flag is not acknowledged when it is processed by the tree construction stage, that is a non-void-html-element-start-tag-with-trailing-solidus parse error.

When an end tag token is emitted with attributes, that is an end-tag-with-attributes parse error.

When an end tag token is emitted with its self-closing flag set, that is an end-tag-with-trailing-solidus parse error.

An appropriate end tag token is an end tag token whose tag name matches the tag name of the last start tag to have been emitted from this tokenizer, if any. If no start tag has been emitted from this tokenizer, then no end tag token is appropriate.

A character reference is said to be consumed as part of an attribute if the return state is either attribute value (double-quoted) state, attribute value (single-quoted) state or attribute value (unquoted) state.

When a state says to flush code points consumed as a character reference, it means that for each code point in the temporary buffer (in the order they were added to the buffer) user agent must append the code point from the buffer to the current attribute's value if the character reference was consumed as part of an attribute, or emit the code point as a character token otherwise.

Before each step of the tokenizer, the user agent must first check the parser pause flag. If it is true, then the tokenizer must abort the processing of any nested invocations of the tokenizer, yielding control back to the caller.

The tokenizer state machine consists of the states defined in the following subsections.

13.2.5.1 Data state

Consume the next input character:

U+0026 AMPERSAND (&)
Set the return state to the data state. Switch to the character reference state.
U+003C LESS-THAN SIGN (<)
Switch to the tag open state.
U+0000 NULL
This is an unexpected-null-character parse error. Emit the current input character as a character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.2 RCDATA state

Consume the next input character:

U+0026 AMPERSAND (&)
Set the return state to the RCDATA state. Switch to the character reference state.
U+003C LESS-THAN SIGN (<)
Switch to the RCDATA less-than sign state.
U+0000 NULL
This is an unexpected-null-character parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.3 RAWTEXT state

Consume the next input character:

U+003C LESS-THAN SIGN (<)
Switch to the RAWTEXT less-than sign state.
U+0000 NULL
This is an unexpected-null-character parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.4 Script data state

Consume the next input character:

U+003C LESS-THAN SIGN (<)
Switch to the script data less-than sign state.
U+0000 NULL
This is an unexpected-null-character parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.5 PLAINTEXT state

Consume the next input character:

U+0000 NULL
This is an unexpected-null-character parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.6 Tag open state

Consume the next input character:

U+0021 EXCLAMATION MARK (!)
Switch to the markup declaration open state.
U+002F SOLIDUS (/)
Switch to the end tag open state.
ASCII alpha
Create a new start tag token, set its tag name to the empty string. Reconsume in the tag name state.
U+003F QUESTION MARK (?)
This is an unexpected-question-mark-instead-of-tag-name parse error. Create a comment token whose data is the empty string. Reconsume in the bogus comment state.
EOF
This is an eof-before-tag-name parse error. Emit a U+003C LESS-THAN SIGN character token and an end-of-file token.
Anything else
This is an invalid-first-character-of-tag-name parse error. Emit a U+003C LESS-THAN SIGN character token. Reconsume in the data state.
13.2.5.7 End tag open state

Consume the next input character:

ASCII alpha
Create a new end tag token, set its tag name to the empty string. Reconsume in the tag name state.
U+003E GREATER-THAN SIGN (>)
This is a missing-end-tag-name parse error. Switch to the data state.
EOF
This is an eof-before-tag-name parse error. Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token and an end-of-file token.
Anything else
This is an invalid-first-character-of-tag-name parse error. Create a comment token whose data is the empty string. Reconsume in the bogus comment state.
13.2.5.8 Tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the before attribute name state.
U+002F SOLIDUS (/)
Switch to the self-closing start tag state.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current tag token.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current tag token's tag name.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
Append the current input character to the current tag token's tag name.
13.2.5.9 RCDATA 小于号状态

消耗掉 下一个输入字符

U+002F SOLIDUS (/)
temporary buffer 设为空字符串。 切换到 RCDATA 结束标签打开状态
任何其他情况
发出一个 U+003C LESS-THAN SIGN 字符标记。 在 RCDATA 状态 重新消耗 该字符。
13.2.5.10 RCDATA 结束标签打开状态

使用掉 下一个输入字符

ASCII 字符
创建一个新的结束标签标记,把它的标签名设为空字符串。 在 RCDATA 结束标签名状态 重新消耗 该字符。
任何其他情况
发出一个 U+003C LESS-THAN SIGN 和 U+002F SOLIDUS 字符标记。 在 RCDATA 状态 重新消耗 该字符。
13.2.5.11 RCDATA end tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
If the current end tag token is an appropriate end tag token, then switch to the before attribute name state. Otherwise, treat it as per the "anything else" entry below.
U+002F SOLIDUS (/)
If the current end tag token is an appropriate end tag token, then switch to the self-closing start tag state. Otherwise, treat it as per the "anything else" entry below.
U+003E GREATER-THAN SIGN (>)
If the current end tag token is an appropriate end tag token, then switch to the data state and emit the current tag token. Otherwise, treat it as per the "anything else" entry below.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name. Append the current input character to the temporary buffer.
ASCII lower alpha
Append the current input character to the current tag token's tag name. Append the current input character to the temporary buffer.
Anything else
Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token, and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). Reconsume in the RCDATA state.
13.2.5.12 RAWTEXT 小于号状态

消耗掉 下一个输入字符

U+002F SOLIDUS (/)
设置 temporary buffer 为空字符串。切换到 RAWTEXT 结束标签打开状态
任何其他情况
发出一个 U+003C LESS-THAN SIGN 字符标记。 在 RAWTEXT 状态 重新消耗 该字符。
13.2.5.13 RAWTEXT end tag open state

Consume the next input character:

ASCII alpha
Create a new end tag token, set its tag name to the empty string. Reconsume in the RAWTEXT end tag name state.
Anything else
Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume in the RAWTEXT state.
13.2.5.14 RAWTEXT end tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
If the current end tag token is an appropriate end tag token, then switch to the before attribute name state. Otherwise, treat it as per the "anything else" entry below.
U+002F SOLIDUS (/)
If the current end tag token is an appropriate end tag token, then switch to the self-closing start tag state. Otherwise, treat it as per the "anything else" entry below.
U+003E GREATER-THAN SIGN (>)
If the current end tag token is an appropriate end tag token, then switch to the data state and emit the current tag token. Otherwise, treat it as per the "anything else" entry below.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name. Append the current input character to the temporary buffer.
ASCII lower alpha
Append the current input character to the current tag token's tag name. Append the current input character to the temporary buffer.
Anything else
Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token, and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). Reconsume in the RAWTEXT state.
13.2.5.15

消耗掉 下一个输入字符

U+002F SOLIDUS (/)
临时缓冲区 设为空字符串。切换到 脚本数据结束标签打开状态
U+0021 EXCLAMATION MARK (!)
切换到 脚本数据转义开始状态。 发出一个 U+003C LESS-THAN SIGN 和 U+0021 EXCLAMATION MARK 字符标记。
任何其他字符
发出一个 U+003C LESS-THAN SIGN 字符标记。 在 脚本数据状态重新消耗 该字符。
13.2.5.16 Script data end tag open state

Consume the next input character:

ASCII alpha
Create a new end tag token, set its tag name to the empty string. Reconsume in the script data end tag name state.
Anything else
Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume in the script data state.
13.2.5.17 Script data end tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
If the current end tag token is an appropriate end tag token, then switch to the before attribute name state. Otherwise, treat it as per the "anything else" entry below.
U+002F SOLIDUS (/)
If the current end tag token is an appropriate end tag token, then switch to the self-closing start tag state. Otherwise, treat it as per the "anything else" entry below.
U+003E GREATER-THAN SIGN (>)
If the current end tag token is an appropriate end tag token, then switch to the data state and emit the current tag token. Otherwise, treat it as per the "anything else" entry below.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name. Append the current input character to the temporary buffer.
ASCII lower alpha
Append the current input character to the current tag token's tag name. Append the current input character to the temporary buffer.
Anything else
Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token, and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). Reconsume in the script data state.
13.2.5.18 脚本数据转义开始状态

消耗掉 下一个输入字符

U+002D HYPHEN-MINUS (-)
切换到 脚本数据转义开始横线状态。 发出一个 U+002D HYPHEN-MINUS 字符标记。
任何其他字符
脚本数据状态重新消耗 该字符。
13.2.5.19 脚本数据转义开始

使用掉 下一个输入字符

U+002D HYPHEN-MINUS (-)
切换到 脚本数据转义横线横线状态。 发出一个 U+002D HYPHEN-MINUS 字符标记。
任何其他情况
脚本数据状态 重新消耗 该字符。
13.2.5.20 脚本数据转义状态

使用掉 下一个输入字符

U+002D HYPHEN-MINUS (-)
切换到 脚本数据转义横线状态。 发出一个 U+002D HYPHEN-MINUS 字符标记。
U+003C LESS-THAN SIGN (<)
切换到 脚本数据转义小于号状态
U+0000 NULL
这是一个 unexpected-null-character 解析错误。 发出一个 U+FFFD REPLACEMENT CHARACTER 字符标记。
EOF
这是一个 eof-in-script-html-comment-like-text 解析错误。发出一个 EOF 标记。
任何其他情况
当前输入字符 作为字符标记发出。
13.2.5.21 脚本数据转义横线状态

消耗掉 下一个输入字符

U+002D HYPHEN-MINUS (-)
切换到 脚本数据转义横线横线状态。发出一个 U+002D HYPHEN-MINUS 字符标记。
U+003C LESS-THAN SIGN (<)
切换到 脚本数据转义小于号状态
U+0000 NULL
这是一个 unexpected-null-character 解析错误。 切换到 脚本数据转义状态。 发出一个 U+FFFD REPLACEMENT CHARACTER 字符标记。
EOF
这是一个 eof-in-script-html-comment-like-text 解析错误。 发出一个 EOF 标记。
任何其他情况
切换到 脚本数据转义状态。 把 当前输入字符 作为字符标记发出。
13.2.5.22 Script data escaped dash dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the script data escaped less-than sign state.
U+003E GREATER-THAN SIGN (>)
Switch to the script data state. Emit a U+003E GREATER-THAN SIGN character token.
U+0000 NULL
This is an unexpected-null-character parse error. Switch to the script data escaped state. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
This is an eof-in-script-html-comment-like-text parse error. Emit an end-of-file token.
Anything else
Switch to the script data escaped state. Emit the current input character as a character token.
13.2.5.23 脚本数据转义小于号状态

消耗掉 下一个输入字符

U+002F SOLIDUS (/)
设置 temporary buffer 为空字符串。切换到 脚本数据转义结束标签打开状态
ASCII 字符
设置 temporary buffer 为空字符串。发出一个 U+003C LESS-THAN SIGN 字符标记。 在 小本数据双重转义开始状态 重新消耗该字符
任何其他情况
发出一个 U+003C LESS-THAN SIGN 字符标记。 在 脚本数据转义状态 重新消耗 该字符。
13.2.5.24 Script data escaped end tag open state

Consume the next input character:

ASCII alpha
Create a new end tag token, set its tag name to the empty string. Reconsume in the script data escaped end tag name state.
Anything else
Emit a U+003C LESS-THAN SIGN character token and a U+002F SOLIDUS character token. Reconsume in the script data escaped state.
13.2.5.25 Script data escaped end tag name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
If the current end tag token is an appropriate end tag token, then switch to the before attribute name state. Otherwise, treat it as per the "anything else" entry below.
U+002F SOLIDUS (/)
If the current end tag token is an appropriate end tag token, then switch to the self-closing start tag state. Otherwise, treat it as per the "anything else" entry below.
U+003E GREATER-THAN SIGN (>)
If the current end tag token is an appropriate end tag token, then switch to the data state and emit the current tag token. Otherwise, treat it as per the "anything else" entry below.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current tag token's tag name. Append the current input character to the temporary buffer.
ASCII lower alpha
Append the current input character to the current tag token's tag name. Append the current input character to the temporary buffer.
Anything else
Emit a U+003C LESS-THAN SIGN character token, a U+002F SOLIDUS character token, and a character token for each of the characters in the temporary buffer (in the order they were added to the buffer). Reconsume in the script data escaped state.
13.2.5.26 脚本数据双重转义开始状态

使用掉 下一个输入字符

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
U+002F SOLIDUS (/)
U+003E GREATER-THAN SIGN (>)
如果 temporary buffer 是字符串 "script", 则切换到 脚本数据双重转义状态。 否则, 切换到 脚本数据转义状态。 把 当前输入字符 作为字符标记发出。
ASCII 大写字母
当前输入字符 (添加一个 0x0020 到该字符的代码点) 的小写版本追加到 temporary buffer。 把 当前输入字符 作为字符标记发出。
ASCII 小写字母
当前输入字符 追加到 temporary buffer。 把 当前输入字符 作为字符标记发出。
任何其他情况
脚本数据转义状态 重新消耗 该字符。
13.2.5.27 Script data double escaped state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the script data double escaped dash state. Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the script data double escaped less-than sign state. Emit a U+003C LESS-THAN SIGN character token.
U+0000 NULL
This is an unexpected-null-character parse error. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
This is an eof-in-script-html-comment-like-text parse error. Emit an end-of-file token.
Anything else
Emit the current input character as a character token.
13.2.5.28 脚本数据双重转义横线状态

使用掉 下一个输入字符

U+002D HYPHEN-MINUS (-)
切换到 脚本数据双重转义横线横线状态。 发出一个 U+002D HYPHEN-MINUS 字符标记。
U+003C LESS-THAN SIGN (<)
切换到 脚本数据双重转义小于号状态。 发出一个 U+003C LESS-THAN SIGN 字符标记。
U+0000 NULL
这是一个 unexpected-null-character 解析错误。 切换到 脚本数据双重转义状态。 发出一个 U+FFFD REPLACEMENT CHARACTER 字符标记。
EOF
这是一个 eof-in-script-html-comment-like-text 解析错误。 发出一个 EOF 标记。
任何其他情况
切换到 脚本数据双重转义状态。 把 当前输入字符 作为字符标记发出。
13.2.5.29 Script data double escaped dash dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Emit a U+002D HYPHEN-MINUS character token.
U+003C LESS-THAN SIGN (<)
Switch to the script data double escaped less-than sign state. Emit a U+003C LESS-THAN SIGN character token.
U+003E GREATER-THAN SIGN (>)
Switch to the script data state. Emit a U+003E GREATER-THAN SIGN character token.
U+0000 NULL
This is an unexpected-null-character parse error. Switch to the script data double escaped state. Emit a U+FFFD REPLACEMENT CHARACTER character token.
EOF
This is an eof-in-script-html-comment-like-text parse error. Emit an end-of-file token.
Anything else
Switch to the script data double escaped state. Emit the current input character as a character token.
13.2.5.30 脚本数据双重转义小于号状态

使用掉 下一个输入字符

U+002F SOLIDUS (/)
设置 temporary buffer 设为空字符串。 切换到 脚本数据双重转义结束状态。 发出一个 U+002F SOLIDUS 字符标记。
任何其他情况
脚本数据双重转义状态 重新消耗 该字符。
13.2.5.31 脚本数据双重转义结束状态

使用掉 下一个输入字符

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
U+002F SOLIDUS (/)
U+003E GREATER-THAN SIGN (>)
如果 temporary buffer 是字符串 "script",就切换到 脚本数据转义状态。 否则,切换到 脚本数据双重转义状态。 把 当前输入字符 作为字符标记发出。
ASCII 大写字母
当前输入字符 (添加一个 0x0020 到该字符的代码点) 的小写版本追加到 temporary buffer。 把 当前输入字符 作为字符标记发出。
ASCII 小写字母
当前输入字符 追加到 temporary buffer。 把 当前输入字符 作为字符标记发出。
任何其他情况
脚本数据双重转义状态 重新消耗 该字符。
13.2.5.32 Before attribute name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+002F SOLIDUS (/)
U+003E GREATER-THAN SIGN (>)
EOF
Reconsume in the after attribute name state.
U+003D EQUALS SIGN (=)
This is an unexpected-equals-sign-before-attribute-name parse error. Start a new attribute in the current tag token. Set that attribute's name to the current input character, and its value to the empty string. Switch to the attribute name state.
Anything else
Start a new attribute in the current tag token. Set that attribute name and value to the empty string. Reconsume in the attribute name state.
13.2.5.33 Attribute name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
U+002F SOLIDUS (/)
U+003E GREATER-THAN SIGN (>)
EOF
Reconsume in the after attribute name state.
U+003D EQUALS SIGN (=)
Switch to the before attribute value state.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current attribute's name.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute's name.
U+0022 QUOTATION MARK (")
U+0027 APOSTROPHE (')
U+003C LESS-THAN SIGN (<)
This is an unexpected-character-in-attribute-name parse error. Treat it as per the "anything else" entry below.
Anything else
Append the current input character to the current attribute's name.

When the user agent leaves the attribute name state (and before emitting the tag token, if appropriate), the complete attribute's name must be compared to the other attributes on the same token; if there is already an attribute on the token with the exact same name, then this is a duplicate-attribute parse error and the new attribute must be removed from the token.

If an attribute is so removed from a token, it, and the value that gets associated with it, if any, are never subsequently used by the parser, and are therefore effectively discarded. Removing the attribute in this way does not change its status as the "current attribute" for the purposes of the tokenizer, however.

13.2.5.34 After attribute name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+002F SOLIDUS (/)
Switch to the self-closing start tag state.
U+003D EQUALS SIGN (=)
Switch to the before attribute value state.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current tag token.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
Start a new attribute in the current tag token. Set that attribute name and value to the empty string. Reconsume in the attribute name state.
13.2.5.35 Before attribute value state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+0022 QUOTATION MARK (")
Switch to the attribute value (double-quoted) state.
U+0027 APOSTROPHE (')
Switch to the attribute value (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
This is a missing-attribute-value parse error. Switch to the data state. Emit the current tag token.
Anything else
Reconsume in the attribute value (unquoted) state.
13.2.5.36 Attribute value (double-quoted) state

Consume the next input character:

U+0022 QUOTATION MARK (")
Switch to the after attribute value (quoted) state.
U+0026 AMPERSAND (&)
Set the return state to the attribute value (double-quoted) state. Switch to the character reference state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute's value.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
Append the current input character to the current attribute's value.
13.2.5.37 Attribute value (single-quoted) state

Consume the next input character:

U+0027 APOSTROPHE (')
Switch to the after attribute value (quoted) state.
U+0026 AMPERSAND (&)
Set the return state to the attribute value (single-quoted) state. Switch to the character reference state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute's value.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
Append the current input character to the current attribute's value.
13.2.5.38 Attribute value (unquoted) state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the before attribute name state.
U+0026 AMPERSAND (&)
Set the return state to the attribute value (unquoted) state. Switch to the character reference state.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current tag token.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current attribute's value.
U+0022 QUOTATION MARK (")
U+0027 APOSTROPHE (')
U+003C LESS-THAN SIGN (<)
U+003D EQUALS SIGN (=)
U+0060 GRAVE ACCENT (`)
This is an unexpected-character-in-unquoted-attribute-value parse error. Treat it as per the "anything else" entry below.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
Append the current input character to the current attribute's value.
13.2.5.39 After attribute value (quoted) state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the before attribute name state.
U+002F SOLIDUS (/)
Switch to the self-closing start tag state.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current tag token.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
This is a missing-whitespace-between-attributes parse error. Reconsume in the before attribute name state.
13.2.5.40 Self-closing start tag state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
Set the self-closing flag of the current tag token. Switch to the data state. Emit the current tag token.
EOF
This is an eof-in-tag parse error. Emit an end-of-file token.
Anything else
This is an unexpected-solidus-in-tag parse error. Reconsume in the before attribute name state.
13.2.5.41 Bogus comment state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the comment token.
EOF
Emit the comment. Emit an end-of-file token.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the comment token's data.
Anything else
Append the current input character to the comment token's data.
13.2.5.42 Markup declaration open state

If the next few characters are:

Two U+002D HYPHEN-MINUS characters (-)
Consume those two characters, create a comment token whose data is the empty string, and switch to the comment start state.
ASCII case-insensitive match for the word "DOCTYPE"
Consume those characters and switch to the DOCTYPE state.
The string "[CDATA[" (the five uppercase letters "CDATA" with a U+005B LEFT SQUARE BRACKET character before and after)
Consume those characters. If there is an adjusted current node and it is not an element in the HTML namespace, then switch to the CDATA section state. Otherwise, this is a cdata-in-html-content parse error. Create a comment token whose data is the "[CDATA[" string. Switch to the bogus comment state.
Anything else
This is an incorrectly-opened-comment parse error. Create a comment token whose data is the empty string. Switch to the bogus comment state (don't consume anything in the current state).
13.2.5.43 Comment start state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the comment start dash state.
U+003E GREATER-THAN SIGN (>)
This is an abrupt-closing-of-empty-comment parse error. Switch to the data state. Emit the comment token.
Anything else
Reconsume in the comment state.
13.2.5.44 Comment start dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the comment end state
U+003E GREATER-THAN SIGN (>)
This is an abrupt-closing-of-empty-comment parse error. Switch to the data state. Emit the comment token.
EOF
This is an eof-in-comment parse error. Emit the comment token. Emit an end-of-file token.
Anything else
Append a U+002D HYPHEN-MINUS character (-) to the comment token's data. Reconsume in the comment state.
13.2.5.45 Comment state

Consume the next input character:

U+003C LESS-THAN SIGN (<)
Append the current input character to the comment token's data. Switch to the comment less-than sign state.
U+002D HYPHEN-MINUS (-)
Switch to the comment end dash state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the comment token's data.
EOF
This is an eof-in-comment parse error. Emit the comment token. Emit an end-of-file token.
Anything else
Append the current input character to the comment token's data.
13.2.5.46 注释小于号状态

消耗掉 下一个输入字符

U+0021 EXCLAMATION MARK (!)
当前输入字符 添加到注释标记的数据。 切换到 注释小于号感叹号状态
U+003C LESS-THAN SIGN (<)
当前输入字符 添加到注释标记的数据。
任何其他字符
注释状态 重新消耗它
13.2.5.47 注释小于号感叹号状态

使用掉 下一个输入字符

U+002D HYPHEN-MINUS (-)
切换到 注释小于号感叹号横线状态
任何其他情况
注释状态 重新消耗 该字符。
13.2.5.48 注释小于号感叹号横线状态

使用掉 下一个输入字符

U+002D HYPHEN-MINUS (-)
切换到 注释小于号感叹号横线横线状态
任何其他情况
注释结束横线状态 重新消耗 该字符。
13.2.5.49 Comment less-than sign bang dash dash state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
EOF
Reconsume in the comment end state.
Anything else
This is a nested-comment parse error. Reconsume in the comment end state.
13.2.5.50 Comment end dash state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Switch to the comment end state
EOF
This is an eof-in-comment parse error. Emit the comment token. Emit an end-of-file token.
Anything else
Append a U+002D HYPHEN-MINUS character (-) to the comment token's data. Reconsume in the comment state.
13.2.5.51 Comment end state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the comment token.
U+0021 EXCLAMATION MARK (!)
Switch to the comment end bang state.
U+002D HYPHEN-MINUS (-)
Append a U+002D HYPHEN-MINUS character (-) to the comment token's data.
EOF
This is an eof-in-comment parse error. Emit the comment token. Emit an end-of-file token.
Anything else
Append two U+002D HYPHEN-MINUS characters (-) to the comment token's data. Reconsume in the comment state.
13.2.5.52 Comment end bang state

Consume the next input character:

U+002D HYPHEN-MINUS (-)
Append two U+002D HYPHEN-MINUS characters (-) and a U+0021 EXCLAMATION MARK character (!) to the comment token's data. Switch to the comment end dash state.
U+003E GREATER-THAN SIGN (>)
This is an incorrectly-closed-comment parse error. Switch to the data state. Emit the comment token.
EOF
This is an eof-in-comment parse error. Emit the comment token. Emit an end-of-file token.
Anything else
Append two U+002D HYPHEN-MINUS characters (-) and a U+0021 EXCLAMATION MARK character (!) to the comment token's data. Reconsume in the comment state.
13.2.5.53 DOCTYPE state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the before DOCTYPE name state.
U+003E GREATER-THAN SIGN (>)
Reconsume in the before DOCTYPE name state.
EOF
This is an eof-in-doctype parse error. Create a new DOCTYPE token. Set its force-quirks flag to on. Emit the token. Emit an end-of-file token.
Anything else
This is a missing-whitespace-before-doctype-name parse error. Reconsume in the before DOCTYPE name state.
13.2.5.54 Before DOCTYPE name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
ASCII upper alpha
Create a new DOCTYPE token. Set the token's name to the lowercase version of the current input character (add 0x0020 to the character's code point). Switch to the DOCTYPE name state.
U+0000 NULL
This is an unexpected-null-character parse error. Create a new DOCTYPE token. Set the token's name to a U+FFFD REPLACEMENT CHARACTER character. Switch to the DOCTYPE name state.
U+003E GREATER-THAN SIGN (>)
This is a missing-doctype-name parse error. Create a new DOCTYPE token. Set its force-quirks flag to on. Switch to the data state. Emit the token.
EOF
This is an eof-in-doctype parse error. Create a new DOCTYPE token. Set its force-quirks flag to on. Emit the token. Emit an end-of-file token.
Anything else
Create a new DOCTYPE token. Set the token's name to the current input character. Switch to the DOCTYPE name state.
13.2.5.55 DOCTYPE name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the after DOCTYPE name state.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current DOCTYPE token.
ASCII upper alpha
Append the lowercase version of the current input character (add 0x0020 to the character's code point) to the current DOCTYPE token's name.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's name.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else
Append the current input character to the current DOCTYPE token's name.
13.2.5.56 After DOCTYPE name state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else

If the six characters starting from the current input character are an ASCII case-insensitive match for the word "PUBLIC", then consume those characters and switch to the after DOCTYPE public keyword state.

Otherwise, if the six characters starting from the current input character are an ASCII case-insensitive match for the word "SYSTEM", then consume those characters and switch to the after DOCTYPE system keyword state.

Otherwise, this is an invalid-character-sequence-after-doctype-name parse error. Set the DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.

13.2.5.57 After DOCTYPE public keyword state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the before DOCTYPE public identifier state.
U+0022 QUOTATION MARK (")
This is a missing-whitespace-after-doctype-public-keyword parse error. Set the DOCTYPE token's public identifier to the empty string (not missing), then switch to the DOCTYPE public identifier (double-quoted) state.
U+0027 APOSTROPHE (')
This is a missing-whitespace-after-doctype-public-keyword parse error. Set the DOCTYPE token's public identifier to the empty string (not missing), then switch to the DOCTYPE public identifier (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
This is a missing-doctype-public-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit that DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else
This is a missing-quote-before-doctype-public-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.
13.2.5.58 Before DOCTYPE public identifier state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+0022 QUOTATION MARK (")
Set the DOCTYPE token's public identifier to the empty string (not missing), then switch to the DOCTYPE public identifier (double-quoted) state.
U+0027 APOSTROPHE (')
Set the DOCTYPE token's public identifier to the empty string (not missing), then switch to the DOCTYPE public identifier (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
This is a missing-doctype-public-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit that DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else
This is a missing-quote-before-doctype-public-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.
13.2.5.59 DOCTYPE public identifier (double-quoted) state

Consume the next input character:

U+0022 QUOTATION MARK (")
Switch to the after DOCTYPE public identifier state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's public identifier.
U+003E GREATER-THAN SIGN (>)
This is an abrupt-doctype-public-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit that DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else
Append the current input character to the current DOCTYPE token's public identifier.
13.2.5.60 DOCTYPE public identifier (single-quoted) state

Consume the next input character:

U+0027 APOSTROPHE (')
Switch to the after DOCTYPE public identifier state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's public identifier.
U+003E GREATER-THAN SIGN (>)
This is an abrupt-doctype-public-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit that DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else
Append the current input character to the current DOCTYPE token's public identifier.
13.2.5.61 After DOCTYPE public identifier state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the between DOCTYPE public and system identifiers state.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current DOCTYPE token.
U+0022 QUOTATION MARK (")
This is a missing-whitespace-between-doctype-public-and-system-identifiers parse error. Set the DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (double-quoted) state.
U+0027 APOSTROPHE (')
This is a missing-whitespace-between-doctype-public-and-system-identifiers parse error. Set the DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (single-quoted) state.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else
This is a missing-quote-before-doctype-system-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.
13.2.5.62 Between DOCTYPE public and system identifiers state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current DOCTYPE token.
U+0022 QUOTATION MARK (")
Set the DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (double-quoted) state.
U+0027 APOSTROPHE (')
Set the DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (single-quoted) state.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else
This is a missing-quote-before-doctype-system-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.
13.2.5.63 After DOCTYPE system keyword state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Switch to the before DOCTYPE system identifier state.
U+0022 QUOTATION MARK (")
This is a missing-whitespace-after-doctype-system-keyword parse error. Set the DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (double-quoted) state.
U+0027 APOSTROPHE (')
This is a missing-whitespace-after-doctype-system-keyword parse error. Set the DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
This is a missing-doctype-system-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit that DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else
This is a missing-quote-before-doctype-system-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.
13.2.5.64 Before DOCTYPE system identifier state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+0022 QUOTATION MARK (")
Set the DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (double-quoted) state.
U+0027 APOSTROPHE (')
Set the DOCTYPE token's system identifier to the empty string (not missing), then switch to the DOCTYPE system identifier (single-quoted) state.
U+003E GREATER-THAN SIGN (>)
This is a missing-doctype-system-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit that DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else
This is a missing-quote-before-doctype-system-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Reconsume in the bogus DOCTYPE state.
13.2.5.65 DOCTYPE system identifier (double-quoted) state

Consume the next input character:

U+0022 QUOTATION MARK (")
Switch to the after DOCTYPE system identifier state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's system identifier.
U+003E GREATER-THAN SIGN (>)
This is an abrupt-doctype-system-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit that DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else
Append the current input character to the current DOCTYPE token's system identifier.
13.2.5.66 DOCTYPE system identifier (single-quoted) state

Consume the next input character:

U+0027 APOSTROPHE (')
Switch to the after DOCTYPE system identifier state.
U+0000 NULL
This is an unexpected-null-character parse error. Append a U+FFFD REPLACEMENT CHARACTER character to the current DOCTYPE token's system identifier.
U+003E GREATER-THAN SIGN (>)
This is an abrupt-doctype-system-identifier parse error. Set the DOCTYPE token's force-quirks flag to on. Switch to the data state. Emit that DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else
Append the current input character to the current DOCTYPE token's system identifier.
13.2.5.67 After DOCTYPE system identifier state

Consume the next input character:

U+0009 CHARACTER TABULATION (tab)
U+000A LINE FEED (LF)
U+000C FORM FEED (FF)
U+0020 SPACE
Ignore the character.
U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the current DOCTYPE token.
EOF
This is an eof-in-doctype parse error. Set the DOCTYPE token's force-quirks flag to on. Emit that DOCTYPE token. Emit an end-of-file token.
Anything else
This is an unexpected-character-after-doctype-system-identifier parse error. Reconsume in the bogus DOCTYPE state. (This does not set the DOCTYPE token's force-quirks flag to on.)
13.2.5.68 Bogus DOCTYPE state

Consume the next input character:

U+003E GREATER-THAN SIGN (>)
Switch to the data state. Emit the DOCTYPE token.
U+0000 NULL
This is an unexpected-null-character parse error. Ignore the character.
EOF
Emit the DOCTYPE token. Emit an end-of-file token.
Anything else
Ignore the character.
13.2.5.69 CDATA 部分状态

消耗掉 下一个输入字符

U+005D RIGHT SQUARE BRACKET (])
切换到 CDATA 部分括号状态
EOF
这是一个 eof-in-cdata 解析错误。发出一个 EOF 标记。
任何其他字符
当前输入字符 作为一个字符标记发出。

U+0000 NULL 字符在构造树的阶段,作为 in foreign content 插入模式的一部分进行处理。CDATA 部分只出现在这里。

13.2.5.70 CDATA 部分括号状态

使用掉 下一个输入字符

U+005D RIGHT SQUARE BRACKET (])
切换到 CDATA 部分结束状态
任何其他情况
发出一个 U+005D RIGHT SQUARE BRACKET 字符标记。 在 CDATA 部分状态 重新消耗 该字符。
13.2.5.71 CDATA 部分结束状态

使用掉 下一个输入字符

U+005D RIGHT SQUARE BRACKET (])
发出一个 U+005D RIGHT SQUARE BRACKET 字符标记。
U+003E GREATER-THAN SIGN character
切换到 数据状态
任何其他情况
发出两个 U+005D RIGHT SQUARE BRACKET 字符标记。 在 CDATA 部分状态 重新消耗 该字符。
13.2.5.72 Character reference state

Set the temporary buffer to the empty string. Append a U+0026 AMPERSAND (&) character to the temporary buffer. Consume the next input character:

ASCII alphanumeric
Reconsume in the named character reference state.
U+0023 NUMBER SIGN (#)
Append the current input character to the temporary buffer. Switch to the numeric character reference state.
Anything else
Flush code points consumed as a character reference. Reconsume in the return state.
13.2.5.73 Named character reference state

Consume the maximum number of characters possible, where the consumed characters are one of the identifiers in the first column of the named character references table. Append each character to the temporary buffer when it's consumed.

If there is a match

If the character reference was consumed as part of an attribute, and the last character matched is not a U+003B SEMICOLON character (;), and the next input character is either a U+003D EQUALS SIGN character (=) or an ASCII alphanumeric, then, for historical reasons, flush code points consumed as a character reference and switch to the return state.

Otherwise:

  1. If the last character matched is not a U+003B SEMICOLON character (;), then this is a missing-semicolon-after-character-reference parse error.

  2. Set the temporary buffer to the empty string. Append one or two characters corresponding to the character reference name (as given by the second column of the named character references table) to the temporary buffer.

  3. Flush code points consumed as a character reference. Switch to the return state.
Otherwise
Flush code points consumed as a character reference. Switch to the ambiguous ampersand state.

If the markup contains (not in an attribute) the string I'm &notit; I tell you, the character reference is parsed as "not", as in, I'm ¬it; I tell you (and this is a parse error). But if the markup was I'm &notin; I tell you, the character reference would be parsed as "notin;", resulting in I'm ∉ I tell you (and no parse error).

However, if the markup contains the string I'm &notit; I tell you in an attribute, no character reference is parsed and string remains intact (and there is no parse error).

13.2.5.74 Ambiguous ampersand state

Consume the next input character:

ASCII alphanumeric
If the character reference was consumed as part of an attribute, then append the current input character to the current attribute's value. Otherwise, emit the current input character as a character token.
U+003B SEMICOLON (;)
This is an unknown-named-character-reference parse error. Reconsume in the return state.
Anything else
Reconsume in the return state.
13.2.5.75 数字字符引用状态

设置 字符引用代码 为 zero (0)。

消耗掉 下一个输入字符

U+0078 LATIN SMALL LETTER X
U+0058 LATIN CAPITAL LETTER X
当前输入字符 追加到 temporary buffer。 切换到 十六进制字符引用开始状态
任何其他情况
十进制字符引用开始状态 重新消耗 该字符。
13.2.5.76 Hexadecimal character reference start state

Consume the next input character:

ASCII hex digit
Reconsume in the hexadecimal character reference state.
Anything else
This is an absence-of-digits-in-numeric-character-reference parse error. Flush code points consumed as a character reference. Reconsume in the return state.
13.2.5.77 Decimal character reference start state

Consume the next input character:

ASCII digit
Reconsume in the decimal character reference state.
Anything else
This is an absence-of-digits-in-numeric-character-reference parse error. Flush code points consumed as a character reference. Reconsume in the return state.
13.2.5.78 Hexadecimal character reference state

Consume the next input character:

ASCII digit
Multiply the character reference code by 16. Add a numeric version of the current input character (subtract 0x0030 from the character's code point) to the character reference code.
ASCII upper hex digit
Multiply the character reference code by 16. Add a numeric version of the current input character as a hexadecimal digit (subtract 0x0037 from the character's code point) to the character reference code.
ASCII lower hex digit
Multiply the character reference code by 16. Add a numeric version of the current input character as a hexadecimal digit (subtract 0x0057 from the character's code point) to the character reference code.
U+003B SEMICOLON
Switch to the numeric character reference end state.
Anything else
This is a missing-semicolon-after-character-reference parse error. Reconsume in the numeric character reference end state.
13.2.5.79 Decimal character reference state

Consume the next input character:

ASCII digit
Multiply the character reference code by 10. Add a numeric version of the current input character (subtract 0x0030 from the character's code point) to the character reference code.
U+003B SEMICOLON
Switch to the numeric character reference end state.
Anything else
This is a missing-semicolon-after-character-reference parse error. Reconsume in the numeric character reference end state.
13.2.5.80 数字字符引用结束状态

检查 字符引用代码

temporary buffer 设为空字符串。 给 temporary buffer 追加一个等于 字符引用代码 的代码点。 把消耗掉的代码点输出为字符引用。 切换到 return state

13.2.6 Tree construction

The input to the tree construction stage is a sequence of tokens from the tokenization stage. The tree construction stage is associated with a DOM Document object when a parser is created. The "output" of this stage consists of dynamically modifying or extending that document's DOM tree.

This specification does not define when an interactive user agent has to render the Document so that it is available to the user, or when it has to begin accepting user input.


As each token is emitted from the tokenizer, the user agent must follow the appropriate steps from the following list, known as the tree construction dispatcher:

If the stack of open elements is empty
If the adjusted current node is an element in the HTML namespace
If the adjusted current node is a MathML text integration point and the token is a start tag whose tag name is neither "mglyph" nor "malignmark"
If the adjusted current node is a MathML text integration point and the token is a character token
If the adjusted current node is a MathML annotation-xml element and the token is a start tag whose tag name is "svg"
If the adjusted current node is an HTML integration point and the token is a start tag
If the adjusted current node is an HTML integration point and the token is a character token
If the token is an end-of-file token
Process the token according to the rules given in the section corresponding to the current insertion mode in HTML content.
Otherwise
Process the token according to the rules given in the section for parsing tokens in foreign content.

The next token is the token that is about to be processed by the tree construction dispatcher (even if the token is subsequently just ignored).

A node is a MathML text integration point if it is one of the following elements:

A node is an HTML integration point if it is one of the following elements:

If the node in question is the context element passed to the HTML fragment parsing algorithm, then the start tag token for that element is the "fake" token created during by that HTML fragment parsing algorithm.


Not all of the tag names mentioned below are conformant tag names in this specification; many are included to handle legacy content. They still form part of the algorithm that implementations are required to implement to claim conformance.

The algorithm described below places no limit on the depth of the DOM tree generated, or on the length of tag names, attribute names, attribute values, Text nodes, etc. While implementers are encouraged to avoid arbitrary limits, it is recognized that practical concerns will likely force user agents to impose nesting depth constraints.

13.2.6.1 Creating and inserting nodes

While the parser is processing a token, it can enable or disable foster parenting. This affects the following algorithm.

The appropriate place for inserting a node, optionally using a particular override target, is the position in an element returned by running the following steps:

  1. If there was an override target specified, then let target be the override target.

    Otherwise, let target be the current node.

  2. Determine the adjusted insertion location using the first matching steps from the following list:

    If foster parenting is enabled and target is a table, tbody, tfoot, thead, or tr element

    Foster parenting happens when content is misnested in tables.

    Run these substeps:

    1. Let last template be the last template element in the stack of open elements, if any.

    2. Let last table be the last table element in the stack of open elements, if any.

    3. If there is a last template and either there is no last table, or there is one, but last template is lower (more recently added) than last table in the stack of open elements, then: let adjusted insertion location be inside last template's template contents, after its last child (if any), and abort these steps.

    4. If there is no last table, then let adjusted insertion location be inside the first element in the stack of open elements (the html element), after its last child (if any), and abort these steps. (fragment case)

    5. If last table has a parent node, then let adjusted insertion location be inside last table's parent node, immediately before last table, and abort these steps.

    6. Let previous element be the element immediately above last table in the stack of open elements.

    7. Let adjusted insertion location be inside previous element, after its last child (if any).

    These steps are involved in part because it's possible for elements, the table element in this case in particular, to have been moved by a script around in the DOM, or indeed removed from the DOM entirely, after the element was inserted by the parser.

    Otherwise

    Let adjusted insertion location be inside target, after its last child (if any).

  3. If the adjusted insertion location is inside a template element, let it instead be inside the template element's template contents, after its last child (if any).

  4. Return the adjusted insertion location.


When the steps below require the UA to create an element for a token in a particular given namespace and with a particular intended parent, the UA must run the following steps:

  1. Let document be intended parent's node document.

  2. Let local name be the tag name of the token.

  3. Let is be the value of the "is" attribute in the given token, if such an attribute exists, or null otherwise.

  4. Let definition be the result of looking up a custom element definition given document, given namespace, local name, and is.

  5. If definition is non-null and the parser was not created as part of the HTML fragment parsing algorithm, then let will execute script be true. Otherwise, let it be false.

  6. If will execute script is true, then:

    1. Increment document's throw-on-dynamic-markup-insertion counter.

    2. If the JavaScript execution context stack is empty, then perform a microtask checkpoint.

    3. Push a new element queue onto document's relevant agent's custom element reactions stack.

  7. Let element be the result of creating an element given document, localName, given namespace, null, and is. If will execute script is true, set the synchronous custom elements flag; otherwise, leave it unset.

    This will cause custom element constructors to run, if will execute script is true. However, since we incremented the throw-on-dynamic-markup-insertion counter, this cannot cause new characters to be inserted into the tokenizer, or the document to be blown away.

  8. Append each attribute in the given token to element.

    This can enqueue a custom element callback reaction for the attributeChangedCallback, which might run immediately (in the next step).

    Even though the is attribute governs the creation of a customized built-in element, it is not present during the execution of the relevant custom element constructor; it is appended in this step, along with all other attributes.

  9. If will execute script is true, then:

    1. Let queue be the result of popping from document's relevant agent's custom element reactions stack. (This will be the same element queue as was pushed above.)

    2. Invoke custom element reactions in queue.

    3. Decrement document's throw-on-dynamic-markup-insertion counter.

  10. If element has an xmlns attribute in the XMLNS namespace whose value is not exactly the same as the element's namespace, that is a parse error. Similarly, if element has an xmlns:xlink attribute in the XMLNS namespace whose value is not the XLink Namespace, that is a parse error.

  11. If element is a resettable element, invoke its reset algorithm. (This initializes the element's value and checkedness based on the element's attributes.)

  12. If element is a form-associated element and not a form-associated custom element, the form element pointer is not null, there is no template element on the stack of open elements, element is either not listed or doesn't have a form attribute, and the intended parent is in the same tree as the element pointed to by the form element pointer, then associate element with the form element pointed to by the form element pointer and set element's parser inserted flag.

  13. Return element.


When the steps below require the user agent to insert a foreign element for a token in a given namespace, the user agent must run these steps:

  1. Let the adjusted insertion location be the appropriate place for inserting a node.

  2. Let element be the result of creating an element for the token in the given namespace, with the intended parent being the element in which the adjusted insertion location finds itself.

  3. If it is possible to insert element at the adjusted insertion location, then:

    1. If the parser was not created as part of the HTML fragment parsing algorithm, then push a new element queue onto element's relevant agent's custom element reactions stack.

    2. Insert element at the adjusted insertion location.

    3. If the parser was not created as part of the HTML fragment parsing algorithm, then pop the element queue from element's relevant agent's custom element reactions stack, and invoke custom element reactions in that queue.

    If the adjusted insertion location cannot accept more elements, e.g. because it's a Document that already has an element child, then element is dropped on the floor.

  4. Push element onto the stack of open elements so that it is the new current node.

  5. Return element.

When the steps below require the user agent to insert an HTML element for a token, the user agent must insert a foreign element for the token, in the HTML namespace.


When the steps below require the user agent to adjust MathML attributes for a token, then, if the token has an attribute named definitionurl, change its name to definitionURL (note the case difference).

When the steps below require the user agent to adjust SVG attributes for a token, then, for each attribute on the token whose attribute name is one of the ones in the first column of the following table, change the attribute's name to the name given in the corresponding cell in the second column. (This fixes the case of SVG attributes that are not all lowercase.)

Attribute name on token Attribute name on element
attributename attributeName
attributetype attributeType
basefrequency baseFrequency
baseprofile baseProfile
calcmode calcMode
clippathunits clipPathUnits
diffuseconstant diffuseConstant
edgemode edgeMode
filterunits filterUnits
glyphref glyphRef
gradienttransform gradientTransform
gradientunits gradientUnits
kernelmatrix kernelMatrix
kernelunitlength kernelUnitLength
keypoints keyPoints
keysplines keySplines
keytimes keyTimes
lengthadjust lengthAdjust
limitingconeangle limitingConeAngle
markerheight markerHeight
markerunits markerUnits
markerwidth markerWidth
maskcontentunits maskContentUnits
maskunits maskUnits
numoctaves numOctaves
pathlength pathLength
patterncontentunits patternContentUnits
patterntransform patternTransform
patternunits patternUnits
pointsatx pointsAtX
pointsaty pointsAtY
pointsatz pointsAtZ
preservealpha preserveAlpha
preserveaspectratio preserveAspectRatio
primitiveunits primitiveUnits
refx refX
refy refY
repeatcount repeatCount
repeatdur repeatDur
requiredextensions requiredExtensions
requiredfeatures requiredFeatures
specularconstant specularConstant
specularexponent specularExponent
spreadmethod spreadMethod
startoffset startOffset
stddeviation stdDeviation
stitchtiles stitchTiles
surfacescale surfaceScale
systemlanguage systemLanguage
tablevalues tableValues
targetx targetX
targety targetY
textlength textLength
viewbox viewBox
viewtarget viewTarget
xchannelselector xChannelSelector
ychannelselector yChannelSelector
zoomandpan zoomAndPan

When the steps below require the user agent to adjust foreign attributes for a token, then, if any of the attributes on the token match the strings given in the first column of the following table, let the attribute be a namespaced attribute, with the prefix being the string given in the corresponding cell in the second column, the local name being the string given in the corresponding cell in the third column, and the namespace being the namespace given in the corresponding cell in the fourth column. (This fixes the use of namespaced attributes, in particular lang attributes in the XML namespace.)

Attribute name Prefix Local name Namespace
xlink:actuate xlink actuate XLink namespace
xlink:arcrole xlink arcrole XLink namespace
xlink:href xlink href XLink namespace
xlink:role xlink role XLink namespace
xlink:show xlink show XLink namespace
xlink:title xlink title XLink namespace
xlink:type xlink type XLink namespace
xml:lang xml lang XML namespace
xml:space xml space XML namespace
xmlns (none) xmlns XMLNS namespace
xmlns:xlink xmlns xlink XMLNS namespace

When the steps below require the user agent to insert a character while processing a token, the user agent must run the following steps:

  1. Let data be the characters passed to the algorithm, or, if no characters were explicitly specified, the character of the character token being processed.

  2. Let the adjusted insertion location be the appropriate place for inserting a node.

  3. If the adjusted insertion location is in a Document node, then return.

    The DOM will not let Document nodes have Text node children, so they are dropped on the floor.

  4. If there is a Text node immediately before the adjusted insertion location, then append data to that Text node's data.

    Otherwise, create a new Text node whose data is data and whose node document is the same as that of the element in which the adjusted insertion location finds itself, and insert the newly created node at the adjusted insertion location.

Here are some sample inputs to the parser and the corresponding number of Text nodes that they result in, assuming a user agent that executes scripts.

Input Number of Text nodes
A<script>
var script = document.getElementsByTagName('script')[0];
document.body.removeChild(script);
</script>B
One Text node in the document, containing "AB".
A<script>
var text = document.createTextNode('B');
document.body.appendChild(text);
</script>C
Three Text nodes; "A" before the script, the script's contents, and "BC" after the script (the parser appends to the Text node created by the script).
A<script>
var text = document.getElementsByTagName('script')[0].firstChild;
text.data = 'B';
document.body.appendChild(text);
</script>C
Two adjacent Text nodes in the document, containing "A" and "BC".
A<table>B<tr>C</tr>D</table>
One Text node before the table, containing "ABCD". (This is caused by foster parenting.)
A<table><tr> B</tr> C</table>
One Text node before the table, containing "A B C" (A-space-B-space-C). (This is caused by foster parenting.)
A<table><tr> B</tr> </em>C</table>
One Text node before the table, containing "A BC" (A-space-B-C), and one Text node inside the table (as a child of a tbody) with a single space character. (Space characters separated from non-space characters by non-character tokens are not affected by foster parenting, even if those other tokens then get ignored.)

When the steps below require the user agent to insert a comment while processing a comment token, optionally with an explicitly insertion position position, the user agent must run the following steps:

  1. Let data be the data given in the comment token being processed.

  2. If position was specified, then let the adjusted insertion location be position. Otherwise, let adjusted insertion location be the appropriate place for inserting a node.

  3. Create a Comment node whose data attribute is set to data and whose node document is the same as that of the node in which the adjusted insertion location finds itself.

  4. Insert the newly created node at the adjusted insertion location.


DOM mutation events must not fire for changes caused by the UA parsing the document. This includes the parsing of any content inserted using document.write() and document.writeln() calls. [UIEVENTS]

However, mutation observers do fire, as required by DOM .

13.2.6.2 解析只包含文本的元素

通用原始文本元素解析算法通用 RCDATA 元素解析算法 包括以下步骤。这些算法只会被开始标签的标记调用。

  1. 为该标记 插入一个 HTML 元素

  2. 如果被调用的是 通用原始文本元素解析算法, 把 tokenizer 切换到 RAWTEXT 状态; 否则,如果被调用的是 通用 RCDATA 元素解析算法, 把 tokenizer 切换到 RCDATA 状态

  3. 原始插入模式 为当前 插入模式

  4. 然后,把 插入模式 切换到 "text"。

13.2.6.3 Closing elements that have implied end tags

When the steps below require the UA to generate implied end tags, then, while the current node is a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, or an rtc element, the UA must pop the current node off the stack of open elements.

If a step requires the UA to generate implied end tags but lists an element to exclude from the process, then the UA must perform the above steps as if that element was not in the above list.

When the steps below require the UA to generate all implied end tags thoroughly, then, while the current node is a caption element, a colgroup element, a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, or a tr element, the UA must pop the current node off the stack of open elements.

13.2.6.4 解析 HTML 内容中的标记的规则
13.2.6.4.1 "initial" 插入模式

当用户代理应用 "initial" 插入模式 的规则时,用户代理必须按以下规则处理标记:

如果该标记是一个 U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), 或 U+0020 SPACE 字符标记。

忽略这个标记。

注释标记

Document 对象上 插入注释 作为最后一个子节点。

DOCTYPE 标记

如果这个 DOCTYPE 标记的名字不是字符串 "html" 的大小写敏感匹配, 或者该标记的系统标识符不存在或者大小写敏感地匹配字符串 "about:legacy-compat", 那么这是一个解析错误 解析错误

Document 节点上追加一个 DocumentType 节点, 其 name 属性设为 DOCTYPE 标记给出的名字,如果没有就设为空字符串; publicId 属性设为 DOCTYPE 标记给出的共有标识符,如果没有就设为空字符串; systemId 属性设为 DOCTYPE 标记给出的系统标识符,如果没有就设为空字符串; DocumentType 对象的其他属性适当地设为 null 或者空列表。 把 DocumentType 节点关联到 Document 对象, 这样它就会作为 Document 对象的 doctype 属性值返回。

如果该文档 不是 一个 iframe srcdoc 文档, 且 DOCTYPE 标记匹配以下一个条件,就把 Document 设为 怪异模式

否则,如果该文档 不是 一个 iframe srcdoc 文档, 且 DOCTYPE 标记匹配以下任一条件,那么设置 Document受限的怪异模式

系统标识符和公共标识符字符串与上述列表给出的值进行比较时,必须采用 ASCII 大小写不敏感 的方式。 上述条件中,值为空字符串的系统标识符不被认为缺失。

然后将 插入模式 设置为 "before html"。

任何其他情况

如果该文档 不是 一个 iframe srcdoc 文档, 那么这是一个 解析错误; 把 Document 设置为 怪异模式

任何情况下,都把 插入模式 设置为 "before html",然后开始重新处理标记。

13.2.6.4.2 "before html" 插入模式

当用户代理应用 "before html" 插入模式 的规则时,用户代理必须按以下规则处理标记:

DOCTYPE 标记

解析错误。 忽略该标记。

注释标记

Document 最后 插入注释 作为最后一个子节点。

字符标记 U+0009 CHARACTER TABULATION,U+000A LINE FEED (LF),U+000C FORM FEED (FF),U+000D CARRIAGE RETURN (CR),或 U+0020 SPACE

忽略该标记。

名为 "html" 的开始标签

HTML 命名空间 为该标记创建一个元素, 其目标父元素是 Document。把它添加到 Document 对象。 把该元素放到 打开元素栈

如果 Document 正在作为 浏览环境导航 的一步进行载入,执行这些步骤:

  1. 如果为该文档的 URL 执行 匹配 service worker 注册 的结果不是 null,执行 应用缓存选择算法, 把 Document 对象传给它,不带 manifest。

  2. 否则,执行这些子步骤:

    1. 如果新创建的元素有一个 manifest 属性且值为非空字符串,就相对于新创建的文档的 节点文档 解析 该属性的值, 如果成功就执行 应用缓存选择算法, 传参包括 Document 对象以及设置 exclude fragment 标志 的情况下对 结果 URL 记录 应用 URL 序列化 算法的结果。

    2. 否则,执行 应用缓存选择算法, 把 Document 对象传给它,不带 manifest。

插入模式 切换为 "before head"。

名为 "head","body","html","br" 的结束标签

执行下面“任何其他标记”的步骤。

任何其他结束标签

解析错误。 忽略该标记。

任何其他标记

创建一个 html 元素,其 节点文档Document 对象。 把它添加到 Document 对象。把该元素放到 打开元素栈

如果 Document 正在作为 浏览环境导航 的一步进行载入,则执行 应用缓存选择算法,不带 manifest 并传入 Document 对象。

插入模式 切换到 "before head",然后重新处理该标记。

document 元素 最终可能被从 Document 对象移除, 比如可能是脚本移除了它;这种情况下什么都不会发生,会按照下一部分描述的规则继续把内容添加到对应的节点。

13.2.6.4.3 "before head" 插入模式

当用户代理应用 "before head" 插入模式 的规则时,用户代理必须按以下规则处理标记:

U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), 或 U+0020 SPACE 字符标记

忽略该标记。

注释标记

插入注释

DOCTYPE 标记

解析错误。 忽略该标记。

名为 "html" 的开始标签

使用 "in body" 插入模式 处理该标记。

名为 "head" 的开始标签

为该标记 插入一个 HTML 元素

head 元素指针 设为刚创建的 head 元素。

插入模式 切换到 "in head"。

名为 "head", "body", "html", "br" 的结束标签

执行下面“其他情况”描述的步骤。

任何其他结束标签

解析错误。 忽略该标记。

其他情况

为 "head" 开始标签标记 插入一个 HTML 元素,不设任何属性。

head 元素指针 设为刚创建的 head 元素。

插入模式 设为 "in head"。

重新处理当前标记。

13.2.6.4.4 The "in head" insertion mode

When the user agent is to apply the rules for the "in head" insertion mode, the user agent must handle the token as follows:

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Insert the character.

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "html"

Process the token using the rules for the "in body" insertion mode.

A start tag whose tag name is one of: "base", "basefont", "bgsound", "link"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

A start tag whose tag name is "meta"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

If the element has a charset attribute, and getting an encoding from its value results in an encoding, and the confidence is currently tentative, then change the encoding to the resulting encoding.

Otherwise, if the element has an http-equiv attribute whose value is an ASCII case-insensitive match for the string "Content-Type", and the element has a content attribute, and applying the algorithm for extracting a character encoding from a meta element to that attribute's value returns an encoding, and the confidence is currently tentative, then change the encoding to the extracted encoding.

A start tag whose tag name is "title"

Follow the generic RCDATA element parsing algorithm.

A start tag whose tag name is "noscript", if the scripting flag is enabled
A start tag whose tag name is one of: "noframes", "style"

Follow the generic raw text element parsing algorithm.

A start tag whose tag name is "noscript", if the scripting flag is disabled

Insert an HTML element for the token.

Switch the insertion mode to "in head noscript".

A start tag whose tag name is "script"

Run these steps:

  1. Let the adjusted insertion location be the appropriate place for inserting a node.

  2. Create an element for the token in the HTML namespace, with the intended parent being the element in which the adjusted insertion location finds itself.

  3. Set the element's parser document to the Document, and unset the element's "non-blocking" flag.

    This ensures that, if the script is external, any document.write() calls in the script will execute in-line, instead of blowing the document away, as would happen in most other cases. It also prevents the script from executing until the end tag is seen.

  4. If the parser was created as part of the HTML fragment parsing algorithm, then mark the script element as "already started". (fragment case)

  5. If the parser was invoked via the document.write() or document.writeln() methods, then optionally mark the script element as "already started". (For example, the user agent might use this clause to prevent execution of cross-origin scripts inserted via document.write() under slow network conditions, or when the page has already taken a long time to load.)

  6. Insert the newly created element at the adjusted insertion location.

  7. Push the element onto the stack of open elements so that it is the new current node.

  8. Switch the tokenizer to the script data state.

  9. Let the original insertion mode be the current insertion mode.

  10. Switch the insertion mode to "text".

An end tag whose tag name is "head"

Pop the current node (which will be the head element) off the stack of open elements.

Switch the insertion mode to "after head".

An end tag whose tag name is one of: "body", "html", "br"

Act as described in the "anything else" entry below.

A start tag whose tag name is "template"

Insert an HTML element for the token.

Insert a marker at the end of the list of active formatting elements.

Set the frameset-ok flag to "not ok".

Switch the insertion mode to "in template".

Push "in template" onto the stack of template insertion modes so that it is the new current template insertion mode.

An end tag whose tag name is "template"

If there is no template element on the stack of open elements, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate all implied end tags thoroughly.

  2. If the current node is not a template element, then this is a parse error.

  3. Pop elements from the stack of open elements until a template element has been popped from the stack.

  4. Clear the list of active formatting elements up to the last marker.
  5. Pop the current template insertion mode off the stack of template insertion modes.

  6. Reset the insertion mode appropriately.

A start tag whose tag name is "head"
Any other end tag

Parse error. Ignore the token.

Anything else

Pop the current node (which will be the head element) off the stack of open elements.

Switch the insertion mode to "after head".

Reprocess the token.

13.2.6.4.5 "in head noscript" 插入模式

当用户代理应用 "in head noscript" 插入模式 的规则时,用户代理必须按以下规则处理标记:

DOCTYPE 标记

解析错误。忽略该标记。

名为 "html" 的开始标签

使用 "in body" 插入模式 处理该标记。

名为 "noscript" 的结束标签

Pop the 当前节点 (which will be a noscript element) from the 打开元素栈; the new 当前节点 will be a head element.

当前节点(是一个 noscript 元素) 从 打开元素栈 弹出, 新的 当前节点 会是一个 head 元素。

插入模式 切换到 "in head"。

字符标记 U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), 或 U+0020 SPACE
注释标记
名为 "basefont", "bgsound", "link", "meta", "noframes", "style" 的开始标签

使用 "in head" 插入模式 处理该标记。

名为 "br" 的结束标签

执行下面“任何其他情况”所描述的步骤。

名为 "head", "noscript" 的开始标签
任何其他结束标签

解析错误。忽略该标记。

任何其他情况

解析错误.

当前节点(是一个 noscript 元素) 从 打开元素栈 弹出, 新的 当前节点 会是一个 head 元素。

插入模式 切换到 "in head"。

重新处理该标记。

13.2.6.4.6 "after head" 插入模式

当用户代理应用 "after head" 插入模式 的规则时,用户代理必须按以下规则处理标记:

字符标记 U+0009 CHARACTER TABULATION,U+000A LINE FEED (LF),U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR) 或 U+0020 SPACE

插入一个字符

注释标记

插入注释

DOCTYPE 标记

解析错误。 忽略该标记。

名为 "html" 的开始标签

使用 "in body" 插入模式 的规则处理该标记。

名为 "body" 的开始标签

为该标记 插入一个 HTML 元素

设置 frameset-ok 标志 为 "not ok"。

插入模式 切换到 "in body"。

名为 "frameset" 的开始标签

插入一个 HTML 元素 为该标记。

插入模式 切换到 "in frameset"。

名为 "base","basefont","bgsound","link","meta", "noframes","script","style","template","title" 的开始标签

解析错误

head 元素指针 指向的那个元素压入 打开元素栈

使用 "in head" 插入模式 的规则处理该标记。

head 元素指针 指向的元素从 打开元素栈 移除。 (这时它可能不是 当前节点

head 元素指针 这时不会是 null。

名为 "template" 的结束标签

使用 "in head" 插入模式 的规则处理该标记。

名为 "body","html","br" 的结束标签

执行下面 "任何其他情况" 的步骤。

名为 "head" 的开始标签
任何其他结束标签

解析错误。忽略该标记。

任何其他情况

为 "body" 开始标签标记 插入一个 HTML 元素,不设任何属性。

插入模式 切换到 "in body"。

重新处理当前标记。

13.2.6.4.7 The "in body" insertion mode

When the user agent is to apply the rules for the "in body" insertion mode, the user agent must handle the token as follows:

A character token that is U+0000 NULL

Parse error. Ignore the token.

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Reconstruct the active formatting elements, if any.

Insert the token's character.

Any other character token

Reconstruct the active formatting elements, if any.

Insert the token's character.

Set the frameset-ok flag to "not ok".

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is "html"

Parse error.

If there is a template element on the stack of open elements, then ignore the token.

Otherwise, for each attribute on the token, check to see if the attribute is already present on the top element of the stack of open elements. If it is not, add the attribute and its corresponding value to that element.

A start tag whose tag name is one of: "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "template", "title"
An end tag whose tag name is "template"

Process the token using the rules for the "in head" insertion mode.

A start tag whose tag name is "body"

Parse error.

If the second element on the stack of open elements is not a body element, if the stack of open elements has only one node on it, or if there is a template element on the stack of open elements, then ignore the token. (fragment case)

Otherwise, set the frameset-ok flag to "not ok"; then, for each attribute on the token, check to see if the attribute is already present on the body element (the second element) on the stack of open elements, and if it is not, add the attribute and its corresponding value to that element.

A start tag whose tag name is "frameset"

Parse error.

If the stack of open elements has only one node on it, or if the second element on the stack of open elements is not a body element, then ignore the token. (fragment case)

If the frameset-ok flag is set to "not ok", ignore the token.

Otherwise, run the following steps:

  1. Remove the second element on the stack of open elements from its parent node, if it has one.

  2. Pop all the nodes from the bottom of the stack of open elements, from the current node up to, but not including, the root html element.

  3. Insert an HTML element for the token.

  4. Switch the insertion mode to "in frameset".

An end-of-file token

If the stack of template insertion modes is not empty, then process the token using the rules for the "in template" insertion mode.

Otherwise, follow these steps:

  1. If there is a node in the stack of open elements that is not either a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, a tr element, the body element, or the html element, then this is a parse error.

  2. Stop parsing.

An end tag whose tag name is "body"

If the stack of open elements does not have a body element in scope, this is a parse error; ignore the token.

Otherwise, if there is a node in the stack of open elements that is not either a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, a tr element, the body element, or the html element, then this is a parse error.

Switch the insertion mode to "after body".

An end tag whose tag name is "html"

If the stack of open elements does not have a body element in scope, this is a parse error; ignore the token.

Otherwise, if there is a node in the stack of open elements that is not either a dd element, a dt element, an li element, an optgroup element, an option element, a p element, an rb element, an rp element, an rt element, an rtc element, a tbody element, a td element, a tfoot element, a th element, a thead element, a tr element, the body element, or the html element, then this is a parse error.

Switch the insertion mode to "after body".

Reprocess the token.

A start tag whose tag name is one of: "address", "article", "aside", "blockquote", "center", "details", "dialog", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "main", "menu", "nav", "ol", "p", "section", "summary", "ul"

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token.

A start tag whose tag name is one of: "h1", "h2", "h3", "h4", "h5", "h6"

If the stack of open elements has a p element in button scope, then close a p element.

If the current node is an HTML element whose tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then this is a parse error; pop the current node off the stack of open elements.

Insert an HTML element for the token.

A start tag whose tag name is one of: "pre", "listing"

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token.

If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of pre blocks are ignored as an authoring convenience.)

Set the frameset-ok flag to "not ok".

A start tag whose tag name is "form"

If the form element pointer is not null, and there is no template element on the stack of open elements, then this is a parse error; ignore the token.

Otherwise:

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token, and, if there is no template element on the stack of open elements, set the form element pointer to point to the element created.

A start tag whose tag name is "li"

Run these steps:

  1. Set the frameset-ok flag to "not ok".

  2. Initialize node to be the current node (the bottommost node of the stack).

  3. Loop: If node is an li element, then run these substeps:

    1. Generate implied end tags, except for li elements.

    2. If the current node is not an li element, then this is a parse error.

    3. Pop elements from the stack of open elements until an li element has been popped from the stack.

    4. Jump to the step labeled done below.

  4. If node is in the special category, but is not an address, div, or p element, then jump to the step labeled done below.

  5. Otherwise, set node to the previous entry in the stack of open elements and return to the step labeled loop.

  6. Done: If the stack of open elements has a p element in button scope, then close a p element.

  7. Finally, insert an HTML element for the token.

A start tag whose tag name is one of: "dd", "dt"

Run these steps:

  1. Set the frameset-ok flag to "not ok".

  2. Initialize node to be the current node (the bottommost node of the stack).

  3. Loop: If node is a dd element, then run these substeps:

    1. Generate implied end tags, except for dd elements.

    2. If the current node is not a dd element, then this is a parse error.

    3. Pop elements from the stack of open elements until a dd element has been popped from the stack.

    4. Jump to the step labeled done below.

  4. If node is a dt element, then run these substeps:

    1. Generate implied end tags, except for dt elements.

    2. If the current node is not a dt element, then this is a parse error.

    3. Pop elements from the stack of open elements until a dt element has been popped from the stack.

    4. Jump to the step labeled done below.

  5. If node is in the special category, but is not an address, div, or p element, then jump to the step labeled done below.

  6. Otherwise, set node to the previous entry in the stack of open elements and return to the step labeled loop.

  7. Done: If the stack of open elements has a p element in button scope, then close a p element.

  8. Finally, insert an HTML element for the token.

A start tag whose tag name is "plaintext"

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token.

Switch the tokenizer to the PLAINTEXT state.

Once a start tag with the tag name "plaintext" has been seen, that will be the last token ever seen other than character tokens (and the end-of-file token), because there is no way to switch out of the PLAINTEXT state.

A start tag whose tag name is "button"
  1. If the stack of open elements has a button element in scope, then run these substeps:

    1. Parse error.

    2. Generate implied end tags.

    3. Pop elements from the stack of open elements until a button element has been popped from the stack.

  2. Reconstruct the active formatting elements, if any.

  3. Insert an HTML element for the token.

  4. Set the frameset-ok flag to "not ok".

An end tag whose tag name is one of: "address", "article", "aside", "blockquote", "button", "center", "details", "dialog", "dir", "div", "dl", "fieldset", "figcaption", "figure", "footer", "header", "hgroup", "listing", "main", "menu", "nav", "ol", "pre", "section", "summary", "ul"

If the stack of open elements does not have an element in scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags.

  2. If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.

  3. Pop elements from the stack of open elements until an HTML element with the same tag name as the token has been popped from the stack.

An end tag whose tag name is "form"

If there is no template element on the stack of open elements, then run these substeps:

  1. Let node be the element that the form element pointer is set to, or null if it is not set to an element.

  2. Set the form element pointer to null.

  3. If node is null or if the stack of open elements does not have node in scope, then this is a parse error; return and ignore the token.

  4. Generate implied end tags.

  5. If the current node is not node, then this is a parse error.

  6. Remove node from the stack of open elements.

If there is a template element on the stack of open elements, then run these substeps instead:

  1. If the stack of open elements does not have a form element in scope, then this is a parse error; return and ignore the token.

  2. Generate implied end tags.

  3. If the current node is not a form element, then this is a parse error.

  4. Pop elements from the stack of open elements until a form element has been popped from the stack.

An end tag whose tag name is "p"

If the stack of open elements does not have a p element in button scope, then this is a parse error; insert an HTML element for a "p" start tag token with no attributes.

Close a p element.

An end tag whose tag name is "li"

If the stack of open elements does not have an li element in list item scope, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags, except for li elements.

  2. If the current node is not an li element, then this is a parse error.

  3. Pop elements from the stack of open elements until an li element has been popped from the stack.

An end tag whose tag name is one of: "dd", "dt"

If the stack of open elements does not have an element in scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags, except for HTML elements with the same tag name as the token.

  2. If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.

  3. Pop elements from the stack of open elements until an HTML element with the same tag name as the token has been popped from the stack.

An end tag whose tag name is one of: "h1", "h2", "h3", "h4", "h5", "h6"

If the stack of open elements does not have an element in scope that is an HTML element and whose tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6", then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags.

  2. If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.

  3. Pop elements from the stack of open elements until an HTML element whose tag name is one of "h1", "h2", "h3", "h4", "h5", or "h6" has been popped from the stack.

An end tag whose tag name is "sarcasm"

Take a deep breath, then act as described in the "any other end tag" entry below.

A start tag whose tag name is "a"

If the list of active formatting elements contains an a element between the end of the list and the last marker on the list (or the start of the list if there is no marker on the list), then this is a parse error; run the adoption agency algorithm for the token, then remove that element from the list of active formatting elements and the stack of open elements if the adoption agency algorithm didn't already remove it (it might not have if the element is not in table scope).

In the non-conforming stream <a href="a">a<table><a href="b">b</table>x, the first a element would be closed upon seeing the second one, and the "x" character would be inside a link to "b", not to "a". This is despite the fact that the outer a element is not in table scope (meaning that a regular </a> end tag at the start of the table wouldn't close the outer a element). The result is that the two a elements are indirectly nested inside each other — non-conforming markup will often result in non-conforming DOMs when parsed.

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Push onto the list of active formatting elements that element.

A start tag whose tag name is one of: "b", "big", "code", "em", "font", "i", "s", "small", "strike", "strong", "tt", "u"

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Push onto the list of active formatting elements that element.

A start tag whose tag name is "nobr"

Reconstruct the active formatting elements, if any.

If the stack of open elements has a nobr element in scope, then this is a parse error; run the adoption agency algorithm for the token, then once again reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Push onto the list of active formatting elements that element.

An end tag whose tag name is one of: "a", "b", "big", "code", "em", "font", "i", "nobr", "s", "small", "strike", "strong", "tt", "u"

Run the adoption agency algorithm for the token.

A start tag whose tag name is one of: "applet", "marquee", "object"

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token.

Insert a marker at the end of the list of active formatting elements.

Set the frameset-ok flag to "not ok".

An end tag token whose tag name is one of: "applet", "marquee", "object"

If the stack of open elements does not have an element in scope that is an HTML element with the same tag name as that of the token, then this is a parse error; ignore the token.

Otherwise, run these steps:

  1. Generate implied end tags.

  2. If the current node is not an HTML element with the same tag name as that of the token, then this is a parse error.

  3. Pop elements from the stack of open elements until an HTML element with the same tag name as the token has been popped from the stack.

  4. Clear the list of active formatting elements up to the last marker.
A start tag whose tag name is "table"

If the Document is not set to quirks mode, and the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token.

Set the frameset-ok flag to "not ok".

Switch the insertion mode to "in table".

An end tag whose tag name is "br"

Parse error. Drop the attributes from the token, and act as described in the next entry; i.e. act as if this was a "br" start tag token with no attributes, rather than the end tag token that it actually is.

A start tag whose tag name is one of: "area", "br", "embed", "img", "keygen", "wbr"

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

Set the frameset-ok flag to "not ok".

A start tag whose tag name is "input"

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

If the token does not have an attribute with the name "type", or if it does, but that attribute's value is not an ASCII case-insensitive match for the string "hidden", then: set the frameset-ok flag to "not ok".

A start tag whose tag name is one of: "param", "source", "track"

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

A start tag whose tag name is "hr"

If the stack of open elements has a p element in button scope, then close a p element.

Insert an HTML element for the token. Immediately pop the current node off the stack of open elements.

Acknowledge the token's self-closing flag, if it is set.

Set the frameset-ok flag to "not ok".

A start tag whose tag name is "image"

Parse error. Change the token's tag name to "img" and reprocess it. (Don't ask.)

A start tag whose tag name is "textarea"

Run these steps:

  1. Insert an HTML element for the token.

  2. If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.)

  3. Switch the tokenizer to the RCDATA state.

  4. Let the original insertion mode be the current insertion mode.

  5. Set the frameset-ok flag to "not ok".

  6. Switch the insertion mode to "text".

A start tag whose tag name is "xmp"

If the stack of open elements has a p element in button scope, then close a p element.

Reconstruct the active formatting elements, if any.

Set the frameset-ok flag to "not ok".

Follow the generic raw text element parsing algorithm.

A start tag whose tag name is "iframe"

Set the frameset-ok flag to "not ok".

Follow the generic raw text element parsing algorithm.

A start tag whose tag name is "noembed"
A start tag whose tag name is "noscript", if the scripting flag is enabled

Follow the generic raw text element parsing algorithm.

A start tag whose tag name is "select"

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token.

Set the frameset-ok flag to "not ok".

If the insertion mode is one of "in table", "in caption", "in table body", "in row", or "in cell", then switch the insertion mode to "in select in table". Otherwise, switch the insertion mode to "in select".

A start tag whose tag name is one of: "optgroup", "option"

If the current node is an option element, then pop the current node off the stack of open elements.

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token.

A start tag whose tag name is one of: "rb", "rtc"

If the stack of open elements has a ruby element in scope, then generate implied end tags. If the current node is not now a ruby element, this is a parse error.

Insert an HTML element for the token.

A start tag whose tag name is one of: "rp", "rt"

If the stack of open elements has a ruby element in scope, then generate implied end tags, except for rtc elements. If the current node is not now a rtc element or a ruby element, this is a parse error.

Insert an HTML element for the token.

A start tag whose tag name is "math"

Reconstruct the active formatting elements, if any.

Adjust MathML attributes for the token. (This fixes the case of MathML attributes that are not all lowercase.)

Adjust foreign attributes for the token. (This fixes the use of namespaced attributes, in particular XLink.)

Insert a foreign element for the token, in the MathML namespace.

If the token has its self-closing flag set, pop the current node off the stack of open elements and acknowledge the token's self-closing flag.

A start tag whose tag name is "svg"

Reconstruct the active formatting elements, if any.

Adjust SVG attributes for the token. (This fixes the case of SVG attributes that are not all lowercase.)

Adjust foreign attributes for the token. (This fixes the use of namespaced attributes, in particular XLink in SVG.)

Insert a foreign element for the token, in the SVG namespace.

If the token has its self-closing flag set, pop the current node off the stack of open elements and acknowledge the token's self-closing flag.

A start tag whose tag name is one of: "caption", "col", "colgroup", "frame", "head", "tbody", "td", "tfoot", "th", "thead", "tr"

Parse error. Ignore the token.

Any other start tag

Reconstruct the active formatting elements, if any.

Insert an HTML element for the token.

This element will be an ordinary element.

Any other end tag

Run these steps:

  1. Initialize node to be the current node (the bottommost node of the stack).

  2. Loop: If node is an HTML element with the same tag name as the token, then:

    1. Generate implied end tags, except for HTML elements with the same tag name as the token.

    2. If node is not the current node, then this is a parse error.

    3. Pop all the nodes from the current node up to node, including node, then stop these steps.

  3. Otherwise, if node is in the special category, then this is a parse error; ignore the token, and return.

  4. Set node to the previous entry in the stack of open elements.

  5. Return to the step labeled loop.

When the steps above say the user agent is to close a p element, it means that the user agent must run the following steps:

  1. Generate implied end tags, except for p elements.

  2. If the current node is not a p element, then this is a parse error.

  3. Pop elements from the stack of open elements until a p element has been popped from the stack.

The adoption agency algorithm, which takes as its only argument a token token for which the algorithm is being run, consists of the following steps:

  1. Let subject be token's tag name.

  2. If the current node is an HTML element whose tag name is subject, and the current node is not in the list of active formatting elements, then pop the current node off the stack of open elements, and return.

  3. Let outer loop counter be zero.

  4. Outer loop: If outer loop counter is greater than or equal to eight, then return.

  5. Increment outer loop counter by one.

  6. Let formatting element be the last element in the list of active formatting elements that:

    If there is no such element, then return and instead act as described in the "any other end tag" entry above.

  7. If formatting element is not in the stack of open elements, then this is a parse error; remove the element from the list, and return.

  8. If formatting element is in the stack of open elements, but the element is not in scope, then this is a parse error; return.

  9. If formatting element is not the current node, this is a parse error. (But do not return.)

  10. Let furthest block be the topmost node in the stack of open elements that is lower in the stack than formatting element, and is an element in the special category. There might not be one.

  11. If there is no furthest block, then the UA must first pop all the nodes from the bottom of the stack of open elements, from the current node up to and including formatting element, then remove formatting element from the list of active formatting elements, and finally return.

  12. Let common ancestor be the element immediately above formatting element in the stack of open elements.

  13. Let a bookmark note the position of formatting element in the list of active formatting elements relative to the elements on either side of it in the list.

  14. Let node and last node be furthest block. Follow these steps:

    1. Let inner loop counter be zero.

    2. Inner loop: Increment inner loop counter by one.

    3. Let node be the element immediately above node in the stack of open elements, or if node is no longer in the stack of open elements (e.g. because it got removed by this algorithm), the element that was immediately above node in the stack of open elements before node was removed.

    4. If node is formatting element, then go to the next step in the overall algorithm.

    5. If inner loop counter is greater than three and node is in the list of active formatting elements, then remove node from the list of active formatting elements.

    6. If node is not in the list of active formatting elements, then remove node from the stack of open elements and then go back to the step labeled inner loop.

    7. Create an element for the token for which the element node was created, in the HTML namespace, with common ancestor as the intended parent; replace the entry for node in the list of active formatting elements with an entry for the new element, replace the entry for node in the stack of open elements with an entry for the new element, and let node be the new element.

    8. If last node is furthest block, then move the aforementioned bookmark to be immediately after the new node in the list of active formatting elements.

    9. Insert last node into node, first removing it from its previous parent node if any.

    10. Let last node be node.

    11. Return to the step labeled inner loop.

  15. Insert whatever last node ended up being in the previous step at the appropriate place for inserting a node, but using common ancestor as the override target.

  16. Create an element for the token for which formatting element was created, in the HTML namespace, with furthest block as the intended parent.

  17. Take all of the child nodes of furthest block and append them to the element created in the last step.

  18. Append that new element to furthest block.

  19. Remove formatting element from the list of active formatting elements, and insert the new element into the list of active formatting elements at the position of the aforementioned bookmark.

  20. Remove formatting element from the stack of open elements, and insert the new element into the stack of open elements immediately below the position of furthest block in that stack.

  21. Jump back to the step labeled outer loop.

This algorithm's name, the "adoption agency algorithm", comes from the way it causes elements to change parents, and is in contrast with other possible algorithms for dealing with misnested content.

13.2.6.4.8 The "text" insertion mode

When the user agent is to apply the rules for the "text" insertion mode, the user agent must handle the token as follows:

A character token

Insert the token's character.

This can never be a U+0000 NULL character; the tokenizer converts those to U+FFFD REPLACEMENT CHARACTER characters.

An end-of-file token

Parse error.

If the current node is a script element, mark the script element as "already started".

Pop the current node off the stack of open elements.

Switch the insertion mode to the original insertion mode and reprocess the token.

An end tag whose tag name is "script"

If the JavaScript execution context stack is empty, perform a microtask checkpoint.

Let script be the current node (which will be a script element).

Pop the current node off the stack of open elements.

Switch the insertion mode to the original insertion mode.

Let the old insertion point have the same value as the current insertion point. Let the insertion point be just before the next input character.

Increment the parser's script nesting level by one.

Prepare the script. This might cause some script to execute, which might cause new characters to be inserted into the tokenizer, and might cause the tokenizer to output more tokens, resulting in a reentrant invocation of the parser.

Decrement the parser's script nesting level by one. If the parser's script nesting level is zero, then set the parser pause flag to false.

Let the insertion point have the value of the old insertion point. (In other words, restore the insertion point to its previous value. This value might be the "undefined" value.)

At this stage, if there is a pending parsing-blocking script, then:

If the script nesting level is not zero:

Set the parser pause flag to true, and abort the processing of any nested invocations of the tokenizer, yielding control back to the caller. (Tokenization will resume when the caller returns to the "outer" tree construction stage.)

The tree construction stage of this particular parser is being called reentrantly, say from a call to document.write().

Otherwise:

Run these steps:

  1. Let the script be the pending parsing-blocking script. There is no longer a pending parsing-blocking script.

  2. Block the tokenizer for this instance of the HTML parser, such that the event loop will not run tasks that invoke the tokenizer.

  3. If the parser's Document has a style sheet that is blocking scripts or the script's "ready to be parser-executed" flag is not set: spin the event loop until the parser's Document has no style sheet that is blocking scripts and the script's "ready to be parser-executed" flag is set.

  4. If this parser has been aborted in the meantime, return.

    This could happen if, e.g., while the spin the event loop algorithm is running, the browsing context gets closed, or the document.open() method gets invoked on the Document.

  5. Unblock the tokenizer for this instance of the HTML parser, such that tasks that invoke the tokenizer can again be run.

  6. Let the insertion point be just before the next input character.

  7. Increment the parser's script nesting level by one (it should be zero before this step, so this sets it to one).

  8. Execute the script.

  9. Decrement the parser's script nesting level by one. If the parser's script nesting level is zero (which it always should be at this point), then set the parser pause flag to false.

  10. Let the insertion point be undefined again.

  11. If there is once again a pending parsing-blocking script, then repeat these steps from step 1.

Any other end tag

Pop the current node off the stack of open elements.

Switch the insertion mode to the original insertion mode.

13.2.6.4.9 "in table" 插入模式

当用户代理应用 "in table" 插入模式 的规则时,用户代理必须按以下规则处理标记:

字符标记,如果 current nodetable, tbody, tfoot, thead, 或 tr 元素

待处理表格字符标记 为一个空的标记列表。

原始插入模式 为当前 插入模式

插入模式 切换到 "in table text" 后重新处理该标记。

注释标记

插入注释

DOCTYPE 标记

解析错误。忽略该标记。

名为 "caption" 的开始标签

将栈清除回表格上下文。(见下文)

活动的格式化原始列表 的结尾插入一个 标记

为该标记 插入一个 HTML 元素 ,然后把 插入模式 切换到 "in caption"。

名为 "colgroup" 的开始标签

将栈清除回表格上下文。(见下文)

为该标记 插入一个 HTML 元素 ,然后把 插入模式 切换到 "in column group"。

名为 "col" 的开始标签

将栈清除回表格上下文。(见下文)

为 "colgroup" 开始标签标记 插入一个 HTML 元素,没有任何属性, 然后把 插入模式 切换到 "in column group"。

重新处理当前标记。

名为 "tbody", "tfoot", "thead" 的开始标签

将栈清除回表格上下文。(见下文)

为该标记 插入一个 HTML 元素 ,然后把 插入模式 切换到 "in table body"。

名为 "td", "th", "tr" 的开始标签

将栈清除回表格上下文。(见下文)

为 "tbody" 开始标签标记 插入一个 HTML 元素,没有任何属性, 然后把 插入模式 切换到 "in table body"。

重新处理当前标记。

名为 "table" 的开始标签

解析错误

如果 打开元素的栈 在表格范围内部包含一个 table 元素,忽略该标记。

否则:

打开元素栈 弹栈直到弹出来的是一个 table 元素。

适当地重置解析器的插入模式

重新处理该标记。

名为 "table" 的结束标签

如果 打开元素栈 在表格范围内部包含一个 table 元素, 这是一个 解析错误;忽略该标记。

否则:

打开元素栈 弹栈直到弹出来的是一个 table 元素。

适当地重置解析器的插入模式

名为 "body", "caption", "col", "colgroup", "html", "tbody", "td", "tfoot", "th", "thead", "tr" 的结束标签

解析错误。忽略该标记。

名为 "style", "script", "template" 的开始标签
名为 "template" 的结束标签

使用 "in head" 插入模式 的规则处理该标记。

名为 "input" 的开始标签

如果该标记没有名为 "type" 的属性,或该属性的值不能 ASCII 大小写不敏感 地匹配字符串 "hidden",那么执行下面 "anything else" 描述的步骤。

否则:

解析错误

为该标记 插入一个 HTML 元素

把那个 input 元素从 打开元素栈 弹栈。

确认该标记的 self-closing 标志,如果设置了这个标志的话。

名为 "form" 的开始标签

解析错误

如果在 打开元素栈 上有一个 template 元素,且 form 元素指针 不是 null, 忽略该标记。

否则:

为该标记 插入一个 HTML 元素,然后设置 form 元素指针 为该元素创建的指针。

把那个 form 元素从 打开元素栈 弹出。

文件尾(EOF)标记

使用 "in body" 插入模式 的规则处理该标记。

其他情况

解析错误。启用 foster parenting使用 "in body" 插入模式 处理该标记,然后禁用 foster parenting

当上述步骤要求 UA 把栈清除回表格上下文 时, 那么 UA 必须从 打开元素栈 弹出元素, 直到 当前节点table, template, 或 html 元素。

这与 在表格范围内存在元素 步骤中用到的元素列表是一样的。

在这一处理后,当前节点 是一个 html 元素的, 就是一个 fragment case

13.2.6.4.10 The "in table text" insertion mode

When the user agent is to apply the rules for the "in table text" insertion mode, the user agent must handle the token as follows:

A character token that is U+0000 NULL

Parse error. Ignore the token.

Any other character token

Append the character token to the pending table character tokens list.

Anything else

If any of the tokens in the pending table character tokens list are character tokens that are not ASCII whitespace, then this is a parse error: reprocess the character tokens in the pending table character tokens list using the rules given in the "anything else" entry in the "in table" insertion mode.

Otherwise, insert the characters given by the pending table character tokens list.

Switch the insertion mode to the original insertion mode and reprocess the token.

13.2.6.4.11 The "in caption" 插入模式

当用户代理应用 "in caption" 插入模式 的规则时,用户代理必须按以下规则处理标记:

名为 "caption" 的结束标签

the 打开元素栈 在表格范围内不包含一个 caption 元素, 这是一个 解析错误; 忽略该标记。 (fragment case)

否则:

生成暗示的结束标签

现在如果 当前节点 不是 caption 元素, 那么这是一个 解析错误

从栈中弹出元素直到得到一个 caption 元素。

清空直到最后一个标记的活跃的格式化元素列表

插入模式 切换到 "in table"。

名为 "caption","col","colgroup","tbody","td","tfoot", "th","thead","tr" 的开始标签
名为 "table" 的结束标签

如果 打开元素栈 在表格范围内没有 caption 元素, 这是一个 解析错误; 忽略该标记。 (fragment case)

否则:

生成暗示的结束标签

现在如果 当前节点 不是 caption 元素, 那么这是一个 解析错误

从栈中弹出元素直到得到一个 caption 元素。

清空直到最后一个标记的活跃的格式化元素列表

插入模式 切换到 "in table"。

重新处理该标记。

名为 "body","col","colgroup","html","tbody","td", "tfoot","th","thead","tr" 的结束标签

解析错误。 忽略该标记。

任何其他标记

使用 "in body" 插入模式 的规则处理该标记。

13.2.6.4.12 "in column group" 插入模式

当用户代理应用 "in column group" 插入模式 的规则时,用户代理必须按以下规则处理标记:

字符标记 U+0009 CHARACTER TABULATION,U+000A LINE FEED (LF),U+000C FORM FEED (FF),U+000D CARRIAGE RETURN (CR),或 U+0020 SPACE

插入该字符

注释标记

插入注释

DOCTYPE 标记

解析错误。忽略该标记。

名为 "html" 的开始标签

使用 "in body" 插入模式 的规则处理该标记。

名为 "col" 的开始标签

插入一个 HTML 元素 为该标记。 把 当前节点 立即从 打开元素栈 弹出。

确认该标记的 self-closing flag,如果设置了该标记的话。

名为 "colgroup" 的结束标签

如果 当前节点 不是 colgroup 元素,那么 解析错误; 忽略该标记。

否则,把 当前节点打开元素栈 弹出。 将 插入模式 切换到 "in table"。

名为 "col" 的结束标签

解析错误。 忽略该标记。

名为 "template" 的开始标签
名为 "template" 的结束标签

使用 "in head" 插入模式 的规则处理该标记。

文件尾(EOF)标记

使用 "in body" 插入模式 的规则处理该标记。

任何其他标记

如果 当前节点 不是 colgroup 元素,那么这是一个 解析错误; 忽略该标记。

否则,把 当前节点打开元素栈 弹出。

插入模式 切换到 "in table"。

重新处理该标记。

13.2.6.4.13 "in table body" 插入模式

当用户代理应用 "in table body" 插入模式 的规则时,用户代理必须按以下规则处理标记:

名为 "tr" 的开始标签

将栈清除回表格体上下文。(见下文)

为该标记 插入一个 HTML 元素, 然后把 插入模式 切换到 "in row"。

名为 "th", "td" 的开始标签

解析错误

将栈清除回表格体上下文。(见下文)

为 "tr" 开始标签标记 插入一个 HTML 元素, 不设置任何属性,然后把 插入模式 切换为 "in row"。

重新处理当前标记。

名为 "tbody", "tfoot", "thead" 的结束标签标记

如果 打开元素栈 在表格范围内没有 一个与该标记同名的 HTML 元素, 这就是一个 解析错误;忽略这个标记。

否则:

将栈清除回表格体上下文。(见下文)

当前节点打开元素栈 弹出。 把 插入模式 切换到 "in table"。

名为 "caption", "col", "colgroup", "tbody", "tfoot", "thead" 的开始标记
名为 "table" 的结束标签

如果 打开元素栈 在表格范围内没有一个 tbody, thead, 或 tfoot 元素, 这是一个 解析错误;忽略该标记。

否则:

将栈清除回表格体上下文。(见下文)

当前节点打开元素栈 弹出。 把 插入模式 切换到 "in table"。

重新处理当前标记。

名为 "body", "caption", "col", "colgroup", "html", "td", "th", "tr" 的结束标签

解析错误。忽略该标记。

任何其他情况

使用 "in table" 插入模式 的规则处理该标记。

当上述步骤中要求 UA 将栈清除回表格体上下文 时, UA 必须从 打开元素栈 弹出元素,直到 当前节点tbody, tfoot, thead, templatehtml 元素为止。

在这一处理后,当前节点 是一个 html 元素的, 就是一个 fragment case

13.2.6.4.14 "in row" 插入模式

当用户代理应用 "in row" 插入模式 的规则时,用户代理必须按以下规则处理标记:

名为 "th", "td" 的开始标签

将栈清除回表格行上下文。(见下文)

尾该标记 插入一个 HTML 元素,然后b把 插入模式 切换到 "in cell"。

活动的格式化元素列表 的结尾插入一个 标记

名为 "tr" 的结束标签

如果 打开元素标记 在 table 范围内不包含一个 tr 元素, 这是一个 解析错误;忽略该标记。

否则:

将栈清除回表格行上下文。(见下文)

当前节点(是一个 tr 元素) 从 打开元素栈 弹出。 把 插入模式 切换到 "in table body"。

名为 "caption", "col", "colgroup", "tbody", "tfoot", "thead", "tr" 的开始标签
名为 "table" 的结束标签

如果 打开元素栈 在 table 范围内不包含 tr 元素, 这是一个 解析错误;忽略该标记。

否则:

将栈清除回表格行上下文。(见下文)

当前节点(是一个 tr 元素) 从 打开元素栈 弹出。 把 插入模式 切换到 "in table body"。

重新处理该标记。

名为 "tbody", "tfoot", "thead" 的结束标签

如果 打开元素栈 在表格范围内没有 一个与该标记同名的 HTML 元素, 这就是一个 解析错误;忽略这个标记。

如果 打开元素栈 在 table 范围内没有一个 tr 元素,这是一个 解析错误;忽略该标记。

否则:

将栈清除回表格行上下文。(见下文)

当前节点(是一个 tr 元素) 从 打开元素栈 弹出。 把 插入模式 切换到 "in table body"。

重新处理该标记。

名为 "body", "caption", "col", "colgroup", "html", "td", "th" 的结束标签

解析错误。忽略该标记。

其他情况

使用 "in table" 插入模式 处理该标记。

当上述步骤中要求 UA 将栈清除回表格行上下文 时, UA 必须从 打开元素栈 弹出元素,直到 当前节点tr, templatehtml 元素为止。

在这一处理后,当前节点 是一个 html 元素的, 就是一个 fragment case

13.2.6.4.15 "in cell" 插入模式

当用户代理应用 "in cell" 插入模式 的规则时,用户代理必须按以下规则处理标记:

名为 "td","th" 的结束标签

如果 打开元素栈 在表格范围内没有 一个与该标记同名的 HTML 元素, 那么这是一个 解析错误; 忽略该标记。

否则:

生成暗示的结束标签

现在如果 当前节点 不是与该标记同名的 HTML 元素,那么这是一个 解析错误

打开元素栈 弹出元素,直到弹出了与该标记同名的 HTML 元素 为止。

清空直到最后一个标记的活跃的格式化元素列表

插入模式 切换到 "in row"。

名为 "caption","col", "colgroup","tbody","td","tfoot","th","thead","tr" 的开始标签

如果 打开元素栈 在表格范围内 不包含 tdth 元素, 那么这是一个 解析错误;忽略该标记。 (fragment case)

否则,关闭该单元格(见下文)并重新处理该标记。

名为 "body","caption", "col","colgroup","html" 的结束标签

解析错误。 忽略该标记。

名为 "table","tbody", "tfoot","thead","tr" 的结束标签

如果 打开元素栈 在表格范围内不包含 与该标记同名的 HTML 元素, 那么这是一个 解析错误; 忽略该标记。

否则,关闭该单元格(见下文)并重新处理该标记。

任何其他标记

使用 "in body" 插入模式 的规则处理该标记。

上述步骤中的 关闭单元格,是指执行以下算法:

  1. 生成暗示的结束标签

  2. 如果现在的 当前节点 不是 tdth 元素, 那么这是一个 解析错误

  3. 打开元素栈 弹出元素,直到得到一个 tdth 元素。

  4. 清空直到最后一个标记的活跃的格式化元素列表

  5. 插入模式 切换到 "in row"。

打开元素栈 在表格上下文 不可能同时包含 tdth 元素, 当调用 关闭单元格 算法时也不可能包含它们。

13.2.6.4.16 "in select" 插入模式

当用户代理应用 "in select" 插入模式 的规则时,用户代理必须按以下规则处理标记:

一个 U+0000 NULL 字符标记

解析错误。忽略该标记。

任何其他字符标记

插入该标记的字符

注释标记

插入注释

DOCTYPE 标记

解析错误。忽略该标记。

名为 "html" 的开始标签

使用 "in body" 插入模式 处理该标记。

名为 "option" 的开始标签

如果 当前节点 是一个 option 元素, 把该元素从 打开元素栈 弹出。

为该标记 插入一个 HTML 元素

名为 "optgroup" 的开始标签

如果 当前节点 是一个 option 元素, 把该元素从 打开元素栈 弹出。

如果 当前节点 是一个 optgroup 元素, 把该元素从 打开元素栈 弹出。

为该标记 插入一个 HTML 元素

名为 "optgroup" 的结束标签

首先,如果 当前节点 是一个 option 元素, 而且在 打开元素栈 中紧接着该节点之前的那个元素是一个 optgroup 元素,那么把 当前节点打开元素栈 弹出。

如果 当前节点 是一个 optgroup 元素, 那么把该节点从 打开元素栈 弹出。 否则,这是一个 解析错误;忽略该标记。

名为 "option" 的结束标签

如果 当前节点 是一个 option 元素,就把那个节点从 打开元素栈 弹出。 否则这就是一个 解析错误;忽略该标记。

名为 "select" 的结束标签

如果 打开元素栈 在 select 范围内没有 select 元素, 这是一个 解析错误;忽略该标记。(fragment case

否则:

打开元素栈 弹出元素,直到得到一个 select 元素。

适当地重置解析器的插入模式

名为 "select" 的开始标签

解析错误

如果 打开元素栈 在 select 范围内没有一个 select 元素, 忽略该标记(fragment case

否则:

打开元素栈 弹出元素,直到得到一个 select 元素。

适当地重置解析器的插入模式

就是把它当作结束标签处理了。

名为 "input", "keygen", "textarea" 的开始标签

解析错误

如果 打开元素栈 在 select 范围内没有一个 select 元素, 忽略该标记。(fragment case

否则:

打开元素栈 弹出元素直到得到一个 select 元素。

适当地重置解析器的插入模式

重新处理该标记。

名为 "script", "template" 的开始标签
名为 "template" 的结束标签

使用 the "in head" 插入模式 处理该标记。

文件尾(EOF)标记

使用 "in body" 插入模式 处理该标记。

其他情况

解析错误。忽略该标记。

13.2.6.4.17 "in select in table" 插入模式

当用户代理应用 "in select in table" 插入模式 的规则时,用户代理必须按以下规则处理标记:

名为 "caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th" 的开始标签

解析错误

打开元素栈 弹出元素,直到得到一个 select 元素。

适当地重置插入模式

重新处理该标记。

名为 "caption", "table", "tbody", "tfoot", "thead", "tr", "td", "th" 的结束标签

解析错误.

如果 打开元素栈 在 table 范围内不包含 与该标记同名的 HTML 元素, 忽略该标记。

否则:

打开元素栈 弹出元素,直到得到一个 select 元素。

适当地重置解析器的插入模式.

重新处理该标记。

其他情况

使用 "in select" 插入模式 处理该标记。

13.2.6.4.18 "in template" 插入模式

当用户代理应用 "in template" 插入模式 的规则时,用户代理必须按以下规则处理标记:

字符标记
注释标记
DOCTYPE 标记

使用 "in body" 插入模式 的规则处理该标记。

名为 "base", "basefont", "bgsound", "link", "meta", "noframes", "script", "style", "template", "title" 的开始标签
名为 "template" 的结束标签

使用 "in head" 插入模式 的规则处理该标记。

名为 "caption", "colgroup", "tbody", "tfoot", "thead" 的开始标签

把当前 当前模板插入模式 弹出 模板插入模式的栈

把 "in table" 压入 模板插入模式的栈, 让它称为新的 当前模板插入模式

插入模式 切换到 "in table" 后重新处理该标记。

名为 "col" 的开始标签

当前模板插入模式 弹出 模板插入模式的栈

把 "in column group" 压入 模板插入模式的栈 让它称为新的 当前模板插入模式

插入模式 切换到 "in column group" 后重新处理该标记。

名为 "tr" 的开始标签

当前模板插入模式 弹出 模板插入模式的栈

把 "in table body" 压入 模板插入模式的栈 让它称为新的 当前模板插入模式

插入模式 切换到 "in table body" 后重新处理该标记。

名为 "td", "th" 的开始标签

当前模板插入模式 弹出 模板插入模式的栈

把 "in row" 压入 模板插入模式的栈 让它称为新的 当前模板插入模式

插入模式 切换到 "in row" 后重新处理该标记。

任何其他开始标签

当前模板插入模式 弹出 模板插入模式的栈

把 "in body" 压入 模板插入模式的栈 让它称为新的 当前模板插入模式

插入模式 切换到 "in body" 后重新处理该标记。

任何其他结束标签

解析错误。忽略该标签。

文件尾(EOF)标记

如果在 打开元素栈 上没有 template 元素,就 停止解析。(fragment case

否则这就是一个 解析错误

打开元素栈 弹栈直到弹出来的是一个 template 元素。

清空直到最后一个标记的活跃的格式化元素列表

当前模板插入模式 弹出 模板插入模式的栈

适当地重置解析器的插入模式.

重新处理该标记。

13.2.6.4.19 "after body" 插入模式

当用户代理应用 "after body" 插入模式 的规则时,用户代理必须按以下规则处理标记:

字符标记 U+0009 CHARACTER TABULATION,U+000A LINE FEED (LF),U+000C FORM FEED (FF),U+000D CARRIAGE RETURN (CR),或 U+0020 SPACE

使用 "in body" 插入模式 的规则处理该标记。

注释标记

插入一个注释 作为 打开元素栈 中第一个元素的最后一个子节点。 (html 元素)。

DOCTYPE 标记

解析错误。 忽略该标记。

名为 "html" 的开始标签

使用 "in body" 插入模式 的规则处理该标记。

名为 "html" 的结束标签

如果该解析器最初是作为 HTML 片段解析算法 的一部分创建的,那么这是一个 解析错误;忽略该标记。 (fragment case

否则,把 插入模式 切换到 "after after body"。

文件尾(EOF)标记

停止解析

任何其他标记

解析错误。把 插入模式 切换到 "in body" 并重新处理该标记。

13.2.6.4.20 "in frameset" 插入模式

当用户代理应用 "in frameset" 插入模式 的规则时,用户代理必须按以下规则处理标记:

字符标记 U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR) 或 U+0020 SPACE

插入该字符

评论标记

插入该字符

DOCTYPE 字符

解析错误。忽略该字符。

名为 "html" 的开始标签

使用 "in body" 插入模式 处理该标记。

名为 "frameset" 的开始标签

为该标记 插入一个 HTML 元素

名为 "frameset" 的结束标签

如果 当前节点 是根 html 元素, 那么这是一个 解析错误;忽略该标记。(fragment case

否则,把 当前节点打开元素栈 弹出。

如果该解析器最初 不是 作为 HTML 片段解析算法fragment case) 的一部分创建的,且 当前节点 不再是 frameset 元素,那么把 插入模式 切换到 "after frameset"。

名为 "frame" 的开始标签

为该标记 插入一个 HTML 元素。 立即把 当前节点打开元素栈 弹出。

确认该标记的 self-closing 标志,如果设置了这个标志的话。

名为 "noframes" 的开始标签

使用 "in head" 插入模式 处理该标记。

文件尾(EOF)标记

如果 当前节点 不是根 html 元素, 那么这是一个 解析错误

fragment case 中,当前节点 只能是根 html 元素。

停止解析

任何其他标记

解析错误。忽略该标记。

13.2.6.4.21 "after frameset" 插入模式

当用户代理应用 "after frameset" 插入模式 的规则时,用户代理必须按以下规则处理标记:

字符标记 U+0009 CHARACTER TABULATION,U+000A LINE FEED (LF),U+000C FORM FEED (FF),U+000D CARRIAGE RETURN (CR),或 U+0020 SPACE

插入该字符

注释标记

插入注释

DOCTYPE 标记

解析错误。忽略该标记。

名为 "html" 的开始标签

使用 "in body" 插入模式 的规则处理该标记。

名为 "html" 的结束标签

插入模式 切换到 "after after frameset"。

名为 "noframes" 的开始标签

使用 "in head" 插入模式 的规则处理该标记。

文件尾(EOF)标记

停止解析

任何其他标记

解析错误。 忽略该标记。

13.2.6.4.22 "after after body" 插入模式

当用户代理应用 "after after body" 插入模式 的规则时,用户代理必须按以下规则处理标记:

注释标记

作为 Document 对象的最后一个子节点 插入该注释

DOCTYPE 标记
字符标记 U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), 或 U+0020 SPACE
名为 "html" 的开始标签

使用 "in body" 插入模式的规则处理该标记。

文件尾(EOF)标记

停止解析

任何其他标记

解析错误。把 插入模式 切换到 "in body" 并重新处理该标记。

13.2.6.4.23 "after after frameset" 插入模式

当用户代理应用 "after after frameset" 插入模式 的规则时,用户代理必须按以下规则处理标记:

注释标记

插入注释 作为 Document 对象的最后一个子节点。

DOCTYPE 标记
字符标记 U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR) 或 U+0020 SPACE
名为 "html" 的开始标签

使用 "in body" 插入模式 的规则处理该标记。

文件尾(EOF)标记

停止解析

名为 "noframes" 的开始标签

使用 "in head" 插入模式 的规则处理该标记。

任何其他标记

解析错误。忽略该标记。

13.2.6.5 The rules for parsing tokens in foreign content

When the user agent is to apply the rules for parsing tokens in foreign content, the user agent must handle the token as follows:

A character token that is U+0000 NULL

Parse error. Insert a U+FFFD REPLACEMENT CHARACTER character.

A character token that is one of U+0009 CHARACTER TABULATION, U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), or U+0020 SPACE

Insert the token's character.

Any other character token

Insert the token's character.

Set the frameset-ok flag to "not ok".

A comment token

Insert a comment.

A DOCTYPE token

Parse error. Ignore the token.

A start tag whose tag name is one of: "b", "big", "blockquote", "body", "br", "center", "code", "dd", "div", "dl", "dt", "em", "embed", "h1", "h2", "h3", "h4", "h5", "h6", "head", "hr", "i", "img", "li", "listing", "menu", "meta", "nobr", "ol", "p", "pre", "ruby", "s", "small", "span", "strong", "strike", "sub", "sup", "table", "tt", "u", "ul", "var"
A start tag whose tag name is "font", if the token has any attributes named "color", "face", or "size"

Parse error.

If the parser was created as part of the HTML fragment parsing algorithm, then act as described in the "any other start tag" entry below. (fragment case)

Otherwise:

Pop an element from the stack of open elements, and then keep popping more elements from the stack of open elements until the current node is a MathML text integration point, an HTML integration point, or an element in the HTML namespace.

Then, reprocess the token.

Any other start tag

If the adjusted current node is an element in the MathML namespace, adjust MathML attributes for the token. (This fixes the case of MathML attributes that are not all lowercase.)

If the adjusted current node is an element in the SVG namespace, and the token's tag name is one of the ones in the first column of the following table, change the tag name to the name given in the corresponding cell in the second column. (This fixes the case of SVG elements that are not all lowercase.)

Tag name Element name
altglyph altGlyph
altglyphdef altGlyphDef
altglyphitem altGlyphItem
animatecolor animateColor
animatemotion animateMotion
animatetransform animateTransform
clippath clipPath
feblend feBlend
fecolormatrix feColorMatrix
fecomponenttransfer feComponentTransfer
fecomposite feComposite
feconvolvematrix feConvolveMatrix
fediffuselighting feDiffuseLighting
fedisplacementmap feDisplacementMap
fedistantlight feDistantLight
fedropshadow feDropShadow
feflood feFlood
fefunca feFuncA
fefuncb feFuncB
fefuncg feFuncG
fefuncr feFuncR
fegaussianblur feGaussianBlur
feimage feImage
femerge feMerge
femergenode feMergeNode
femorphology feMorphology
feoffset feOffset
fepointlight fePointLight
fespecularlighting feSpecularLighting
fespotlight feSpotLight
fetile feTile
feturbulence feTurbulence
foreignobject foreignObject
glyphref glyphRef
lineargradient linearGradient
radialgradient radialGradient
textpath textPath

If the adjusted current node is an element in the SVG namespace, adjust SVG attributes for the token. (This fixes the case of SVG attributes that are not all lowercase.)

Adjust foreign attributes for the token. (This fixes the use of namespaced attributes, in particular XLink in SVG.)

Insert a foreign element for the token, in the same namespace as the adjusted current node.

If the token has its self-closing flag set, then run the appropriate steps from the following list:

If the token's tag name is "script", and the new current node is in the SVG namespace

Acknowledge the token's self-closing flag, and then act as described in the steps for a "script" end tag below.

Otherwise

Pop the current node off the stack of open elements and acknowledge the token's self-closing flag.

An end tag whose tag name is "script", if the current node is an SVG script element

Pop the current node off the stack of open elements.

Let the old insertion point have the same value as the current insertion point. Let the insertion point be just before the next input character.

Increment the parser's script nesting level by one. Set the parser pause flag to true.

Process the SVG script element according to the SVG rules, if the user agent supports SVG. [SVG]

Even if this causes new characters to be inserted into the tokenizer, the parser will not be executed reentrantly, since the parser pause flag is true.

Decrement the parser's script nesting level by one. If the parser's script nesting level is zero, then set the parser pause flag to false.

Let the insertion point have the value of the old insertion point. (In other words, restore the insertion point to its previous value. This value might be the "undefined" value.)

Any other end tag

Run these steps:

  1. Initialize node to be the current node (the bottommost node of the stack).

  2. If node's tag name, converted to ASCII lowercase, is not the same as the tag name of the token, then this is a parse error.

  3. Loop: If node is the topmost element in the stack of open elements, then return. (fragment case)

  4. If node's tag name, converted to ASCII lowercase, is the same as the tag name of the token, pop elements from the stack of open elements until node has been popped from the stack, and then return.

  5. Set node to the previous entry in the stack of open elements.

  6. If node is not an element in the HTML namespace, return to the step labeled loop.

  7. Otherwise, process the token according to the rules given in the section corresponding to the current insertion mode in HTML content.

13.2.7 The end

Document/DOMContentLoaded_event

Support in all current engines.

Firefox1+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+

Once the user agent stops parsing the document, the user agent must run the following steps:

Window/load_event

Support in all current engines.

Firefox1+Safari1.3+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
  1. Set the current document readiness to "interactive" and the insertion point to undefined.

  2. Pop all the nodes off the stack of open elements.

  3. If the list of scripts that will execute when the document has finished parsing is not empty, run these substeps:

    1. Spin the event loop until the first script in the list of scripts that will execute when the document has finished parsing has its "ready to be parser-executed" flag set and the parser's Document has no style sheet that is blocking scripts.

    2. Execute the first script in the list of scripts that will execute when the document has finished parsing.

    3. Remove the first script element from the list of scripts that will execute when the document has finished parsing (i.e. shift out the first entry in the list).

    4. If the list of scripts that will execute when the document has finished parsing is still not empty, repeat these substeps again from substep 1.

  4. Queue a global task on the DOM manipulation task source given the Document's relevant global object to run the following substeps:

    1. Fire an event named DOMContentLoaded at the Document object, with its bubbles attribute initialized to true.

    2. Enable the client message queue of the ServiceWorkerContainer object whose associated service worker client is the Document object's relevant settings object.

  5. Spin the event loop until the set of scripts that will execute as soon as possible and the list of scripts that will execute in order as soon as possible are empty.

  6. Spin the event loop until there is nothing that delays the load event in the Document.

  7. Queue a global task on the DOM manipulation task source given the Document's relevant global object to run the following substeps:

    1. Set the current document readiness to "complete".

    2. Load event: If the Document object's browsing context is non-null, then fire an event named load at the Document object's relevant global object, with legacy target override flag set.

  8. If the Document object's browsing context is non-null, then queue a global task on the DOM manipulation task source given the Document's relevant global object to run these steps:

    1. If the Document's page showing flag is true, then return (i.e. don't fire the event below).

    2. Set the Document's page showing flag to true.

    3. Fire an event named pageshow at the Document object's relevant global object, using PageTransitionEvent, with the persisted attribute initialized to false, and legacy target override flag set.

  9. If the Document has any pending application cache download process tasks, then queue each such task in the order they were added to the list of pending application cache download process tasks, and then empty the list of pending application cache download process tasks. The task source for these tasks is the networking task source.

  10. If the Document's print when loaded flag is set, then run the printing steps.

  11. The Document is now ready for post-load tasks.

  12. Completely finish loading the Document.

When the user agent is to abort a parser, it must run the following steps:

  1. Throw away any pending content in the input stream, and discard any future content that would have been added to it.

  2. Set the current document readiness to "interactive".

  3. Pop all the nodes off the stack of open elements.

  4. Set the current document readiness to "complete".

13.2.8 Coercing an HTML DOM into an infoset

When an application uses an HTML parser in conjunction with an XML pipeline, it is possible that the constructed DOM is not compatible with the XML tool chain in certain subtle ways. For example, an XML toolchain might not be able to represent attributes with the name xmlns, since they conflict with the Namespaces in XML syntax. There is also some data that the HTML parser generates that isn't included in the DOM itself. This section specifies some rules for handling these issues.

If the XML API being used doesn't support DOCTYPEs, the tool may drop DOCTYPEs altogether.

If the XML API doesn't support attributes in no namespace that are named "xmlns", attributes whose names start with "xmlns:", or attributes in the XMLNS namespace, then the tool may drop such attributes.

The tool may annotate the output with any namespace declarations required for proper operation.

If the XML API being used restricts the allowable characters in the local names of elements and attributes, then the tool may map all element and attribute local names that the API wouldn't support to a set of names that are allowed, by replacing any character that isn't supported with the uppercase letter U and the six digits of the character's code point when expressed in hexadecimal, using digits 0-9 and capital letters A-F as the symbols, in increasing numeric order.

For example, the element name foo<bar, which can be output by the HTML parser, though it is neither a legal HTML element name nor a well-formed XML element name, would be converted into fooU00003Cbar, which is a well-formed XML element name (though it's still not legal in HTML by any means).

As another example, consider the attribute xlink:href. Used on a MathML element, it becomes, after being adjusted, an attribute with a prefix "xlink" and a local name "href". However, used on an HTML element, it becomes an attribute with no prefix and the local name "xlink:href", which is not a valid NCName, and thus might not be accepted by an XML API. It could thus get converted, becoming "xlinkU00003Ahref".

The resulting names from this conversion conveniently can't clash with any attribute generated by the HTML parser, since those are all either lowercase or those listed in the adjust foreign attributes algorithm's table.

If the XML API restricts comments from having two consecutive U+002D HYPHEN-MINUS characters (--), the tool may insert a single U+0020 SPACE character between any such offending characters.

If the XML API restricts comments from ending in a U+002D HYPHEN-MINUS character (-), the tool may insert a single U+0020 SPACE character at the end of such comments.

If the XML API restricts allowed characters in character data, attribute values, or comments, the tool may replace any U+000C FORM FEED (FF) character with a U+0020 SPACE character, and any other literal non-XML character with a U+FFFD REPLACEMENT CHARACTER.

If the tool has no way to convey out-of-band information, then the tool may drop the following information:

The mutations allowed by this section apply after the HTML parser's rules have been applied. For example, a <a::> start tag will be closed by a </a::> end tag, and never by a </aU00003AU00003A> end tag, even if the user agent is using the rules above to then generate an actual element in the DOM with the name aU00003AU00003A for that start tag.

13.2.9 解析器的错误处理和奇怪的场景介绍

This section is non-normative.

这一部分来检查一些错误的标记,并讨论 HTML 解析器 如何处理这些情况。

13.2.9.1 错误嵌套的标签:<b><i></b></i>

This section is non-normative.

这是一个最常讨论的有问题的标记:

<p>1<b>2<i>3</b>4</i>5</p>

直到 "3" 解析的结果都很直观,这时 DOM 看起来是这样:

这里 打开元素栈 有五个元素: html, body, p, b 以及 i活动格式化元素列表 只有两个: bi插入模式 为 "in body"。

在收到标签名为 "b" 的结束标记时,会调用 "adoption agency algorithm"。 这是一个简单的例子,formatting elementb 元素, 且没有 furthest block。 因此 打开元素栈 最终只有三个元素: html, bodyp活动格式化元素列表 只有一个 i。 这时 DOM 树没有变化。

下一个标记是一个字符("4"),触发了 重新构造活动的格式化元素算法, 这个例子中就是 i 元素。因此会为 Text 节点 "4" 创建一个 i 元素。 在收到 "i" 的结束标签标记后,再插入 Text 节点 "5",DOM 看起来如下:

13.2.9.2 错误嵌套的标签:<b><p></b></p>

This section is non-normative.

这是与上一个例子类似的一个例子:

<b>1<p>2</b>3</p>

直到 "2" 解析的结果都很直观:

有趣的部分是解析到 "b" 的结束标记时。

在看到该标记之前,打开元素栈 有四个元素: html, body, b, 和 p活动格式化元素列表 只有一个: b插入模式 为 "in body"。

在收到 "b" 的结束标记时,会像上一个例子那样调用 "adoption agency 算法"。 但这个例子中 一个 furthest block,即 p 元素。 因此 adoption agency 算法不会被跳过。

common ancestorbody 元素。 "bookmark" 的概念标记了 b活动格式化元素列表 中的位置, 但由于该列表只有一个元素,这个 bookmark 没啥作用。

算法继续进行,node 最终被设为格式化元素(b), last node 最终被设为 furthest blockp)。

last node 被追加(移动)到 common ancestor,所以 DOM 变成了这样:

继续创建一个 b 元素,把 p 元素的子节点移动过去:

最后把新的 b 元素追加到 p 元素,所以 DOM 变成了这样:

活动格式化元素列表打开元素栈 移除 b 元素, 所以当解析 "3" 时,它被追加到了 p 元素:

13.2.9.3 Unexpected markup in tables

This section is non-normative.

Error handling in tables is, for historical reasons, especially strange. For example, consider the following markup:

<table><b><tr><td>aaa</td></tr>bbb</table>ccc

The highlighted b element start tag is not allowed directly inside a table like that, and the parser handles this case by placing the element before the table. (This is called foster parenting.) This can be seen by examining the DOM tree as it stands just after the table element's start tag has been seen:

...and then immediately after the b element start tag has been seen:

At this point, the stack of open elements has on it the elements html, body, table, and b (in that order, despite the resulting DOM tree); the list of active formatting elements just has the b element in it; and the insertion mode is "in table".

The tr start tag causes the b element to be popped off the stack and a tbody start tag to be implied; the tbody and tr elements are then handled in a rather straight-forward manner, taking the parser through the "in table body" and "in row" insertion modes, after which the DOM looks as follows:

Here, the stack of open elements has on it the elements html, body, table, tbody, and tr; the list of active formatting elements still has the b element in it; and the insertion mode is "in row".

The td element start tag token, after putting a td element on the tree, puts a marker on the list of active formatting elements (it also switches to the "in cell" insertion mode).

The marker means that when the "aaa" character tokens are seen, no b element is created to hold the resulting Text node:

The end tags are handled in a straight-forward manner; after handling them, the stack of open elements has on it the elements html, body, table, and tbody; the list of active formatting elements still has the b element in it (the marker having been removed by the "td" end tag token); and the insertion mode is "in table body".

Thus it is that the "bbb" character tokens are found. These trigger the "in table text" insertion mode to be used (with the original insertion mode set to "in table body"). The character tokens are collected, and when the next token (the table element end tag) is seen, they are processed as a group. Since they are not all spaces, they are handled as per the "anything else" rules in the "in table" insertion mode, which defer to the "in body" insertion mode but with foster parenting.

When the active formatting elements are reconstructed, a b element is created and foster parented, and then the "bbb" Text node is appended to it:

The stack of open elements has on it the elements html, body, table, tbody, and the new b (again, note that this doesn't match the resulting tree!); the list of active formatting elements has the new b element in it; and the insertion mode is still "in table body".

Had the character tokens been only ASCII whitespace instead of "bbb", then that ASCII whitespace would just be appended to the tbody element.

Finally, the table is closed by a "table" end tag. This pops all the nodes from the stack of open elements up to and including the table element, but it doesn't affect the list of active formatting elements, so the "ccc" character tokens after the table result in yet another b element being created, this time after the table:

13.2.9.4 解析时修改页面的脚本

This section is non-normative.

考虑下面的标记,这个例子中我们假设这个文档的 URLhttps://example.com/inner, 正在渲染到另一个 URLhttps://example.com/outer 的文档的 iframe 中:

<div id=a>
 <script>
  var div = document.getElementById('a');
  parent.document.body.appendChild(div);
 </script>
 <script>
  alert(document.URL);
 </script>
</div>
<script>
 alert(document.URL);
</script>

直到第一个 "script" 结束标签(在解析它之前),结果相对比较直观:

解析这个脚本后 div 元素和它的子元素 script 消失了:

这时它们在前面所说的外层 浏览环境Document 中。但 打开元素栈 仍然包含 div 元素

所以当解析第二个 script 元素时,它被插入 到了外层 Document 对象

解析到的文档与创建解析器的 Document 不同时,其中的脚本不会执行, 所以第一个 alert 不会显示。

一旦解析到 div 元素的结束标签,div 元素就被弹栈, 所以下一个 script 元素处于内层 Document 中:

该脚本会被执行,产生一个写着 "https://example.com/inner" 的 alert。

13.2.9.5 在多个文档中移动的脚本的执行

This section is non-normative.

继续上一小节的例子,考虑第二个 script 元素是外部脚本的情况 (即有 src 属性的脚本)。 由于该元素创建时不在解析器的 Document 中,这个外链脚本甚至不会被下载。

具有 src 属性的 script 元素正常地解析到其解析器的 Document 中的情况, 如果该元素被移动到其他文档中时它还在下载中,那么它会继续下载但不会执行。

通常在 Document 之间移动 script 元素是一个糟糕的实践。

13.2.9.6 Unclosed formatting elements

This section is non-normative.

The following markup shows how nested formatting elements (such as b) get collected and continue to be applied even as the elements they are contained in are closed, but that excessive duplicates are thrown away.

<!DOCTYPE html>
<p><b class=x><b class=x><b><b class=x><b class=x><b>X
<p>X
<p><b><b class=x><b>X
<p></b></b></b></b></b></b>X

The resulting DOM tree is as follows:

Note how the second p element in the markup has no explicit b elements, but in the resulting DOM, up to three of each kind of formatting element (in this case three b elements with the class attribute, and two unadorned b elements) get reconstructed before the element's "X".

Also note how this means that in the final paragraph only six b end tags are needed to completely clear the list of active formatting elements, even though nine b start tags have been seen up to this point.

13.3 序列化 HTML 片段

下列步骤组成了 HTML 片段的序列化算法。该算法的输入为一个 DOM ElementDocument,或 DocumentFragment 作为 node,返回一个字符串。

该算法会把被序列化节点的 子节点 序列化,不包括节点本身。

  1. s 为一个字符串,把它初始化为空字符串。

  2. 如果 该节点 是一个 template 元素,则令 该节点template 元素的 模板内容 (一个 DocumentFragment 节点)。

  3. 该节点 的每一个子节点,以 树序 运行下列步骤:

    1. 当前节点 为正在被处理的子节点。

    2. 从下列列表中选择合适的字符串追加到 s

      如果 当前节点 是一个 Element

      如果 当前节点HTML 命名空间MathML 命名空间, 或 SVG 命名空间 中的一个元素,则令 tagname当前节点 的 局部名。 否则,令 tagname当前节点的 qualified name。

      追加一个 U+003C LESS-THAN SIGN 字符(<),以及 tagname

      对于由 HTML parsercreateElement() 创建的 HTML 元素tagname 将会是小写。

      对该元素具有的每一个属性,追加一个 U+0020 SPACE 字符,属性的序列化名称(见下文), 一个 U+003D EQUALS SIGN 字符(=),一个 U+0022 QUOTATION MARK 字符("), 属性在 属性模式转义后的(见下文) 值, 以及第二个 U+0022 QUOTATION MARK 字符(")。

      上一段中属性的序列化名称 必须这样确定:

      如果该属性没有命名空间

      该属性的序列化名称为该属性的 局部名。

      对于由 HTML 解析器Element.setAttribute() 设置的 HTML 元素 上的属性,局部名 将会是小写的。

      如果该属性在 XML 命名空间

      该属性的序列化名称是:字符串 "xml:" 紧跟着该属性的 局部名。

      如果该属性在 XMLNS 命名空间 且该属性的 局部名 是 xmlns

      该属性的序列化名称为字符串 "xmlns"。

      如果该属性在 XMLNS 命名空间 且该属性的 局部名 不是xmlns

      该属性的序列化名称为字符串 "xmlns:" 紧跟着该属性的 局部名。

      如果该属性在 XLink 命名空间

      该属性的序列化名称为字符串 "xlink:" 紧跟着该属性的 局部名。

      如果该属性在其他命名空间

      该属性的序列化名称为该属性的 qualified name。

      尽管真正的属性顺序是 UA 定义的,也依赖于其他一些因素,比如原始标记中属性的给出顺序, 但是排序次序必须是稳定的,这样对该算法的连续调用中,元素属性的序列化采取同样的次序。

      追加一个 U+003E GREATER-THAN SIGN 字符(>)。

      如果 当前节点 是一个 areabase, basefontbgsoundbrcol, embedframehrimg, inputkeygenlinkmeta, paramsourcetrackwbr 元素, 则继续处理下一个子元素。

      当前节点 的元素上执行 HTML 片段序列化算法 (以此递归进入该元素),紧跟着一个 U+003C LESS-THAN SIGN 字符(<),一个 U+002F SOLIDUS 字符 (/),再来一个 tagname ,最后是一个 U+003E GREATER-THAN SIGN 字符(>)。

      如果 当前节点是一个 Text 节点

      如果 当前节点 的父节点是一个 style, scriptxmpiframenoembed, noframes,或 plaintext 元素,或者 当前节点 的父节点是一个 noscript 元素且该节点的 脚本被启用,则追加 当前节点data IDL 属性的字面值。

      否则,追加 当前节点data IDL 属性的 转义(见下文)后的值。

      如果 当前节点是一个 Comment

      追加字面字符串 "<!--"(U+003C LESS-THAN SIGN,U+0021 EXCLAMATION MARK,U+002D HYPHEN-MINUS,U+002D HYPHEN-MINUS),再加 当前节点data IDL 属性的值,再加字面字符串 "-->" (U+002D HYPHEN-MINUS,U+002D HYPHEN-MINUS, U+003E GREATER-THAN SIGN)。

      如果 当前节点 是一个 ProcessingInstruction

      追加字面字符串 "<?"(U+003C LESS-THAN SIGN,U+003F QUESTION MARK),再加 当前节点target IDL 属性的值, 再加一个 U+0020 SPACE 字符,再加 当前节点data IDL 属性的值, 再加一个 U+003E GREATER-THAN SIGN 字符(>)。

      如果 当前节点是一个 DocumentType

      追加字面字符串 "<!DOCTYPE"(U+003C LESS-THAN SIGN,U+0021 EXCLAMATION MARK,U+0044 LATIN CAPITAL LETTER D,U+004F LATIN CAPITAL LETTER O,U+0043 LATIN CAPITAL LETTER C,U+0054 LATIN CAPITAL LETTER T,U+0059 LATIN CAPITAL LETTER Y,U+0050 LATIN CAPITAL LETTER P,U+0045 LATIN CAPITAL LETTER E),再加一个空格(U+0020 SPACE), 再加 当前节点name IDL 属性的值, 再加字面字符串 ">"(U+003E GREATER-THAN SIGN)。

  4. 该算法的结果就是字符串 s

如果用 HTMl 解析器 解析, 该算法输出的可能不是原始的树结构。HTMl 解析器 本身也可以产生 序列化、重新解析后不能复原的树结构,虽然这些情形是不一致的而且很典型。

例如,对于一个有着 Comment 子节点的 textarea 元素, 先序列化后,再重新解析输出,注释将会显示在文本控件中。 类似地,作为 DOM 操作的结果, 如果某个元素内部的注释中包含字面字符串"-->",那么解析该元素序列化的结果之后, 该注释将会从那一点截断,剩余的注释将会解释为标记。还有很多类似的例子,比如: script 元素包含的 Text 节点包含字符串 "</script>" 的情况、 p 元素包含 ul 元素的情况(ul 元素的 开始标签 意味着 p 的结束标签)。

这可能引起跨站脚本攻击。一个例子是页面让用户输入一些字体家族的名称, 它们稍后被通过 DOM 插入到 CSS style 块, 然后使用 innerHTML IDL 属性来获取那个 style 元素的 HTML 序列化。如果用户输入 "</style><script>attack</script>" 作为字体家族名称,innerHTML 返回的标记如果在不同的上下文进行解析, 将会包含一个 script 节点,即使原始 DOM 中不存在 script 节点。

例如,考虑下列标记:

<form id="outer"><div></form><form id="inner"><input>

这将被解析为:

input 元素将会关联到内部 form 元素。 现在如果序列化并重新解析这一树结构,<form id="inner"> 开始标签将被忽略, 所以 input 元素将会被关联到外部 form 元素上。

<html><head></head><body><form id="outer"><div><form id="inner"><input></form></div></form></body></html>

作为下一个例子,考虑下列标记:

<a><table><a>

将被解析为:

a 元素是嵌套的,因为第二个 a 元素是 foster parented。 经历序列化-再解析往返后, a 元素和 table 元素将会都变成兄弟节点,因为第二个 <a> 开始标签隐式地关闭了第一个 a 元素。

<html><head></head><body><a><a></a><table></table></a></body></html>

由于历史原因,即使(在前两个例子中)往返计算的标记可以是一致的,也不能保持 pretextarea,或 listing 元素中初始的 U+000A LINE FEED(LF)字符 HTML 解析器 在解析过程中会扔掉这样的字符, 但该算法 不会 序列化一个额外的 U+000A LINE FEED(LF)字符进去。

例如,考虑下列标记:

<pre>

Hello.</pre>

当该文档初次被解析时,pre 元素的 子文本内容 以一个换行字符起始。 经历序列化-再解析往返后,pre 元素的 子文本内容 会只是 "Hello."。

上述算法用到的 转义字符串 包含运行下列步骤:

  1. 将所有出现的 "&" 字符替换为字符串 "&amp;"。

  2. 将所有出现的 U+00A0 NO-BREAK SPACE 字符替换为字符串 "&nbsp;"。

  3. 如果算法在 属性模式 下调用的,将所有出现的 """ 字符替换为字符串 "&quot;"。

  4. 如果算法 不是属性模式 下调用的, 将所有出现的 "<" 字符替换为字符串 "&lt;", 且所有出现的 ">" 字符替换为字符串 "&gt;"。

13.4 解析 HTML 片段

下面的步骤构成了 HTML 片段解析算法。 该算法的输入包括一个 Element 元素,称为 context 元素, 它为解析器提供了上下文;以及一个 input,就是要解析的字符串。 返回一个包含0个或更多节点的列表。

在解析器这一部分的算法中标记为 fragment case 的部分, 是只在解析器是为该算法创建的时候才发生的。 该算法已经用这样的标记标注过,但只用于表达这样的信息,并没有规范的权重。 如果当解析器并非为本算法创建但仍然发生了 fragment case 描述的条件, 那么就是本规范中的一个错误。

  1. 创建一个新的 Document 节点,把它标记为 HTML 文档

  2. 如果 context 元素的 节点文档 处于 怪异模式, 那么令 Document 处于 怪异模式。 否则 context 元素的 节点文档 就处于 受限的怪异模式, 然后令 Document 处于 受限的怪异模式。 否则让 Document 处于 非怪异模式

  3. 创建一个新的 HTML 解析器, 并把它关联到刚创建的 Document 节点。

  4. 按下面的描述,根据 context 元素设置 HTML 解析器tokenization 阶段的状态:

    title
    textarea
    将 tokenizer 切换到 RCDATA 状态
    style
    xmp
    iframe
    noembed
    noframes
    将 tokenizer 切换到 RAWTEXT 状态
    script
    将 tokenizer 切换到 脚本数据状态
    noscript
    如果 脚本标志 处于启用状态, 将 tokenizer 切换到 RAWTEXT 状态。 否则,让 tokenizer 留在 数据状态
    plaintext
    将 tokenizer 切换到 纯文本状态
    任何其他元素
    将 tokenizer 留在 数据状态

    出于性能原因,不报告错误的实现,以及直接使用本规范中描述的实际状态机的实现, 可以(在上述提到的地方)使用 PLAINTEXT 状态,而不是 RAWTEXT 和脚本数据状态。 除了关于解析错误的规则之外,它们是等价的, 因为 fragment case 中没有 适当的结束标记, 所以它们涉及的状态转换少得多。

  5. root 为一个新的没有属性的 html 元素。

  6. root 元素添加到上面创建的 Document 节点中。

  7. 建立解析器的 打开元素栈, 让它只包含一个 root 元素。

  8. 如果 context 元素是一个 template,把 "in template" 压入 模板插入模式的栈, 这样它就变成了新的 当前模板插入模式

  9. 创建一个开始标签的标记,其名字为 context 的 local name,其属性为 context 的属性。

    令这个开始标签标记为 context 元素的开始标签标记, 比如可以用于确定是否是一个 HTML 集成点

  10. 适当地重置解析器的插入模式

    该算法中解析器会引用 context 元素。

  11. 设置解析器的 form 元素指针 为 离 context 元素最近的 form 元素节点(直接从祖先链向上找,包括该元素自己),如果有的话。 (如果没有这样的 form 元素, form 元素指针 就保持它的初始值 null)

  12. input 放到刚创建的 HTML 解析器输入流 中。字符编码的 信心irrelevant

  13. 启动这个解析器,让它开始运行直到消耗完刚才插入到输入流中的所有字符。

  14. 按照 树序 返回 root 的子节点。

13.5 Named character references

This table lists the character reference names that are supported by HTML, and the code points to which they refer. It is referenced by the previous sections.

It is intentional, for legacy compatibility, that many code points have multiple character reference names. For example, some appear both with and without the trailing semicolon, or with different capitalizations.

Name Character(s) Glyph
Aacute; U+000C1 Á
Aacute U+000C1 Á
aacute; U+000E1 á
aacute U+000E1 á
Abreve; U+00102 Ă
abreve; U+00103 ă
ac; U+0223E
acd; U+0223F
acE; U+0223E U+00333 ∾̳
Acirc; U+000C2 Â
Acirc U+000C2 Â
acirc; U+000E2 â
acirc U+000E2 â
acute; U+000B4 ´
acute U+000B4 ´
Acy; U+00410 А
acy; U+00430 а
AElig; U+000C6 Æ
AElig U+000C6 Æ
aelig; U+000E6 æ
aelig U+000E6 æ
af; U+02061
Afr; U+1D504 𝔄
afr; U+1D51E 𝔞
Agrave; U+000C0 À
Agrave U+000C0 À
agrave; U+000E0 à
agrave U+000E0 à
alefsym; U+02135
aleph; U+02135
Alpha; U+00391 Α
alpha; U+003B1 α
Amacr; U+00100 Ā
amacr; U+00101 ā
amalg; U+02A3F ⨿
AMP; U+00026 &
AMP U+00026 &
amp; U+00026 &
amp U+00026 &
And; U+02A53
and; U+02227
andand; U+02A55
andd; U+02A5C
andslope; U+02A58
andv; U+02A5A
ang; U+02220
ange; U+029A4
angle; U+02220
angmsd; U+02221
angmsdaa; U+029A8
angmsdab; U+029A9
angmsdac; U+029AA
angmsdad; U+029AB
angmsdae; U+029AC
angmsdaf; U+029AD
angmsdag; U+029AE
angmsdah; U+029AF
angrt; U+0221F
angrtvb; U+022BE
angrtvbd; U+0299D
angsph; U+02222
angst; U+000C5 Å
angzarr; U+0237C
Aogon; U+00104 Ą
aogon; U+00105 ą
Aopf; U+1D538 𝔸
aopf; U+1D552 𝕒
ap; U+02248
apacir; U+02A6F
apE; U+02A70
ape; U+0224A
apid; U+0224B
apos; U+00027 '
ApplyFunction; U+02061
approx; U+02248
approxeq; U+0224A
Aring; U+000C5 Å
Aring U+000C5 Å
aring; U+000E5 å
aring U+000E5 å
Ascr; U+1D49C 𝒜
ascr; U+1D4B6 𝒶
Assign; U+02254
ast; U+0002A *
asymp; U+02248
asympeq; U+0224D
Atilde; U+000C3 Ã
Atilde U+000C3 Ã
atilde; U+000E3 ã
atilde U+000E3 ã
Auml; U+000C4 Ä
Auml U+000C4 Ä
auml; U+000E4 ä
auml U+000E4 ä
awconint; U+02233
awint; U+02A11
backcong; U+0224C
backepsilon; U+003F6 ϶
backprime; U+02035
backsim; U+0223D
backsimeq; U+022CD
Backslash; U+02216
Barv; U+02AE7
barvee; U+022BD
Barwed; U+02306
barwed; U+02305
barwedge; U+02305
bbrk; U+023B5
bbrktbrk; U+023B6
bcong; U+0224C
Bcy; U+00411 Б
bcy; U+00431 б
bdquo; U+0201E
becaus; U+02235
Because; U+02235
because; U+02235
bemptyv; U+029B0
bepsi; U+003F6 ϶
bernou; U+0212C
Bernoullis; U+0212C
Beta; U+00392 Β
beta; U+003B2 β
beth; U+02136
between; U+0226C
Bfr; U+1D505 𝔅
bfr; U+1D51F 𝔟
bigcap; U+022C2
bigcirc; U+025EF
bigcup; U+022C3
bigodot; U+02A00
bigoplus; U+02A01
bigotimes; U+02A02
bigsqcup; U+02A06
bigstar; U+02605
bigtriangledown; U+025BD
bigtriangleup; U+025B3
biguplus; U+02A04
bigvee; U+022C1
bigwedge; U+022C0
bkarow; U+0290D
blacklozenge; U+029EB
blacksquare; U+025AA
blacktriangle; U+025B4
blacktriangledown; U+025BE
blacktriangleleft; U+025C2
blacktriangleright; U+025B8
blank; U+02423
blk12; U+02592
blk14; U+02591
blk34; U+02593
block; U+02588
bne; U+0003D U+020E5 =⃥
bnequiv; U+02261 U+020E5 ≡⃥
bNot; U+02AED
bnot; U+02310
Bopf; U+1D539 𝔹
bopf; U+1D553 𝕓
bot; U+022A5
bottom; U+022A5
bowtie; U+022C8
boxbox; U+029C9
boxDL; U+02557
boxDl; U+02556
boxdL; U+02555
boxdl; U+02510
boxDR; U+02554
boxDr; U+02553
boxdR; U+02552
boxdr; U+0250C
boxH; U+02550
boxh; U+02500
boxHD; U+02566
boxHd; U+02564
boxhD; U+02565
boxhd; U+0252C
boxHU; U+02569
boxHu; U+02567
boxhU; U+02568
boxhu; U+02534
boxminus; U+0229F
boxplus; U+0229E
boxtimes; U+022A0
boxUL; U+0255D
boxUl; U+0255C
boxuL; U+0255B
boxul; U+02518
boxUR; U+0255A
boxUr; U+02559
boxuR; U+02558
boxur; U+02514
boxV; U+02551
boxv; U+02502
boxVH; U+0256C
boxVh; U+0256B
boxvH; U+0256A
boxvh; U+0253C
boxVL; U+02563
boxVl; U+02562
boxvL; U+02561
boxvl; U+02524
boxVR; U+02560
boxVr; U+0255F
boxvR; U+0255E
boxvr; U+0251C
bprime; U+02035
Breve; U+002D8 ˘
breve; U+002D8 ˘
brvbar; U+000A6 ¦
brvbar U+000A6 ¦
Bscr; U+0212C
bscr; U+1D4B7 𝒷
bsemi; U+0204F
bsim; U+0223D
bsime; U+022CD
bsol; U+0005C \
bsolb; U+029C5
bsolhsub; U+027C8
bull; U+02022
bullet; U+02022
bump; U+0224E
bumpE; U+02AAE
bumpe; U+0224F
Bumpeq; U+0224E
bumpeq; U+0224F
Cacute; U+00106 Ć
cacute; U+00107 ć
Cap; U+022D2
cap; U+02229
capand; U+02A44
capbrcup; U+02A49
capcap; U+02A4B
capcup; U+02A47
capdot; U+02A40
CapitalDifferentialD; U+02145
caps; U+02229 U+0FE00 ∩︀
caret; U+02041
caron; U+002C7 ˇ
Cayleys; U+0212D
ccaps; U+02A4D
Ccaron; U+0010C Č
ccaron; U+0010D č
Ccedil; U+000C7 Ç
Ccedil U+000C7 Ç
ccedil; U+000E7 ç
ccedil U+000E7 ç
Ccirc; U+00108 Ĉ
ccirc; U+00109 ĉ
Cconint; U+02230
ccups; U+02A4C
ccupssm; U+02A50
Cdot; U+0010A Ċ
cdot; U+0010B ċ
cedil; U+000B8 ¸
cedil U+000B8 ¸
Cedilla; U+000B8 ¸
cemptyv; U+029B2
cent; U+000A2 ¢
cent U+000A2 ¢
CenterDot; U+000B7 ·
centerdot; U+000B7 ·
Cfr; U+0212D
cfr; U+1D520 𝔠
CHcy; U+00427 Ч
chcy; U+00447 ч
check; U+02713
checkmark; U+02713
Chi; U+003A7 Χ
chi; U+003C7 χ
cir; U+025CB
circ; U+002C6 ˆ
circeq; U+02257
circlearrowleft; U+021BA
circlearrowright; U+021BB
circledast; U+0229B
circledcirc; U+0229A
circleddash; U+0229D
CircleDot; U+02299
circledR; U+000AE ®
circledS; U+024C8
CircleMinus; U+02296
CirclePlus; U+02295
CircleTimes; U+02297
cirE; U+029C3
cire; U+02257
cirfnint; U+02A10
cirmid; U+02AEF
cirscir; U+029C2
ClockwiseContourIntegral; U+02232
CloseCurlyDoubleQuote; U+0201D
CloseCurlyQuote; U+02019
clubs; U+02663
clubsuit; U+02663
Colon; U+02237
colon; U+0003A :
Colone; U+02A74
colone; U+02254
coloneq; U+02254
comma; U+0002C ,
commat; U+00040 @
comp; U+02201
compfn; U+02218
complement; U+02201
complexes; U+02102
cong; U+02245
congdot; U+02A6D
Congruent; U+02261
Conint; U+0222F
conint; U+0222E
ContourIntegral; U+0222E
Copf; U+02102
copf; U+1D554 𝕔
coprod; U+02210
Coproduct; U+02210
COPY; U+000A9 ©
COPY U+000A9 ©
copy; U+000A9 ©
copy U+000A9 ©
copysr; U+02117
CounterClockwiseContourIntegral; U+02233
crarr; U+021B5
Cross; U+02A2F
cross; U+02717
Cscr; U+1D49E 𝒞
cscr; U+1D4B8 𝒸
csub; U+02ACF
csube; U+02AD1
csup; U+02AD0
csupe; U+02AD2
ctdot; U+022EF
cudarrl; U+02938
cudarrr; U+02935
cuepr; U+022DE
cuesc; U+022DF
cularr; U+021B6
cularrp; U+0293D
Cup; U+022D3
cup; U+0222A
cupbrcap; U+02A48
CupCap; U+0224D
cupcap; U+02A46
cupcup; U+02A4A
cupdot; U+0228D
cupor; U+02A45
cups; U+0222A U+0FE00 ∪︀
curarr; U+021B7
curarrm; U+0293C
curlyeqprec; U+022DE
curlyeqsucc; U+022DF
curlyvee; U+022CE
curlywedge; U+022CF
curren; U+000A4 ¤
curren U+000A4 ¤
curvearrowleft; U+021B6
curvearrowright; U+021B7
cuvee; U+022CE
cuwed; U+022CF
cwconint; U+02232
cwint; U+02231
cylcty; U+0232D
Dagger; U+02021
dagger; U+02020
daleth; U+02138
Darr; U+021A1
dArr; U+021D3
darr; U+02193
dash; U+02010
Dashv; U+02AE4
dashv; U+022A3
dbkarow; U+0290F
dblac; U+002DD ˝
Dcaron; U+0010E Ď
dcaron; U+0010F ď
Dcy; U+00414 Д
dcy; U+00434 д
DD; U+02145
dd; U+02146
ddagger; U+02021
ddarr; U+021CA
DDotrahd; U+02911
ddotseq; U+02A77
deg; U+000B0 °
deg U+000B0 °
Del; U+02207
Delta; U+00394 Δ
delta; U+003B4 δ
demptyv; U+029B1
dfisht; U+0297F ⥿
Dfr; U+1D507 𝔇
dfr; U+1D521 𝔡
dHar; U+02965
dharl; U+021C3
dharr; U+021C2
DiacriticalAcute; U+000B4 ´
DiacriticalDot; U+002D9 ˙
DiacriticalDoubleAcute; U+002DD ˝
DiacriticalGrave; U+00060 `
DiacriticalTilde; U+002DC ˜
diam; U+022C4
Diamond; U+022C4
diamond; U+022C4
diamondsuit; U+02666
diams; U+02666
die; U+000A8 ¨
DifferentialD; U+02146
digamma; U+003DD ϝ
disin; U+022F2
div; U+000F7 ÷
divide; U+000F7 ÷
divide U+000F7 ÷
divideontimes; U+022C7
divonx; U+022C7
DJcy; U+00402 Ђ
djcy; U+00452 ђ
dlcorn; U+0231E
dlcrop; U+0230D
dollar; U+00024 $
Dopf; U+1D53B 𝔻
dopf; U+1D555 𝕕
Dot; U+000A8 ¨
dot; U+002D9 ˙
DotDot; U+020DC ◌⃜
doteq; U+02250
doteqdot; U+02251
DotEqual; U+02250
dotminus; U+02238
dotplus; U+02214
dotsquare; U+022A1
doublebarwedge; U+02306
DoubleContourIntegral; U+0222F
DoubleDot; U+000A8 ¨
DoubleDownArrow; U+021D3
DoubleLeftArrow; U+021D0
DoubleLeftRightArrow; U+021D4
DoubleLeftTee; U+02AE4
DoubleLongLeftArrow; U+027F8
DoubleLongLeftRightArrow; U+027FA
DoubleLongRightArrow; U+027F9
DoubleRightArrow; U+021D2
DoubleRightTee; U+022A8
DoubleUpArrow; U+021D1
DoubleUpDownArrow; U+021D5
DoubleVerticalBar; U+02225
DownArrow; U+02193
Downarrow; U+021D3
downarrow; U+02193
DownArrowBar; U+02913
DownArrowUpArrow; U+021F5
DownBreve; U+00311 ◌̑
downdownarrows; U+021CA
downharpoonleft; U+021C3
downharpoonright; U+021C2
DownLeftRightVector; U+02950
DownLeftTeeVector; U+0295E
DownLeftVector; U+021BD
DownLeftVectorBar; U+02956
DownRightTeeVector; U+0295F
DownRightVector; U+021C1
DownRightVectorBar; U+02957
DownTee; U+022A4
DownTeeArrow; U+021A7
drbkarow; U+02910
drcorn; U+0231F
drcrop; U+0230C
Dscr; U+1D49F 𝒟
dscr; U+1D4B9 𝒹
DScy; U+00405 Ѕ
dscy; U+00455 ѕ
dsol; U+029F6
Dstrok; U+00110 Đ
dstrok; U+00111 đ
dtdot; U+022F1
dtri; U+025BF
dtrif; U+025BE
duarr; U+021F5
duhar; U+0296F
dwangle; U+029A6
DZcy; U+0040F Џ
dzcy; U+0045F џ
dzigrarr; U+027FF
Eacute; U+000C9 É
Eacute U+000C9 É
eacute; U+000E9 é
eacute U+000E9 é
easter; U+02A6E
Ecaron; U+0011A Ě
ecaron; U+0011B ě
ecir; U+02256
Ecirc; U+000CA Ê
Ecirc U+000CA Ê
ecirc; U+000EA ê
ecirc U+000EA ê
ecolon; U+02255
Ecy; U+0042D Э
ecy; U+0044D э
eDDot; U+02A77
Edot; U+00116 Ė
eDot; U+02251
edot; U+00117 ė
ee; U+02147
efDot; U+02252
Efr; U+1D508 𝔈
efr; U+1D522 𝔢
eg; U+02A9A
Egrave; U+000C8 È
Egrave U+000C8 È
egrave; U+000E8 è
egrave U+000E8 è
egs; U+02A96
egsdot; U+02A98
el; U+02A99
Element; U+02208
elinters; U+023E7
ell; U+02113
els; U+02A95
elsdot; U+02A97
Emacr; U+00112 Ē
emacr; U+00113 ē
empty; U+02205
emptyset; U+02205
EmptySmallSquare; U+025FB
emptyv; U+02205
EmptyVerySmallSquare; U+025AB
emsp; U+02003
emsp13; U+02004
emsp14; U+02005
ENG; U+0014A Ŋ
eng; U+0014B ŋ
ensp; U+02002
Eogon; U+00118 Ę
eogon; U+00119 ę
Eopf; U+1D53C 𝔼
eopf; U+1D556 𝕖
epar; U+022D5
eparsl; U+029E3
eplus; U+02A71
epsi; U+003B5 ε
Epsilon; U+00395 Ε
epsilon; U+003B5 ε
epsiv; U+003F5 ϵ
eqcirc; U+02256
eqcolon; U+02255
eqsim; U+02242
eqslantgtr; U+02A96
eqslantless; U+02A95
Equal; U+02A75
equals; U+0003D =
EqualTilde; U+02242
equest; U+0225F
Equilibrium; U+021CC
equiv; U+02261
equivDD; U+02A78
eqvparsl; U+029E5
erarr; U+02971
erDot; U+02253
Escr; U+02130
escr; U+0212F
esdot; U+02250
Esim; U+02A73
esim; U+02242
Eta; U+00397 Η
eta; U+003B7 η
ETH; U+000D0 Ð
ETH U+000D0 Ð
eth; U+000F0 ð
eth U+000F0 ð
Euml; U+000CB Ë
Euml U+000CB Ë
euml; U+000EB ë
euml U+000EB ë
euro; U+020AC
excl; U+00021 !
exist; U+02203
Exists; U+02203
expectation; U+02130
ExponentialE; U+02147
exponentiale; U+02147
fallingdotseq; U+02252
Fcy; U+00424 Ф
fcy; U+00444 ф
female; U+02640
ffilig; U+0FB03
fflig; U+0FB00
ffllig; U+0FB04
Ffr; U+1D509 𝔉
ffr; U+1D523 𝔣
filig; U+0FB01
FilledSmallSquare; U+025FC
FilledVerySmallSquare; U+025AA
fjlig; U+00066 U+0006A fj
flat; U+0266D
fllig; U+0FB02
fltns; U+025B1
fnof; U+00192 ƒ
Fopf; U+1D53D 𝔽
fopf; U+1D557 𝕗
ForAll; U+02200
forall; U+02200
fork; U+022D4
forkv; U+02AD9
Fouriertrf; U+02131
fpartint; U+02A0D
frac12; U+000BD ½
frac12 U+000BD ½
frac13; U+02153
frac14; U+000BC ¼
frac14 U+000BC ¼
frac15; U+02155
frac16; U+02159
frac18; U+0215B
frac23; U+02154
frac25; U+02156
frac34; U+000BE ¾
frac34 U+000BE ¾
frac35; U+02157
frac38; U+0215C
frac45; U+02158
frac56; U+0215A
frac58; U+0215D
frac78; U+0215E
frasl; U+02044
frown; U+02322
Fscr; U+02131
fscr; U+1D4BB 𝒻
gacute; U+001F5 ǵ
Gamma; U+00393 Γ
gamma; U+003B3 γ
Gammad; U+003DC Ϝ
gammad; U+003DD ϝ
gap; U+02A86
Gbreve; U+0011E Ğ
gbreve; U+0011F ğ
Gcedil; U+00122 Ģ
Gcirc; U+0011C Ĝ
gcirc; U+0011D ĝ
Gcy; U+00413 Г
gcy; U+00433 г
Gdot; U+00120 Ġ
gdot; U+00121 ġ
gE; U+02267
ge; U+02265
gEl; U+02A8C
gel; U+022DB
geq; U+02265
geqq; U+02267
geqslant; U+02A7E
ges; U+02A7E
gescc; U+02AA9
gesdot; U+02A80
gesdoto; U+02A82
gesdotol; U+02A84
gesl; U+022DB U+0FE00 ⋛︀
gesles; U+02A94
Gfr; U+1D50A 𝔊
gfr; U+1D524 𝔤
Gg; U+022D9
gg; U+0226B
ggg; U+022D9
gimel; U+02137
GJcy; U+00403 Ѓ
gjcy; U+00453 ѓ
gl; U+02277
gla; U+02AA5
glE; U+02A92
glj; U+02AA4
gnap; U+02A8A
gnapprox; U+02A8A
gnE; U+02269
gne; U+02A88
gneq; U+02A88
gneqq; U+02269
gnsim; U+022E7
Gopf; U+1D53E 𝔾
gopf; U+1D558 𝕘
grave; U+00060 `
GreaterEqual; U+02265
GreaterEqualLess; U+022DB
GreaterFullEqual; U+02267
GreaterGreater; U+02AA2
GreaterLess; U+02277
GreaterSlantEqual; U+02A7E
GreaterTilde; U+02273
Gscr; U+1D4A2 𝒢
gscr; U+0210A
gsim; U+02273
gsime; U+02A8E
gsiml; U+02A90
GT; U+0003E >
GT U+0003E >
Gt; U+0226B
gt; U+0003E >
gt U+0003E >
gtcc; U+02AA7
gtcir; U+02A7A
gtdot; U+022D7
gtlPar; U+02995
gtquest; U+02A7C
gtrapprox; U+02A86
gtrarr; U+02978
gtrdot; U+022D7
gtreqless; U+022DB
gtreqqless; U+02A8C
gtrless; U+02277
gtrsim; U+02273
gvertneqq; U+02269 U+0FE00 ≩︀
gvnE; U+02269 U+0FE00 ≩︀
Hacek; U+002C7 ˇ
hairsp; U+0200A
half; U+000BD ½
hamilt; U+0210B
HARDcy; U+0042A Ъ
hardcy; U+0044A ъ
hArr; U+021D4
harr; U+02194
harrcir; U+02948
harrw; U+021AD
Hat; U+0005E ^
hbar; U+0210F
Hcirc; U+00124 Ĥ
hcirc; U+00125 ĥ
hearts; U+02665
heartsuit; U+02665
hellip; U+02026
hercon; U+022B9
Hfr; U+0210C
hfr; U+1D525 𝔥
HilbertSpace; U+0210B
hksearow; U+02925
hkswarow; U+02926
hoarr; U+021FF
homtht; U+0223B
hookleftarrow; U+021A9
hookrightarrow; U+021AA
Hopf; U+0210D
hopf; U+1D559 𝕙
horbar; U+02015
HorizontalLine; U+02500
Hscr; U+0210B
hscr; U+1D4BD 𝒽
hslash; U+0210F
Hstrok; U+00126 Ħ
hstrok; U+00127 ħ
HumpDownHump; U+0224E
HumpEqual; U+0224F
hybull; U+02043
hyphen; U+02010
Iacute; U+000CD Í
Iacute U+000CD Í
iacute; U+000ED í
iacute U+000ED í
ic; U+02063
Icirc; U+000CE Î
Icirc U+000CE Î
icirc; U+000EE î
icirc U+000EE î
Icy; U+00418 И
icy; U+00438 и
Idot; U+00130 İ
IEcy; U+00415 Е
iecy; U+00435 е
iexcl; U+000A1 ¡
iexcl U+000A1 ¡
iff; U+021D4
Ifr; U+02111
ifr; U+1D526 𝔦
Igrave; U+000CC Ì
Igrave U+000CC Ì
igrave; U+000EC ì
igrave U+000EC ì
ii; U+02148
iiiint; U+02A0C
iiint; U+0222D
iinfin; U+029DC
iiota; U+02129
IJlig; U+00132 IJ
ijlig; U+00133 ij
Im; U+02111
Imacr; U+0012A Ī
imacr; U+0012B ī
image; U+02111
ImaginaryI; U+02148
imagline; U+02110
imagpart; U+02111
imath; U+00131 ı
imof; U+022B7
imped; U+001B5 Ƶ
Implies; U+021D2
in; U+02208
incare; U+02105
infin; U+0221E
infintie; U+029DD
inodot; U+00131 ı
Int; U+0222C
int; U+0222B
intcal; U+022BA
integers; U+02124
Integral; U+0222B
intercal; U+022BA
Intersection; U+022C2
intlarhk; U+02A17
intprod; U+02A3C
InvisibleComma; U+02063
InvisibleTimes; U+02062
IOcy; U+00401 Ё
iocy; U+00451 ё
Iogon; U+0012E Į
iogon; U+0012F į
Iopf; U+1D540 𝕀
iopf; U+1D55A 𝕚
Iota; U+00399 Ι
iota; U+003B9 ι
iprod; U+02A3C
iquest; U+000BF ¿
iquest U+000BF ¿
Iscr; U+02110
iscr; U+1D4BE 𝒾
isin; U+02208
isindot; U+022F5
isinE; U+022F9
isins; U+022F4
isinsv; U+022F3
isinv; U+02208
it; U+02062
Itilde; U+00128 Ĩ
itilde; U+00129 ĩ
Iukcy; U+00406 І
iukcy; U+00456 і
Iuml; U+000CF Ï
Iuml U+000CF Ï
iuml; U+000EF ï
iuml U+000EF ï
Jcirc; U+00134 Ĵ
jcirc; U+00135 ĵ
Jcy; U+00419 Й
jcy; U+00439 й
Jfr; U+1D50D 𝔍
jfr; U+1D527 𝔧
jmath; U+00237 ȷ
Jopf; U+1D541 𝕁
jopf; U+1D55B 𝕛
Jscr; U+1D4A5 𝒥
jscr; U+1D4BF 𝒿
Jsercy; U+00408 Ј
jsercy; U+00458 ј
Jukcy; U+00404 Є
jukcy; U+00454 є
Kappa; U+0039A Κ
kappa; U+003BA κ
kappav; U+003F0 ϰ
Kcedil; U+00136 Ķ
kcedil; U+00137 ķ
Kcy; U+0041A К
kcy; U+0043A к
Kfr; U+1D50E 𝔎
kfr; U+1D528 𝔨
kgreen; U+00138 ĸ
KHcy; U+00425 Х
khcy; U+00445 х
KJcy; U+0040C Ќ
kjcy; U+0045C ќ
Kopf; U+1D542 𝕂
kopf; U+1D55C 𝕜
Kscr; U+1D4A6 𝒦
kscr; U+1D4C0 𝓀
lAarr; U+021DA
Lacute; U+00139 Ĺ
lacute; U+0013A ĺ
laemptyv; U+029B4
lagran; U+02112
Lambda; U+0039B Λ
lambda; U+003BB λ
Lang; U+027EA
lang; U+027E8
langd; U+02991
langle; U+027E8
lap; U+02A85
Laplacetrf; U+02112
laquo; U+000AB «
laquo U+000AB «
Larr; U+0219E
lArr; U+021D0
larr; U+02190
larrb; U+021E4
larrbfs; U+0291F
larrfs; U+0291D
larrhk; U+021A9
larrlp; U+021AB
larrpl; U+02939
larrsim; U+02973
larrtl; U+021A2
lat; U+02AAB
lAtail; U+0291B
latail; U+02919
late; U+02AAD
lates; U+02AAD U+0FE00 ⪭︀
lBarr; U+0290E
lbarr; U+0290C
lbbrk; U+02772
lbrace; U+0007B {
lbrack; U+0005B [
lbrke; U+0298B
lbrksld; U+0298F
lbrkslu; U+0298D
Lcaron; U+0013D Ľ
lcaron; U+0013E ľ
Lcedil; U+0013B Ļ
lcedil; U+0013C ļ
lceil; U+02308
lcub; U+0007B {
Lcy; U+0041B Л
lcy; U+0043B л
ldca; U+02936
ldquo; U+0201C
ldquor; U+0201E
ldrdhar; U+02967
ldrushar; U+0294B
ldsh; U+021B2
lE; U+02266
le; U+02264
LeftAngleBracket; U+027E8
LeftArrow; U+02190
Leftarrow; U+021D0
leftarrow; U+02190
LeftArrowBar; U+021E4
LeftArrowRightArrow; U+021C6
leftarrowtail; U+021A2
LeftCeiling; U+02308
LeftDoubleBracket; U+027E6
LeftDownTeeVector; U+02961
LeftDownVector; U+021C3
LeftDownVectorBar; U+02959
LeftFloor; U+0230A
leftharpoondown; U+021BD
leftharpoonup; U+021BC
leftleftarrows; U+021C7
LeftRightArrow; U+02194
Leftrightarrow; U+021D4
leftrightarrow; U+02194
leftrightarrows; U+021C6
leftrightharpoons; U+021CB
leftrightsquigarrow; U+021AD
LeftRightVector; U+0294E
LeftTee; U+022A3
LeftTeeArrow; U+021A4
LeftTeeVector; U+0295A
leftthreetimes; U+022CB
LeftTriangle; U+022B2
LeftTriangleBar; U+029CF
LeftTriangleEqual; U+022B4
LeftUpDownVector; U+02951
LeftUpTeeVector; U+02960
LeftUpVector; U+021BF
LeftUpVectorBar; U+02958
LeftVector; U+021BC
LeftVectorBar; U+02952
lEg; U+02A8B
leg; U+022DA
leq; U+02264
leqq; U+02266
leqslant; U+02A7D
les; U+02A7D
lescc; U+02AA8
lesdot; U+02A7F ⩿
lesdoto; U+02A81
lesdotor; U+02A83
lesg; U+022DA U+0FE00 ⋚︀
lesges; U+02A93
lessapprox; U+02A85
lessdot; U+022D6
lesseqgtr; U+022DA
lesseqqgtr; U+02A8B
LessEqualGreater; U+022DA
LessFullEqual; U+02266
LessGreater; U+02276
lessgtr; U+02276
LessLess; U+02AA1
lesssim; U+02272
LessSlantEqual; U+02A7D
LessTilde; U+02272
lfisht; U+0297C
lfloor; U+0230A
Lfr; U+1D50F 𝔏
lfr; U+1D529 𝔩
lg; U+02276
lgE; U+02A91
lHar; U+02962
lhard; U+021BD
lharu; U+021BC
lharul; U+0296A
lhblk; U+02584
LJcy; U+00409 Љ
ljcy; U+00459 љ
Ll; U+022D8
ll; U+0226A
llarr; U+021C7
llcorner; U+0231E
Lleftarrow; U+021DA
llhard; U+0296B
lltri; U+025FA
Lmidot; U+0013F Ŀ
lmidot; U+00140 ŀ
lmoust; U+023B0
lmoustache; U+023B0
lnap; U+02A89
lnapprox; U+02A89
lnE; U+02268
lne; U+02A87
lneq; U+02A87
lneqq; U+02268
lnsim; U+022E6
loang; U+027EC
loarr; U+021FD
lobrk; U+027E6
LongLeftArrow; U+027F5
Longleftarrow; U+027F8
longleftarrow; U+027F5
LongLeftRightArrow; U+027F7
Longleftrightarrow; U+027FA
longleftrightarrow; U+027F7
longmapsto; U+027FC
LongRightArrow; U+027F6
Longrightarrow; U+027F9
longrightarrow; U+027F6
looparrowleft; U+021AB
looparrowright; U+021AC
lopar; U+02985
Lopf; U+1D543 𝕃
lopf; U+1D55D 𝕝
loplus; U+02A2D
lotimes; U+02A34
lowast; U+02217
lowbar; U+0005F _
LowerLeftArrow; U+02199
LowerRightArrow; U+02198
loz; U+025CA
lozenge; U+025CA
lozf; U+029EB
lpar; U+00028 (
lparlt; U+02993
lrarr; U+021C6
lrcorner; U+0231F
lrhar; U+021CB
lrhard; U+0296D
lrm; U+0200E
lrtri; U+022BF
lsaquo; U+02039
Lscr; U+02112
lscr; U+1D4C1 𝓁
Lsh; U+021B0
lsh; U+021B0
lsim; U+02272
lsime; U+02A8D
lsimg; U+02A8F
lsqb; U+0005B [
lsquo; U+02018
lsquor; U+0201A
Lstrok; U+00141 Ł
lstrok; U+00142 ł
LT; U+0003C <
LT U+0003C <
Lt; U+0226A
lt; U+0003C <
lt U+0003C <
ltcc; U+02AA6
ltcir; U+02A79
ltdot; U+022D6
lthree; U+022CB
ltimes; U+022C9
ltlarr; U+02976
ltquest; U+02A7B
ltri; U+025C3
ltrie; U+022B4
ltrif; U+025C2
ltrPar; U+02996
lurdshar; U+0294A
luruhar; U+02966
lvertneqq; U+02268 U+0FE00 ≨︀
lvnE; U+02268 U+0FE00 ≨︀
macr; U+000AF ¯
macr U+000AF ¯
male; U+02642
malt; U+02720
maltese; U+02720
Map; U+02905
map; U+021A6
mapsto; U+021A6
mapstodown; U+021A7
mapstoleft; U+021A4
mapstoup; U+021A5
marker; U+025AE
mcomma; U+02A29
Mcy; U+0041C М
mcy; U+0043C м
mdash; U+02014
mDDot; U+0223A
measuredangle; U+02221
MediumSpace; U+0205F
Mellintrf; U+02133
Mfr; U+1D510 𝔐
mfr; U+1D52A 𝔪
mho; U+02127
micro; U+000B5 µ
micro U+000B5 µ
mid; U+02223
midast; U+0002A *
midcir; U+02AF0
middot; U+000B7 ·
middot U+000B7 ·
minus; U+02212
minusb; U+0229F
minusd; U+02238
minusdu; U+02A2A
MinusPlus; U+02213
mlcp; U+02ADB
mldr; U+02026
mnplus; U+02213
models; U+022A7
Mopf; U+1D544 𝕄
mopf; U+1D55E 𝕞
mp; U+02213
Mscr; U+02133
mscr; U+1D4C2 𝓂
mstpos; U+0223E
Mu; U+0039C Μ
mu; U+003BC μ
multimap; U+022B8
mumap; U+022B8
nabla; U+02207
Nacute; U+00143 Ń
nacute; U+00144 ń
nang; U+02220 U+020D2 ∠⃒
nap; U+02249
napE; U+02A70 U+00338 ⩰̸
napid; U+0224B U+00338 ≋̸
napos; U+00149 ʼn
napprox; U+02249
natur; U+0266E
natural; U+0266E
naturals; U+02115
nbsp; U+000A0  
nbsp U+000A0  
nbump; U+0224E U+00338 ≎̸
nbumpe; U+0224F U+00338 ≏̸
ncap; U+02A43
Ncaron; U+00147 Ň
ncaron; U+00148 ň
Ncedil; U+00145 Ņ
ncedil; U+00146 ņ
ncong; U+02247
ncongdot; U+02A6D U+00338 ⩭̸
ncup; U+02A42
Ncy; U+0041D Н
ncy; U+0043D н
ndash; U+02013
ne; U+02260
nearhk; U+02924
neArr; U+021D7
nearr; U+02197
nearrow; U+02197
nedot; U+02250 U+00338 ≐̸
NegativeMediumSpace; U+0200B
NegativeThickSpace; U+0200B
NegativeThinSpace; U+0200B
NegativeVeryThinSpace; U+0200B
nequiv; U+02262
nesear; U+02928
nesim; U+02242 U+00338 ≂̸
NestedGreaterGreater; U+0226B
NestedLessLess; U+0226A
NewLine; U+0000A
nexist; U+02204
nexists; U+02204
Nfr; U+1D511 𝔑
nfr; U+1D52B 𝔫
ngE; U+02267 U+00338 ≧̸
nge; U+02271
ngeq; U+02271
ngeqq; U+02267 U+00338 ≧̸
ngeqslant; U+02A7E U+00338 ⩾̸
nges; U+02A7E U+00338 ⩾̸
nGg; U+022D9 U+00338 ⋙̸
ngsim; U+02275
nGt; U+0226B U+020D2 ≫⃒
ngt; U+0226F
ngtr; U+0226F
nGtv; U+0226B U+00338 ≫̸
nhArr; U+021CE
nharr; U+021AE
nhpar; U+02AF2
ni; U+0220B
nis; U+022FC
nisd; U+022FA
niv; U+0220B
NJcy; U+0040A Њ
njcy; U+0045A њ
nlArr; U+021CD
nlarr; U+0219A
nldr; U+02025
nlE; U+02266 U+00338 ≦̸
nle; U+02270
nLeftarrow; U+021CD
nleftarrow; U+0219A
nLeftrightarrow; U+021CE
nleftrightarrow; U+021AE
nleq; U+02270
nleqq; U+02266 U+00338 ≦̸
nleqslant; U+02A7D U+00338 ⩽̸
nles; U+02A7D U+00338 ⩽̸
nless; U+0226E
nLl; U+022D8 U+00338 ⋘̸
nlsim; U+02274
nLt; U+0226A U+020D2 ≪⃒
nlt; U+0226E
nltri; U+022EA
nltrie; U+022EC
nLtv; U+0226A U+00338 ≪̸
nmid; U+02224
NoBreak; U+02060
NonBreakingSpace; U+000A0  
Nopf; U+02115
nopf; U+1D55F 𝕟
Not; U+02AEC
not; U+000AC ¬
not U+000AC ¬
NotCongruent; U+02262
NotCupCap; U+0226D
NotDoubleVerticalBar; U+02226
NotElement; U+02209
NotEqual; U+02260
NotEqualTilde; U+02242 U+00338 ≂̸
NotExists; U+02204
NotGreater; U+0226F
NotGreaterEqual; U+02271
NotGreaterFullEqual; U+02267 U+00338 ≧̸
NotGreaterGreater; U+0226B U+00338 ≫̸
NotGreaterLess; U+02279
NotGreaterSlantEqual; U+02A7E U+00338 ⩾̸
NotGreaterTilde; U+02275
NotHumpDownHump; U+0224E U+00338 ≎̸
NotHumpEqual; U+0224F U+00338 ≏̸
notin; U+02209
notindot; U+022F5 U+00338 ⋵̸
notinE; U+022F9 U+00338 ⋹̸
notinva; U+02209
notinvb; U+022F7
notinvc; U+022F6
NotLeftTriangle; U+022EA
NotLeftTriangleBar; U+029CF U+00338 ⧏̸
NotLeftTriangleEqual; U+022EC
NotLess; U+0226E
NotLessEqual; U+02270
NotLessGreater; U+02278
NotLessLess; U+0226A U+00338 ≪̸
NotLessSlantEqual; U+02A7D U+00338 ⩽̸
NotLessTilde; U+02274
NotNestedGreaterGreater; U+02AA2 U+00338 ⪢̸
NotNestedLessLess; U+02AA1 U+00338 ⪡̸
notni; U+0220C
notniva; U+0220C
notnivb; U+022FE
notnivc; U+022FD
NotPrecedes; U+02280
NotPrecedesEqual; U+02AAF U+00338 ⪯̸
NotPrecedesSlantEqual; U+022E0
NotReverseElement; U+0220C
NotRightTriangle; U+022EB
NotRightTriangleBar; U+029D0 U+00338 ⧐̸
NotRightTriangleEqual; U+022ED
NotSquareSubset; U+0228F U+00338 ⊏̸
NotSquareSubsetEqual; U+022E2
NotSquareSuperset; U+02290 U+00338 ⊐̸
NotSquareSupersetEqual; U+022E3
NotSubset; U+02282 U+020D2 ⊂⃒
NotSubsetEqual; U+02288
NotSucceeds; U+02281
NotSucceedsEqual; U+02AB0 U+00338 ⪰̸
NotSucceedsSlantEqual; U+022E1
NotSucceedsTilde; U+0227F U+00338 ≿̸
NotSuperset; U+02283 U+020D2 ⊃⃒
NotSupersetEqual; U+02289
NotTilde; U+02241
NotTildeEqual; U+02244
NotTildeFullEqual; U+02247
NotTildeTilde; U+02249
NotVerticalBar; U+02224
npar; U+02226
nparallel; U+02226
nparsl; U+02AFD U+020E5 ⫽⃥
npart; U+02202 U+00338 ∂̸
npolint; U+02A14
npr; U+02280
nprcue; U+022E0
npre; U+02AAF U+00338 ⪯̸
nprec; U+02280
npreceq; U+02AAF U+00338 ⪯̸
nrArr; U+021CF
nrarr; U+0219B
nrarrc; U+02933 U+00338 ⤳̸
nrarrw; U+0219D U+00338 ↝̸
nRightarrow; U+021CF
nrightarrow; U+0219B
nrtri; U+022EB
nrtrie; U+022ED
nsc; U+02281
nsccue; U+022E1
nsce; U+02AB0 U+00338 ⪰̸
Nscr; U+1D4A9 𝒩
nscr; U+1D4C3 𝓃
nshortmid; U+02224
nshortparallel; U+02226
nsim; U+02241
nsime; U+02244
nsimeq; U+02244
nsmid; U+02224
nspar; U+02226
nsqsube; U+022E2
nsqsupe; U+022E3
nsub; U+02284
nsubE; U+02AC5 U+00338 ⫅̸
nsube; U+02288
nsubset; U+02282 U+020D2 ⊂⃒
nsubseteq; U+02288
nsubseteqq; U+02AC5 U+00338 ⫅̸
nsucc; U+02281
nsucceq; U+02AB0 U+00338 ⪰̸
nsup; U+02285
nsupE; U+02AC6 U+00338 ⫆̸
nsupe; U+02289
nsupset; U+02283 U+020D2 ⊃⃒
nsupseteq; U+02289
nsupseteqq; U+02AC6 U+00338 ⫆̸
ntgl; U+02279
Ntilde; U+000D1 Ñ
Ntilde U+000D1 Ñ
ntilde; U+000F1 ñ
ntilde U+000F1 ñ
ntlg; U+02278
ntriangleleft; U+022EA
ntrianglelefteq; U+022EC
ntriangleright; U+022EB
ntrianglerighteq; U+022ED
Nu; U+0039D Ν
nu; U+003BD ν
num; U+00023 #
numero; U+02116
numsp; U+02007
nvap; U+0224D U+020D2 ≍⃒
nVDash; U+022AF
nVdash; U+022AE
nvDash; U+022AD
nvdash; U+022AC
nvge; U+02265 U+020D2 ≥⃒
nvgt; U+0003E U+020D2 >⃒
nvHarr; U+02904
nvinfin; U+029DE
nvlArr; U+02902
nvle; U+02264 U+020D2 ≤⃒
nvlt; U+0003C U+020D2 <⃒
nvltrie; U+022B4 U+020D2 ⊴⃒
nvrArr; U+02903
nvrtrie; U+022B5 U+020D2 ⊵⃒
nvsim; U+0223C U+020D2 ∼⃒
nwarhk; U+02923
nwArr; U+021D6
nwarr; U+02196
nwarrow; U+02196
nwnear; U+02927
Oacute; U+000D3 Ó
Oacute U+000D3 Ó
oacute; U+000F3 ó
oacute U+000F3 ó
oast; U+0229B
ocir; U+0229A
Ocirc; U+000D4 Ô
Ocirc U+000D4 Ô
ocirc; U+000F4 ô
ocirc U+000F4 ô
Ocy; U+0041E О
ocy; U+0043E о
odash; U+0229D
Odblac; U+00150 Ő
odblac; U+00151 ő
odiv; U+02A38
odot; U+02299
odsold; U+029BC
OElig; U+00152 Œ
oelig; U+00153 œ
ofcir; U+029BF ⦿
Ofr; U+1D512 𝔒
ofr; U+1D52C 𝔬
ogon; U+002DB ˛
Ograve; U+000D2 Ò
Ograve U+000D2 Ò
ograve; U+000F2 ò
ograve U+000F2 ò
ogt; U+029C1
ohbar; U+029B5
ohm; U+003A9 Ω
oint; U+0222E
olarr; U+021BA
olcir; U+029BE
olcross; U+029BB
oline; U+0203E
olt; U+029C0
Omacr; U+0014C Ō
omacr; U+0014D ō
Omega; U+003A9 Ω
omega; U+003C9 ω
Omicron; U+0039F Ο
omicron; U+003BF ο
omid; U+029B6
ominus; U+02296
Oopf; U+1D546 𝕆
oopf; U+1D560 𝕠
opar; U+029B7
OpenCurlyDoubleQuote; U+0201C
OpenCurlyQuote; U+02018
operp; U+029B9
oplus; U+02295
Or; U+02A54
or; U+02228
orarr; U+021BB
ord; U+02A5D
order; U+02134
orderof; U+02134
ordf; U+000AA ª
ordf U+000AA ª
ordm; U+000BA º
ordm U+000BA º
origof; U+022B6
oror; U+02A56
orslope; U+02A57
orv; U+02A5B
oS; U+024C8
Oscr; U+1D4AA 𝒪
oscr; U+02134
Oslash; U+000D8 Ø
Oslash U+000D8 Ø
oslash; U+000F8 ø
oslash U+000F8 ø
osol; U+02298
Otilde; U+000D5 Õ
Otilde U+000D5 Õ
otilde; U+000F5 õ
otilde U+000F5 õ
Otimes; U+02A37
otimes; U+02297
otimesas; U+02A36
Ouml; U+000D6 Ö
Ouml U+000D6 Ö
ouml; U+000F6 ö
ouml U+000F6 ö
ovbar; U+0233D
OverBar; U+0203E
OverBrace; U+023DE
OverBracket; U+023B4
OverParenthesis; U+023DC
par; U+02225
para; U+000B6
para U+000B6
parallel; U+02225
parsim; U+02AF3
parsl; U+02AFD
part; U+02202
PartialD; U+02202
Pcy; U+0041F П
pcy; U+0043F п
percnt; U+00025 %
period; U+0002E .
permil; U+02030
perp; U+022A5
pertenk; U+02031
Pfr; U+1D513 𝔓
pfr; U+1D52D 𝔭
Phi; U+003A6 Φ
phi; U+003C6 φ
phiv; U+003D5 ϕ
phmmat; U+02133
phone; U+0260E
Pi; U+003A0 Π
pi; U+003C0 π
pitchfork; U+022D4
piv; U+003D6 ϖ
planck; U+0210F
planckh; U+0210E
plankv; U+0210F
plus; U+0002B +
plusacir; U+02A23
plusb; U+0229E
pluscir; U+02A22
plusdo; U+02214
plusdu; U+02A25
pluse; U+02A72
PlusMinus; U+000B1 ±
plusmn; U+000B1 ±
plusmn U+000B1 ±
plussim; U+02A26
plustwo; U+02A27
pm; U+000B1 ±
Poincareplane; U+0210C
pointint; U+02A15
Popf; U+02119
popf; U+1D561 𝕡
pound; U+000A3 £
pound U+000A3 £
Pr; U+02ABB
pr; U+0227A
prap; U+02AB7
prcue; U+0227C
prE; U+02AB3
pre; U+02AAF
prec; U+0227A
precapprox; U+02AB7
preccurlyeq; U+0227C
Precedes; U+0227A
PrecedesEqual; U+02AAF
PrecedesSlantEqual; U+0227C
PrecedesTilde; U+0227E
preceq; U+02AAF
precnapprox; U+02AB9
precneqq; U+02AB5
precnsim; U+022E8
precsim; U+0227E
Prime; U+02033
prime; U+02032
primes; U+02119
prnap; U+02AB9
prnE; U+02AB5
prnsim; U+022E8
prod; U+0220F
Product; U+0220F
profalar; U+0232E
profline; U+02312
profsurf; U+02313
prop; U+0221D
Proportion; U+02237
Proportional; U+0221D
propto; U+0221D
prsim; U+0227E
prurel; U+022B0
Pscr; U+1D4AB 𝒫
pscr; U+1D4C5 𝓅
Psi; U+003A8 Ψ
psi; U+003C8 ψ
puncsp; U+02008
Qfr; U+1D514 𝔔
qfr; U+1D52E 𝔮
qint; U+02A0C
Qopf; U+0211A
qopf; U+1D562 𝕢
qprime; U+02057
Qscr; U+1D4AC 𝒬
qscr; U+1D4C6 𝓆
quaternions; U+0210D
quatint; U+02A16
quest; U+0003F ?
questeq; U+0225F
QUOT; U+00022 "
QUOT U+00022 "
quot; U+00022 "
quot U+00022 "
rAarr; U+021DB
race; U+0223D U+00331 ∽̱
Racute; U+00154 Ŕ
racute; U+00155 ŕ
radic; U+0221A
raemptyv; U+029B3
Rang; U+027EB
rang; U+027E9
rangd; U+02992
range; U+029A5
rangle; U+027E9
raquo; U+000BB »
raquo U+000BB »
Rarr; U+021A0
rArr; U+021D2
rarr; U+02192
rarrap; U+02975
rarrb; U+021E5
rarrbfs; U+02920
rarrc; U+02933
rarrfs; U+0291E
rarrhk; U+021AA
rarrlp; U+021AC
rarrpl; U+02945
rarrsim; U+02974
Rarrtl; U+02916
rarrtl; U+021A3
rarrw; U+0219D
rAtail; U+0291C
ratail; U+0291A
ratio; U+02236
rationals; U+0211A
RBarr; U+02910
rBarr; U+0290F
rbarr; U+0290D
rbbrk; U+02773
rbrace; U+0007D }
rbrack; U+0005D ]
rbrke; U+0298C
rbrksld; U+0298E
rbrkslu; U+02990
Rcaron; U+00158 Ř
rcaron; U+00159 ř
Rcedil; U+00156 Ŗ
rcedil; U+00157 ŗ
rceil; U+02309
rcub; U+0007D }
Rcy; U+00420 Р
rcy; U+00440 р
rdca; U+02937
rdldhar; U+02969
rdquo; U+0201D
rdquor; U+0201D
rdsh; U+021B3
Re; U+0211C
real; U+0211C
realine; U+0211B
realpart; U+0211C
reals; U+0211D
rect; U+025AD
REG; U+000AE ®
REG U+000AE ®
reg; U+000AE ®
reg U+000AE ®
ReverseElement; U+0220B
ReverseEquilibrium; U+021CB
ReverseUpEquilibrium; U+0296F
rfisht; U+0297D
rfloor; U+0230B
Rfr; U+0211C
rfr; U+1D52F 𝔯
rHar; U+02964
rhard; U+021C1
rharu; U+021C0
rharul; U+0296C
Rho; U+003A1 Ρ
rho; U+003C1 ρ
rhov; U+003F1 ϱ
RightAngleBracket; U+027E9
RightArrow; U+02192
Rightarrow; U+021D2
rightarrow; U+02192
RightArrowBar; U+021E5
RightArrowLeftArrow; U+021C4
rightarrowtail; U+021A3
RightCeiling; U+02309
RightDoubleBracket; U+027E7
RightDownTeeVector; U+0295D
RightDownVector; U+021C2
RightDownVectorBar; U+02955
RightFloor; U+0230B
rightharpoondown; U+021C1
rightharpoonup; U+021C0
rightleftarrows; U+021C4
rightleftharpoons; U+021CC
rightrightarrows; U+021C9
rightsquigarrow; U+0219D
RightTee; U+022A2
RightTeeArrow; U+021A6
RightTeeVector; U+0295B
rightthreetimes; U+022CC
RightTriangle; U+022B3
RightTriangleBar; U+029D0
RightTriangleEqual; U+022B5
RightUpDownVector; U+0294F
RightUpTeeVector; U+0295C
RightUpVector; U+021BE
RightUpVectorBar; U+02954
RightVector; U+021C0
RightVectorBar; U+02953
ring; U+002DA ˚
risingdotseq; U+02253
rlarr; U+021C4
rlhar; U+021CC
rlm; U+0200F
rmoust; U+023B1
rmoustache; U+023B1
rnmid; U+02AEE
roang; U+027ED
roarr; U+021FE
robrk; U+027E7
ropar; U+02986
Ropf; U+0211D
ropf; U+1D563 𝕣
roplus; U+02A2E
rotimes; U+02A35
RoundImplies; U+02970
rpar; U+00029 )
rpargt; U+02994
rppolint; U+02A12
rrarr; U+021C9
Rrightarrow; U+021DB
rsaquo; U+0203A
Rscr; U+0211B
rscr; U+1D4C7 𝓇
Rsh; U+021B1
rsh; U+021B1
rsqb; U+0005D ]
rsquo; U+02019
rsquor; U+02019
rthree; U+022CC
rtimes; U+022CA
rtri; U+025B9
rtrie; U+022B5
rtrif; U+025B8
rtriltri; U+029CE
RuleDelayed; U+029F4
ruluhar; U+02968
rx; U+0211E
Sacute; U+0015A Ś
sacute; U+0015B ś
sbquo; U+0201A
Sc; U+02ABC
sc; U+0227B
scap; U+02AB8
Scaron; U+00160 Š
scaron; U+00161 š
sccue; U+0227D
scE; U+02AB4
sce; U+02AB0
Scedil; U+0015E Ş
scedil; U+0015F ş
Scirc; U+0015C Ŝ
scirc; U+0015D ŝ
scnap; U+02ABA
scnE; U+02AB6
scnsim; U+022E9
scpolint; U+02A13
scsim; U+0227F
Scy; U+00421 С
scy; U+00441 с
sdot; U+022C5
sdotb; U+022A1
sdote; U+02A66
searhk; U+02925
seArr; U+021D8
searr; U+02198
searrow; U+02198
sect; U+000A7 §
sect U+000A7 §
semi; U+0003B ;
seswar; U+02929
setminus; U+02216
setmn; U+02216
sext; U+02736
Sfr; U+1D516 𝔖
sfr; U+1D530 𝔰
sfrown; U+02322
sharp; U+0266F
SHCHcy; U+00429 Щ
shchcy; U+00449 щ
SHcy; U+00428 Ш
shcy; U+00448 ш
ShortDownArrow; U+02193
ShortLeftArrow; U+02190
shortmid; U+02223
shortparallel; U+02225
ShortRightArrow; U+02192
ShortUpArrow; U+02191
shy; U+000AD ­
shy U+000AD ­
Sigma; U+003A3 Σ
sigma; U+003C3 σ
sigmaf; U+003C2 ς
sigmav; U+003C2 ς
sim; U+0223C
simdot; U+02A6A
sime; U+02243
simeq; U+02243
simg; U+02A9E
simgE; U+02AA0
siml; U+02A9D
simlE; U+02A9F
simne; U+02246
simplus; U+02A24
simrarr; U+02972
slarr; U+02190
SmallCircle; U+02218
smallsetminus; U+02216
smashp; U+02A33
smeparsl; U+029E4
smid; U+02223
smile; U+02323
smt; U+02AAA
smte; U+02AAC
smtes; U+02AAC U+0FE00 ⪬︀
SOFTcy; U+0042C Ь
softcy; U+0044C ь
sol; U+0002F /
solb; U+029C4
solbar; U+0233F
Sopf; U+1D54A 𝕊
sopf; U+1D564 𝕤
spades; U+02660
spadesuit; U+02660
spar; U+02225
sqcap; U+02293
sqcaps; U+02293 U+0FE00 ⊓︀
sqcup; U+02294
sqcups; U+02294 U+0FE00 ⊔︀
Sqrt; U+0221A
sqsub; U+0228F
sqsube; U+02291
sqsubset; U+0228F
sqsubseteq; U+02291
sqsup; U+02290
sqsupe; U+02292
sqsupset; U+02290
sqsupseteq; U+02292
squ; U+025A1
Square; U+025A1
square; U+025A1
SquareIntersection; U+02293
SquareSubset; U+0228F
SquareSubsetEqual; U+02291
SquareSuperset; U+02290
SquareSupersetEqual; U+02292
SquareUnion; U+02294
squarf; U+025AA
squf; U+025AA
srarr; U+02192
Sscr; U+1D4AE 𝒮
sscr; U+1D4C8 𝓈
ssetmn; U+02216
ssmile; U+02323
sstarf; U+022C6
Star; U+022C6
star; U+02606
starf; U+02605
straightepsilon; U+003F5 ϵ
straightphi; U+003D5 ϕ
strns; U+000AF ¯
Sub; U+022D0
sub; U+02282
subdot; U+02ABD
subE; U+02AC5
sube; U+02286
subedot; U+02AC3
submult; U+02AC1
subnE; U+02ACB
subne; U+0228A
subplus; U+02ABF ⪿
subrarr; U+02979
Subset; U+022D0
subset; U+02282
subseteq; U+02286
subseteqq; U+02AC5
SubsetEqual; U+02286
subsetneq; U+0228A
subsetneqq; U+02ACB
subsim; U+02AC7
subsub; U+02AD5
subsup; U+02AD3
succ; U+0227B
succapprox; U+02AB8
succcurlyeq; U+0227D
Succeeds; U+0227B
SucceedsEqual; U+02AB0
SucceedsSlantEqual; U+0227D
SucceedsTilde; U+0227F
succeq; U+02AB0
succnapprox; U+02ABA
succneqq; U+02AB6
succnsim; U+022E9
succsim; U+0227F
SuchThat; U+0220B
Sum; U+02211
sum; U+02211
sung; U+0266A
Sup; U+022D1
sup; U+02283
sup1; U+000B9 ¹
sup1 U+000B9 ¹
sup2; U+000B2 ²
sup2 U+000B2 ²
sup3; U+000B3 ³
sup3 U+000B3 ³
supdot; U+02ABE
supdsub; U+02AD8
supE; U+02AC6
supe; U+02287
supedot; U+02AC4
Superset; U+02283
SupersetEqual; U+02287
suphsol; U+027C9
suphsub; U+02AD7
suplarr; U+0297B
supmult; U+02AC2
supnE; U+02ACC
supne; U+0228B
supplus; U+02AC0
Supset; U+022D1
supset; U+02283
supseteq; U+02287
supseteqq; U+02AC6
supsetneq; U+0228B
supsetneqq; U+02ACC
supsim; U+02AC8
supsub; U+02AD4
supsup; U+02AD6
swarhk; U+02926
swArr; U+021D9
swarr; U+02199
swarrow; U+02199
swnwar; U+0292A
szlig; U+000DF ß
szlig U+000DF ß
Tab; U+00009
target; U+02316
Tau; U+003A4 Τ
tau; U+003C4 τ
tbrk; U+023B4
Tcaron; U+00164 Ť
tcaron; U+00165 ť
Tcedil; U+00162 Ţ
tcedil; U+00163 ţ
Tcy; U+00422 Т
tcy; U+00442 т
tdot; U+020DB ◌⃛
telrec; U+02315
Tfr; U+1D517 𝔗
tfr; U+1D531 𝔱
there4; U+02234
Therefore; U+02234
therefore; U+02234
Theta; U+00398 Θ
theta; U+003B8 θ
thetasym; U+003D1 ϑ
thetav; U+003D1 ϑ
thickapprox; U+02248
thicksim; U+0223C
ThickSpace; U+0205F U+0200A   
thinsp; U+02009
ThinSpace; U+02009
thkap; U+02248
thksim; U+0223C
THORN; U+000DE Þ
THORN U+000DE Þ
thorn; U+000FE þ
thorn U+000FE þ
Tilde; U+0223C
tilde; U+002DC ˜
TildeEqual; U+02243
TildeFullEqual; U+02245
TildeTilde; U+02248
times; U+000D7 ×
times U+000D7 ×
timesb; U+022A0
timesbar; U+02A31
timesd; U+02A30
tint; U+0222D
toea; U+02928
top; U+022A4
topbot; U+02336
topcir; U+02AF1
Topf; U+1D54B 𝕋
topf; U+1D565 𝕥
topfork; U+02ADA
tosa; U+02929
tprime; U+02034
TRADE; U+02122
trade; U+02122
triangle; U+025B5
triangledown; U+025BF
triangleleft; U+025C3
trianglelefteq; U+022B4
triangleq; U+0225C
triangleright; U+025B9
trianglerighteq; U+022B5
tridot; U+025EC
trie; U+0225C
triminus; U+02A3A
TripleDot; U+020DB ◌⃛
triplus; U+02A39
trisb; U+029CD
tritime; U+02A3B
trpezium; U+023E2
Tscr; U+1D4AF 𝒯
tscr; U+1D4C9 𝓉
TScy; U+00426 Ц
tscy; U+00446 ц
TSHcy; U+0040B Ћ
tshcy; U+0045B ћ
Tstrok; U+00166 Ŧ
tstrok; U+00167 ŧ
twixt; U+0226C
twoheadleftarrow; U+0219E
twoheadrightarrow; U+021A0
Uacute; U+000DA Ú
Uacute U+000DA Ú
uacute; U+000FA ú
uacute U+000FA ú
Uarr; U+0219F
uArr; U+021D1
uarr; U+02191
Uarrocir; U+02949
Ubrcy; U+0040E Ў
ubrcy; U+0045E ў
Ubreve; U+0016C Ŭ
ubreve; U+0016D ŭ
Ucirc; U+000DB Û
Ucirc U+000DB Û
ucirc; U+000FB û
ucirc U+000FB û
Ucy; U+00423 У
ucy; U+00443 у
udarr; U+021C5
Udblac; U+00170 Ű
udblac; U+00171 ű
udhar; U+0296E
ufisht; U+0297E
Ufr; U+1D518 𝔘
ufr; U+1D532 𝔲
Ugrave; U+000D9 Ù
Ugrave U+000D9 Ù
ugrave; U+000F9 ù
ugrave U+000F9 ù
uHar; U+02963
uharl; U+021BF
uharr; U+021BE
uhblk; U+02580
ulcorn; U+0231C
ulcorner; U+0231C
ulcrop; U+0230F
ultri; U+025F8
Umacr; U+0016A Ū
umacr; U+0016B ū
uml; U+000A8 ¨
uml U+000A8 ¨
UnderBar; U+0005F _
UnderBrace; U+023DF
UnderBracket; U+023B5
UnderParenthesis; U+023DD
Union; U+022C3
UnionPlus; U+0228E
Uogon; U+00172 Ų
uogon; U+00173 ų
Uopf; U+1D54C 𝕌
uopf; U+1D566 𝕦
UpArrow; U+02191
Uparrow; U+021D1
uparrow; U+02191
UpArrowBar; U+02912
UpArrowDownArrow; U+021C5
UpDownArrow; U+02195
Updownarrow; U+021D5
updownarrow; U+02195
UpEquilibrium; U+0296E
upharpoonleft; U+021BF
upharpoonright; U+021BE
uplus; U+0228E
UpperLeftArrow; U+02196
UpperRightArrow; U+02197
Upsi; U+003D2 ϒ
upsi; U+003C5 υ
upsih; U+003D2 ϒ
Upsilon; U+003A5 Υ
upsilon; U+003C5 υ
UpTee; U+022A5
UpTeeArrow; U+021A5
upuparrows; U+021C8
urcorn; U+0231D
urcorner; U+0231D
urcrop; U+0230E
Uring; U+0016E Ů
uring; U+0016F ů
urtri; U+025F9
Uscr; U+1D4B0 𝒰
uscr; U+1D4CA 𝓊
utdot; U+022F0
Utilde; U+00168 Ũ
utilde; U+00169 ũ
utri; U+025B5
utrif; U+025B4
uuarr; U+021C8
Uuml; U+000DC Ü
Uuml U+000DC Ü
uuml; U+000FC ü
uuml U+000FC ü
uwangle; U+029A7
vangrt; U+0299C
varepsilon; U+003F5 ϵ
varkappa; U+003F0 ϰ
varnothing; U+02205
varphi; U+003D5 ϕ
varpi; U+003D6 ϖ
varpropto; U+0221D
vArr; U+021D5
varr; U+02195
varrho; U+003F1 ϱ
varsigma; U+003C2 ς
varsubsetneq; U+0228A U+0FE00 ⊊︀
varsubsetneqq; U+02ACB U+0FE00 ⫋︀
varsupsetneq; U+0228B U+0FE00 ⊋︀
varsupsetneqq; U+02ACC U+0FE00 ⫌︀
vartheta; U+003D1 ϑ
vartriangleleft; U+022B2
vartriangleright; U+022B3
Vbar; U+02AEB
vBar; U+02AE8
vBarv; U+02AE9
Vcy; U+00412 В
vcy; U+00432 в
VDash; U+022AB
Vdash; U+022A9
vDash; U+022A8
vdash; U+022A2
Vdashl; U+02AE6
Vee; U+022C1
vee; U+02228
veebar; U+022BB
veeeq; U+0225A
vellip; U+022EE
Verbar; U+02016
verbar; U+0007C |
Vert; U+02016
vert; U+0007C |
VerticalBar; U+02223
VerticalLine; U+0007C |
VerticalSeparator; U+02758
VerticalTilde; U+02240
VeryThinSpace; U+0200A
Vfr; U+1D519 𝔙
vfr; U+1D533 𝔳
vltri; U+022B2
vnsub; U+02282 U+020D2 ⊂⃒
vnsup; U+02283 U+020D2 ⊃⃒
Vopf; U+1D54D 𝕍
vopf; U+1D567 𝕧
vprop; U+0221D
vrtri; U+022B3
Vscr; U+1D4B1 𝒱
vscr; U+1D4CB 𝓋
vsubnE; U+02ACB U+0FE00 ⫋︀
vsubne; U+0228A U+0FE00 ⊊︀
vsupnE; U+02ACC U+0FE00 ⫌︀
vsupne; U+0228B U+0FE00 ⊋︀
Vvdash; U+022AA
vzigzag; U+0299A
Wcirc; U+00174 Ŵ
wcirc; U+00175 ŵ
wedbar; U+02A5F
Wedge; U+022C0
wedge; U+02227
wedgeq; U+02259
weierp; U+02118
Wfr; U+1D51A 𝔚
wfr; U+1D534 𝔴
Wopf; U+1D54E 𝕎
wopf; U+1D568 𝕨
wp; U+02118
wr; U+02240
wreath; U+02240
Wscr; U+1D4B2 𝒲
wscr; U+1D4CC 𝓌
xcap; U+022C2
xcirc; U+025EF
xcup; U+022C3
xdtri; U+025BD
Xfr; U+1D51B 𝔛
xfr; U+1D535 𝔵
xhArr; U+027FA
xharr; U+027F7
Xi; U+0039E Ξ
xi; U+003BE ξ
xlArr; U+027F8
xlarr; U+027F5
xmap; U+027FC
xnis; U+022FB
xodot; U+02A00
Xopf; U+1D54F 𝕏
xopf; U+1D569 𝕩
xoplus; U+02A01
xotime; U+02A02
xrArr; U+027F9
xrarr; U+027F6
Xscr; U+1D4B3 𝒳
xscr; U+1D4CD 𝓍
xsqcup; U+02A06
xuplus; U+02A04
xutri; U+025B3
xvee; U+022C1
xwedge; U+022C0
Yacute; U+000DD Ý
Yacute U+000DD Ý
yacute; U+000FD ý
yacute U+000FD ý
YAcy; U+0042F Я
yacy; U+0044F я
Ycirc; U+00176 Ŷ
ycirc; U+00177 ŷ
Ycy; U+0042B Ы
ycy; U+0044B ы
yen; U+000A5 ¥
yen U+000A5 ¥
Yfr; U+1D51C 𝔜
yfr; U+1D536 𝔶
YIcy; U+00407 Ї
yicy; U+00457 ї
Yopf; U+1D550 𝕐
yopf; U+1D56A 𝕪
Yscr; U+1D4B4 𝒴
yscr; U+1D4CE 𝓎
YUcy; U+0042E Ю
yucy; U+0044E ю
Yuml; U+00178 Ÿ
yuml; U+000FF ÿ
yuml U+000FF ÿ
Zacute; U+00179 Ź
zacute; U+0017A ź
Zcaron; U+0017D Ž
zcaron; U+0017E ž
Zcy; U+00417 З
zcy; U+00437 з
Zdot; U+0017B Ż
zdot; U+0017C ż
zeetrf; U+02128
ZeroWidthSpace; U+0200B
Zeta; U+00396 Ζ
zeta; U+003B6 ζ
Zfr; U+02128
zfr; U+1D537 𝔷
ZHcy; U+00416 Ж
zhcy; U+00436 ж
zigrarr; U+021DD
Zopf; U+02124
zopf; U+1D56B 𝕫
Zscr; U+1D4B5 𝒵
zscr; U+1D4CF 𝓏
zwj; U+0200D
zwnj; U+0200C

This data is also available as a JSON file.

The glyphs displayed above are non-normative. Refer to Unicode for formal definitions of the characters listed above.

The character reference names originate from XML Entity Definitions for Characters, though only the above is considered normative. [XMLENTITY]

14 XML 语法

HTML/XHTML

Support in all current engines.

Firefox2+Safari3.1+Chrome4+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android2+Samsung Internet1.0+Opera Android10.1+

本章只描述 XML 资源的语法规则。 text/html 资源的规则在上一章 "HTML 语法" 中讨论。

14.1 以 XML 语法编写文档

HTML 的 XML 语法以前称为 "XHTML",但本规范不适用这一术语 (一个原因是这样的术语不能用于 MathML 和 SVG 的 HTML 语法)。

XML 的语法定义在 XML 和 Namespaces in XML 规范中。[XML] [XMLNS]

本规范没有在 XML 规范的基础上定义任何语法级别的要求。

XML 文档可能会包含一个 DOCTYPE,但符合本规范不要求包含。 本规范没有定义共有或系统标识符,也没有提供正式的 DTD。

根据 XML 规范,XML 处理器不保证处理 DOCTYPE 中引用的外部 DTD 子集。 这意味着,例如为 XML 文档中的字符使用 实体引用 时,如果它们定义在外部文件中( 除了 &lt;&gt;&amp;&quot; 以及 &apos; 之外 )就是不安全的。

14.2 Parsing XML documents

This section describes the relationship between XML and the DOM, with a particular emphasis on how this interacts with HTML.

An XML parser, for the purposes of this specification, is a construct that follows the rules given in the XML specification to map a string of bytes or characters into a Document object.

At the time of writing, no such rules actually exist.

An XML parser is either associated with a Document object when it is created, or creates one implicitly.

This Document must then be populated with DOM nodes that represent the tree structure of the input passed to the parser, as defined by the XML specification, the Namespaces in XML specification, and the WHATWG DOM standard. When creating DOM nodes representing elements, the create an element for a token algorithm or some equivalent that operates on appropriate XML datastructures must be used, to ensure the proper element interfaces are created and that custom elements are set up correctly.

DOM mutation events must not fire for the operations that the XML parser performs on the Document's tree, but the user agent must act as if elements and attributes were individually appended and set respectively so as to trigger rules in this specification regarding what happens when an element is inserted into a document or has its attributes set, and the WHATWG DOM standard's requirements regarding mutation observers mean that mutation observers are fired (unlike mutation events). [XML] [XMLNS] [DOM] [UIEVENTS]

Between the time an element's start tag is parsed and the time either the element's end tag is parsed or the parser detects a well-formedness error, the user agent must act as if the element was in a stack of open elements.

This is used, e.g. by the object element to avoid instantiating plugins before the param element children have been parsed.

This specification provides the following additional information that user agents should use when retrieving an external entity: the public identifiers given in the following list all correspond to the URL given by this link. (This URL is a DTD containing the entity declarations for the names listed in the named character references section.) [XML]

Furthermore, user agents should attempt to retrieve the above external entity's content when one of the above public identifiers is used, and should not attempt to retrieve any other external entity's content.

This is not strictly a violation of the XML specification, but it does contradict the spirit of the XML specification's requirements. This is motivated by a desire for user agents to all handle entities in an interoperable fashion without requiring any network access for handling external subsets. [XML]

XML parsers can be invoked with XML scripting support enabled or XML scripting support disabled. Except where otherwise specified, XML parsers are invoked with XML scripting support enabled.

When an XML parser with XML scripting support enabled creates a script element, it must be marked as being "parser-inserted" and its "non-blocking" flag must be unset. If the parser was originally created for the XML fragment parsing algorithm, then the element must be marked as "already started" also. When the element's end tag is subsequently parsed, the user agent must perform a microtask checkpoint, and then prepare the script element. If this causes there to be a pending parsing-blocking script, then the user agent must run the following steps:

  1. Block this instance of the XML parser, such that the event loop will not run tasks that invoke it.

  2. Spin the event loop until the parser's Document has no style sheet that is blocking scripts and the pending parsing-blocking script's "ready to be parser-executed" flag is set.

  3. Unblock this instance of the XML parser, such that tasks that invoke it can again be run.

  4. Execute the pending parsing-blocking script.

  5. There is no longer a pending parsing-blocking script.

Since the document.write() API is not available for XML documents, much of the complexity in the HTML parser is not needed in the XML parser.

When the XML parser has XML scripting support disabled, none of this happens.

When an XML parser would append a node to a template element, it must instead append it to the template element's template contents (a DocumentFragment node).

This is a willful violation of the XML specification; unfortunately, XML is not formally extensible in the manner that is needed for template processing. [XML]

When an XML parser creates a Node object, its node document must be set to the node document of the node into which the newly created node is to be inserted.

Certain algorithms in this specification spoon-feed the parser characters one string at a time. In such cases, the XML parser must act as it would have if faced with a single string consisting of the concatenation of all those characters.

When an XML parser reaches the end of its input, it must stop parsing, following the same rules as the HTML parser. An XML parser can also be aborted, which must again be done in the same way as for an HTML parser.

For the purposes of conformance checkers, if a resource is determined to be in XML 语法, then it is an XML document.

14.3 Serializing XML fragments

The XML fragment serialization algorithm for a Document or Element node either returns a fragment of XML that represents that node or throws an exception.

For Documents, the algorithm must return a string in the form of a document entity, if none of the error cases below apply.

For Elements, the algorithm must return a string in the form of an internal general parsed entity, if none of the error cases below apply.

In both cases, the string returned must be XML namespace-well-formed and must be an isomorphic serialization of all of that node's relevant child nodes, in tree order. User agents may adjust prefixes and namespace declarations in the serialization (and indeed might be forced to do so in some cases to obtain namespace-well-formed XML). User agents may use a combination of regular text and character references to represent Text nodes in the DOM.

A node's relevant child nodes are those that apply given the following rules:

For template elements
The relevant child nodes are the child nodes of the template element's template contents, if any.
For all other nodes
The relevant child nodes are the child nodes of node itself, if any.

For Elements, if any of the elements in the serialization are in no namespace, the default namespace in scope for those elements must be explicitly declared as the empty string. (This doesn't apply in the Document case.) [XML] [XMLNS]

For the purposes of this section, an internal general parsed entity is considered XML namespace-well-formed if a document consisting of an element with no namespace declarations whose contents are the internal general parsed entity would itself be XML namespace-well-formed.

If any of the following error cases are found in the DOM subtree being serialized, then the algorithm must throw an "InvalidStateError" DOMException instead of returning a string:

These are the only ways to make a DOM unserialisable. The DOM enforces all the other XML constraints; for example, trying to append two elements to a Document node will throw a "HierarchyRequestError" DOMException.

14.4 Parsing XML fragments

The XML fragment parsing algorithm either returns a Document or throws a "SyntaxError" DOMException. Given a string input and a context element context, the algorithm is as follows:

  1. Create a new XML parser.

  2. Feed the parser just created the string corresponding to the start tag of the context element, declaring all the namespace prefixes that are in scope on that element in the DOM, as well as declaring the default namespace (if any) that is in scope on that element in the DOM.

    A namespace prefix is in scope if the DOM lookupNamespaceURI() method on the element would return a non-null value for that prefix.

    The default namespace is the namespace for which the DOM isDefaultNamespace() method on the element would return true.

    No DOCTYPE is passed to the parser, and therefore no external subset is referenced, and therefore no entities will be recognized.

  3. Feed the parser just created the string input.

  4. Feed the parser just created the string corresponding to the end tag of the context element.

  5. If there is an XML well-formedness or XML namespace well-formedness error, then throw a "SyntaxError" DOMException.

  6. If the document element of the resulting Document has any sibling nodes, then throw a "SyntaxError" DOMException.

  7. Return the child nodes of the document element of the resulting Document, in tree order.

15 渲染

User agents are not required to present HTML documents in any particular way. However, this section provides a set of suggestions for rendering HTML documents that, if followed, are likely to lead to a user experience that closely resembles the experience intended by the documents' authors. So as to avoid confusion regarding the normativity of this section, "must" has not been used. Instead, the term "expected" is used to indicate behavior that will lead to this experience. For the purposes of conformance for user agents designated as supporting the suggested default rendering, the term "expected" in this section has the same conformance implications as "must".

15.1 Introduction

In general, user agents are expected to support CSS, and many of the suggestions in this section are expressed in CSS terms. User agents that use other presentation mechanisms can derive their expected behavior by translating from the CSS rules given in this section.

In the absence of style-layer rules to the contrary (e.g. author style sheets), user agents are expected to render an element so that it conveys to the user the meaning that the element represents, as described by this specification.

The suggestions in this section generally assume a visual output medium with a resolution of 96dpi or greater, but HTML is intended to apply to multiple media (it is a media-independent language). User agent implementers are encouraged to adapt the suggestions in this section to their target media.


An element is being rendered if it has any associated CSS layout boxes, SVG layout boxes, or some equivalent in other styling languages.

Just being off-screen does not mean the element is not being rendered. The presence of the hidden attribute normally means the element is not being rendered, though this might be overridden by the style sheets.

An element is said to intersect the viewport when it is being rendered and its associated CSS layout box intersects the viewport.

This specification does not define the precise timing for when the intersection is tested, but it is suggested that the timing match that of the Intersection Observer API. [INTERSECTIONOBSERVER]


User agents that do not honor author-level CSS style sheets are nonetheless expected to act as if they applied the CSS rules given in these sections in a manner consistent with this specification and the relevant CSS and Unicode specifications. [CSS] [UNICODE] [BIDI]

This is especially important for issues relating to the 'display', 'unicode-bidi', and 'direction' properties.

15.2 The CSS user agent style sheet and presentational hints

The CSS rules given in these subsections are, except where otherwise specified, expected to be used as part of the user-agent level style sheet defaults for all documents that contain HTML elements.

Some rules are intended for the author-level zero-specificity presentational hints part of the CSS cascade; these are explicitly called out as presentational hints.


When the text below says that an attribute attribute on an element element maps to the pixel length property (or properties) properties, it means that if element has an attribute attribute set, and parsing that attribute's value using the rules for parsing non-negative integers doesn't generate an error, then the user agent is expected to use the parsed value as a pixel length for a presentational hint for properties.

When the text below says that an attribute attribute on an element element maps to the dimension property (or properties) properties, it means that if element has an attribute attribute set, and parsing that attribute's value using the rules for parsing dimension values doesn't generate an error, then the user agent is expected to use the parsed dimension as the value for a presentational hint for properties, with the value given as a pixel length if the dimension was a length, and with the value given as a percentage if the dimension was a percentage.

When the text below says that an attribute attribute on an element element maps to the dimension property (ignoring zero) (or properties) properties, it means that if element has an attribute attribute set, and parsing that attribute's value using the rules for parsing nonzero dimension values doesn't generate an error, then the user agent is expected to use the parsed dimension as the value for a presentational hint for properties, with the value given as a pixel length if the dimension was a length, and with the value given as a percentage if the dimension was a percentage.

When a user agent is to align descendants of a node, the user agent is expected to align only those descendants that have both their 'margin-inline-start' and 'margin-inline-end' properties computing to a value other than 'auto', that are over-constrained and that have one of those two margins with a used value forced to a greater value, and that do not themselves have an applicable align attribute. When multiple elements are to align a particular descendant, the most deeply nested such element is expected to override the others. Aligned elements are expected to be aligned by having the used values of their margins on the line-left and line-right sides be set accordingly. [CSSLOGICAL] [CSSWM]

15.3 Non-replaced elements

15.3.1 Hidden elements

@namespace url(http://www.w3.org/1999/xhtml);

[hidden], area, base, basefont, datalist, head, link, meta, noembed,
noframes, param, rp, script, source, style, template, track, title {
  display: none;
}

embed[hidden] { display: inline; height: 0; width: 0; } 

input[type=hidden i] { display: none !important; }

@media (scripting) {
  noscript { display: none !important; }
}

15.3.2 The page

@namespace url(http://www.w3.org/1999/xhtml);

html, body { display: block; }

For each property in the table below, given a body element, the first attribute that exists maps to the pixel length property on the body element. If none of the attributes for a property are found, or if the value of the attribute that was found cannot be parsed successfully, then a default value of 8px is expected to be used for that property instead.

Property Source
'margin-top' The body element's marginheight attribute
The body element's topmargin attribute
The body element's container frame element's marginheight attribute
'margin-right' The body element's marginwidth attribute
The body element's rightmargin attribute
The body element's container frame element's marginwidth attribute
'margin-bottom' The body element's marginheight attribute
The body element's bottommargin attribute
The body element's container frame element's marginheight attribute
'margin-left' The body element's marginwidth attribute
The body element's leftmargin attribute
The body element's container frame element's marginwidth attribute

If the body element's node document's browsing context is a child browsing context, and the container of that browsing context is a frame or iframe element, then the container frame element of the body element is that frame or iframe element. Otherwise, there is no container frame element.

The above requirements imply that a page can change the margins of another page (including one from another origin) using, for example, an iframe. This is potentially a security risk, as it might in some cases allow an attack to contrive a situation in which a page is rendered not as the author intended, possibly for the purposes of phishing or otherwise misleading the user.


If a Document's browsing context is a child browsing context, then it is expected to be positioned and sized to fit inside the content box of the container of that browsing context. If the container is not being rendered, the browsing context is expected to have a viewport with zero width and zero height.

If a Document's browsing context is a child browsing context, the container of that browsing context is a frame or iframe element, that element has a scrolling attribute, and that attribute's value is an ASCII case-insensitive match for the string "off", "noscroll", or "no", then the user agent is expected to prevent any scrollbars from being shown for the viewport of the Document's browsing context, regardless of the 'overflow' property that applies to that viewport.


When a body element has a background attribute set to a non-empty value, the new value is expected to be parsed relative to the element's node document, and if this is successful, the user agent is expected to treat the attribute as a presentational hint setting the element's 'background-image' property to the resulting URL string.

When a body element has a bgcolor attribute set, the new value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'background-color' property to the resulting color.

When a body element has a text attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'color' property to the resulting color.

When a body element has a link attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the 'color' property of any element in the Document matching the :link pseudo-class to the resulting color.

When a body element has a vlink attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the 'color' property of any element in the Document matching the :visited pseudo-class to the resulting color.

When a body element has an alink attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the 'color' property of any element in the Document matching the :active pseudo-class and either the :link pseudo-class or the :visited pseudo-class to the resulting color.

15.3.3 Flow content

@namespace url(http://www.w3.org/1999/xhtml);

address, blockquote, center, dialog, div, figure, figcaption, footer, form,
header, hr, legend, listing, main, p, plaintext, pre, xmp {
  display: block;
}

blockquote, figure, listing, p, plaintext, pre, xmp {
  margin-block-start: 1em; margin-block-end: 1em;
}

blockquote, figure { margin-inline-start: 40px; margin-inline-end: 40px; }

address { font-style: italic; }
listing, plaintext, pre, xmp {
  font-family: monospace; white-space: pre;
}

dialog:not([open]) { display: none; }
dialog {
  position: absolute;
  inset-inline-start: 0; inset-inline-end: 0;
  width: fit-content;
  height: fit-content;
  margin: auto;
  border: solid;
  padding: 1em;
  background: white;
  color: black;
}
dialog::backdrop {
  background: rgba(0,0,0,0.1);
}

slot {
  display: contents;
}

The following rules are also expected to apply, as presentational hints:

@namespace url(http://www.w3.org/1999/xhtml);

pre[wrap] { white-space: pre-wrap; }

In quirks mode, the following rules are also expected to apply:

@namespace url(http://www.w3.org/1999/xhtml);

form { margin-block-end: 1em; }

The center element, and the div element when it has an align attribute whose value is an ASCII case-insensitive match for either the string "center" or the string "middle", are expected to center text within themselves, as if they had their 'text-align' property set to 'center' in a presentational hint, and to align descendants to the center.

The div element, when it has an align attribute whose value is an ASCII case-insensitive match for the string "left", is expected to left-align text within itself, as if it had its 'text-align' property set to 'left' in a presentational hint, and to align descendants to the left.

The div element, when it has an align attribute whose value is an ASCII case-insensitive match for the string "right", is expected to right-align text within itself, as if it had its 'text-align' property set to 'right' in a presentational hint, and to align descendants to the right.

The div element, when it has an align attribute whose value is an ASCII case-insensitive match for the string "justify", is expected to full-justify text within itself, as if it had its 'text-align' property set to 'justify' in a presentational hint, and to align descendants to the left.

The dialog element, when its is modal flag is true, is expected to act as if it had a user-agent-level style sheet rule setting the following properties:

15.3.4 Phrasing content

@namespace url(http://www.w3.org/1999/xhtml);

cite, dfn, em, i, var { font-style: italic; }
b, strong { font-weight: bolder; }
code, kbd, samp, tt { font-family: monospace; }
big { font-size: larger; }
small { font-size: smaller; }

sub { vertical-align: sub; }
sup { vertical-align: super; }
sub, sup { line-height: normal; font-size: smaller; }

ruby { display: ruby; }
rt { display: ruby-text; }

:link { color: #0000EE; }
:visited { color: #551A8B; }
:link:active, :visited:active { color: #FF0000; }
:link, :visited { text-decoration: underline; cursor: pointer; }

:focus { outline: auto; }

mark { background: yellow; color: black; } /* this color is just a suggestion and can be changed based on implementation feedback */

abbr[title], acronym[title] { text-decoration: dotted underline; }
ins, u { text-decoration: underline; }
del, s, strike { text-decoration: line-through; }

q::before { content: open-quote; }
q::after { content: close-quote; }

br { display-outside: newline; } /* this also has bidi implications */
nobr { white-space: nowrap; }
wbr { display-outside: break-opportunity; } /* this also has bidi implications */
nobr wbr { white-space: normal; }

The following rules are also expected to apply, as presentational hints:

@namespace url(http://www.w3.org/1999/xhtml);

br[clear=left i] { clear: left; }
br[clear=right i] { clear: right; }
br[clear=all i], br[clear=both i] { clear: both; }

For the purposes of the CSS ruby model, runs of children of ruby elements that are not rt or rp elements are expected to be wrapped in anonymous boxes whose 'display' property has the value 'ruby-base'. [CSSRUBY]

When a particular part of a ruby has more than one annotation, the annotations should be distributed on both sides of the base text so as to minimize the stacking of ruby annotations on one side.

When it becomes possible to do so, the preceding requirement will be updated to be expressed in terms of CSS ruby. (Currently, CSS ruby does not handle nested ruby elements or multiple sequential rt elements, which is how this semantic is expressed.)

User agents that do not support correct ruby rendering are expected to render parentheses around the text of rt elements in the absence of rp elements.


User agents are expected to support the 'clear' property on inline elements (in order to render br elements with clear attributes) in the manner described in the non-normative note to this effect in CSS.

The initial value for the 'color' property is expected to be black. The initial value for the 'background-color' property is expected to be 'transparent'. The canvas's background is expected to be white.


When a font element has a color attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'color' property to the resulting color.

The font element is expected to override the color of any text decoration that spans the text of the element to the used value of the element's 'color' property.

When a font element has a face attribute, the user agent is expected to treat the attribute as a presentational hint setting the element's 'font-family' property to the attribute's value.

When a font element has a size attribute, the user agent is expected to use the following steps, known as the rules for parsing a legacy font size, to treat the attribute as a presentational hint setting the element's 'font-size' property:

  1. Let input be the attribute's value.

  2. Let position be a pointer into input, initially pointing at the start of the string.

  3. Skip ASCII whitespace within input given position.

  4. If position is past the end of input, there is no presentational hint. Return.

  5. If the character at position is a U+002B PLUS SIGN character (+), then let mode be relative-plus, and advance position to the next character. Otherwise, if the character at position is a U+002D HYPHEN-MINUS character (-), then let mode be relative-minus, and advance position to the next character. Otherwise, let mode be absolute.

  6. Collect a sequence of code points that are ASCII digits from input given position, and let the resulting sequence be digits.

  7. If digits is the empty string, there is no presentational hint. Return.

  8. Interpret digits as a base-ten integer. Let value be the resulting number.

  9. If mode is relative-plus, then increment value by 3. If mode is relative-minus, then let value be the result of subtracting value from 3.

  10. If value is greater than 7, let it be 7.

  11. If value is less than 1, let it be 1.

  12. Set 'font-size' to the keyword corresponding to the value of value according to the following table:

    value 'font-size' keyword
    1 'x-small'
    2 'small'
    3 'medium'
    4 'large'
    5 'x-large'
    6 'xx-large'
    7 'xxx-large'

15.3.5 Bidirectional text

@namespace url(http://www.w3.org/1999/xhtml);

[dir]:dir(ltr), bdi:dir(ltr), input[type=tel i]:dir(ltr) { direction: ltr; }
[dir]:dir(rtl), bdi:dir(rtl) { direction: rtl; }

address, blockquote, center, div, figure, figcaption, footer, form, header, hr,
legend, listing, main, p, plaintext, pre, summary, xmp, article, aside, h1, h2,
h3, h4, h5, h6, hgroup, nav, section, table, caption, colgroup, col, thead,
tbody, tfoot, tr, td, th, dir, dd, dl, dt, menu, ol, ul, li, bdi, output,
[dir=ltr i], [dir=rtl i], [dir=auto i] {
  unicode-bidi: isolate; 
}

bdo, bdo[dir] { unicode-bidi: isolate-override; } 

input[dir=auto i]:is([type=search i], [type=tel i], [type=url i],
[type=email i]), textarea[dir=auto i], pre[dir=auto i] {
  unicode-bidi: plaintext;
}
/* see prose for input elements whose type attribute is in the Text state */

/* the rules setting the 'content' property on br and wbr elements also has bidi implications */

When an input element's dir attribute is in the auto state and its type attribute is in the Text state, then the user agent is expected to act as if it had a user-agent-level style sheet rule setting the 'unicode-bidi' property to 'plaintext'.

Input fields (i.e. textarea elements, and input elements when their type attribute is in the Text, Search, Telephone, URL, or Email state) are expected to present an editing user interface with a directionality that matches the element's 'direction' property.

When the document's character encoding is ISO-8859-8, the following rules are additionally expected to apply, following those above: [ENCODING]

@namespace url(http://www.w3.org/1999/xhtml);

address, blockquote, center, div, figure, figcaption, footer, form, header, hr,
legend, listing, main, p, plaintext, pre, summary, xmp, article, aside, h1, h2,
h3, h4, h5, h6, hgroup, nav, section, table, caption, colgroup, col, thead,
tbody, tfoot, tr, td, th, dir, dd, dl, dt, menu, ol, ul, li, [dir=ltr i],
[dir=rtl i], [dir=auto i], *|* {
  unicode-bidi: bidi-override;
}
input:not([type=submit i]):not([type=reset i]):not([type=button i]),
textarea {
  unicode-bidi: normal;
}

15.3.6 Sections and headings

@namespace url(http://www.w3.org/1999/xhtml);

article, aside, h1, h2, h3, h4, h5, h6, hgroup, nav, section {
  display: block;
}

h1 { margin-block-start: 0.67em; margin-block-end: 0.67em; font-size: 2.00em; font-weight: bold; }
h2 { margin-block-start: 0.83em; margin-block-end: 0.83em; font-size: 1.50em; font-weight: bold; }
h3 { margin-block-start: 1.00em; margin-block-end: 1.00em; font-size: 1.17em; font-weight: bold; }
h4 { margin-block-start: 1.33em; margin-block-end: 1.33em; font-size: 1.00em; font-weight: bold; }
h5 { margin-block-start: 1.67em; margin-block-end: 1.67em; font-size: 0.83em; font-weight: bold; }
h6 { margin-block-start: 2.33em; margin-block-end: 2.33em; font-size: 0.67em; font-weight: bold; }

In the following CSS block, x is shorthand for the following selector: :is(article, aside, nav, section)

@namespace url(http://www.w3.org/1999/xhtml);

x h1 { margin-block-start: 0.83em; margin-block-end: 0.83em; font-size: 1.50em; }
x x h1 { margin-block-start: 1.00em; margin-block-end: 1.00em; font-size: 1.17em; }
x x x h1 { margin-block-start: 1.33em; margin-block-end: 1.33em; font-size: 1.00em; }
x x x x h1 { margin-block-start: 1.67em; margin-block-end: 1.67em; font-size: 0.83em; }
x x x x x h1 { margin-block-start: 2.33em; margin-block-end: 2.33em; font-size: 0.67em; }

x hgroup > h1 ~ h2 { margin-block-start: 1.00em; margin-block-end: 1.00em; font-size: 1.17em; }
x x hgroup > h1 ~ h2 { margin-block-start: 1.33em; margin-block-end: 1.33em; font-size: 1.00em; }
x x x hgroup > h1 ~ h2 { margin-block-start: 1.67em; margin-block-end: 1.67em; font-size: 0.83em; }
x x x x hgroup > h1 ~ h2 { margin-block-start: 2.33em; margin-block-end: 2.33em; font-size: 0.67em; }

x hgroup > h1 ~ h3 { margin-block-start: 1.33em; margin-block-end: 1.33em; font-size: 1.00em; }
x x hgroup > h1 ~ h3 { margin-block-start: 1.67em; margin-block-end: 1.67em; font-size: 0.83em; }
x x x hgroup > h1 ~ h3 { margin-block-start: 2.33em; margin-block-end: 2.33em; font-size: 0.67em; }

x hgroup > h1 ~ h4 { margin-block-start: 1.67em; margin-block-end: 1.67em; font-size: 0.83em; }
x x hgroup > h1 ~ h4 { margin-block-start: 2.33em; margin-block-end: 2.33em; font-size: 0.67em; }

x hgroup > h1 ~ h5 { margin-block-start: 2.33em; margin-block-end: 2.33em; font-size: 0.67em; }

The shorthand is used to keep this block at least mildly readable.

15.3.7 Lists

@namespace url(http://www.w3.org/1999/xhtml);

dir, dd, dl, dt, menu, ol, ul { display: block; }
li { display: list-item; }

dir, dl, menu, ol, ul { margin-block-start: 1em; margin-block-end: 1em; }

:is(dir, dl, menu, ol, ul) :is(dir, dl, menu, ol, ul) {
  margin-block-start: 0; margin-block-end: 0;
}

dd { margin-inline-start: 40px; }
dir, menu, ol, ul { padding-inline-start: 40px; }

ol { list-style-type: decimal; }

dir, menu, ul {
  list-style-type: disc;
}
:is(dir, menu, ol, ul) :is(dir, menu, ul) {
  list-style-type: circle;
}
:is(dir, menu, ol, ul) :is(dir, menu, ol, ul) :is(dir, menu, ul) {
  list-style-type: square;
}

The following rules are also expected to apply, as presentational hints:

@namespace url(http://www.w3.org/1999/xhtml);

ol[type="1"], li[type="1"] { list-style-type: decimal; }
ol[type=a s], li[type=a s] { list-style-type: lower-alpha; }
ol[type=A s], li[type=A s] { list-style-type: upper-alpha; }
ol[type=i s], li[type=i s] { list-style-type: lower-roman; }
ol[type=I s], li[type=I s] { list-style-type: upper-roman; }
ul[type=none i], li[type=none i] { list-style-type: none; }
ul[type=disc i], li[type=disc i] { list-style-type: disc; }
ul[type=circle i], li[type=circle i] { list-style-type: circle; }
ul[type=square i], li[type=square i] { list-style-type: square; }

When rendering li elements, non-CSS user agents are expected to use the ordinal value of the li element to render the counter in the list item marker.

This specification does not yet define the CSS-specific rules for rendering li elements, because CSS doesn't yet provide sufficient hooks for this purpose.

15.3.8 Tables

@namespace url(http://www.w3.org/1999/xhtml);

table { display: table; }
caption { display: table-caption; }
colgroup, colgroup[hidden] { display: table-column-group; }
col, col[hidden] { display: table-column; }
thead, thead[hidden] { display: table-header-group; }
tbody, tbody[hidden] { display: table-row-group; }
tfoot, tfoot[hidden] { display: table-footer-group; }
tr, tr[hidden] { display: table-row; }
td, th { display: table-cell; }

colgroup[hidden], col[hidden], thead[hidden], tbody[hidden],
tfoot[hidden], tr[hidden] {
  visibility: collapse;
}

table {
  box-sizing: border-box;
  border-spacing: 2px;
  border-collapse: separate;
  text-indent: initial;
}
td, th { padding: 1px; }
th { font-weight: bold; }

caption { text-align: center; }
thead, tbody, tfoot, table > tr { vertical-align: middle; }
tr, td, th { vertical-align: inherit; }

thead, tbody, tfoot, tr { border-color: inherit; }
table[rules=none i], table[rules=groups i], table[rules=rows i],
table[rules=cols i], table[rules=all i], table[frame=void i],
table[frame=above i], table[frame=below i], table[frame=hsides i],
table[frame=lhs i], table[frame=rhs i], table[frame=vsides i],
table[frame=box i], table[frame=border i],
table[rules=none i] > tr > td, table[rules=none i] > tr > th,
table[rules=groups i] > tr > td, table[rules=groups i] > tr > th,
table[rules=rows i] > tr > td, table[rules=rows i] > tr > th,
table[rules=cols i] > tr > td, table[rules=cols i] > tr > th,
table[rules=all i] > tr > td, table[rules=all i] > tr > th,
table[rules=none i] > thead > tr > td, table[rules=none i] > thead > tr > th,
table[rules=groups i] > thead > tr > td, table[rules=groups i] > thead > tr > th,
table[rules=rows i] > thead > tr > td, table[rules=rows i] > thead > tr > th,
table[rules=cols i] > thead > tr > td, table[rules=cols i] > thead > tr > th,
table[rules=all i] > thead > tr > td, table[rules=all i] > thead > tr > th,
table[rules=none i] > tbody > tr > td, table[rules=none i] > tbody > tr > th,
table[rules=groups i] > tbody > tr > td, table[rules=groups i] > tbody > tr > th,
table[rules=rows i] > tbody > tr > td, table[rules=rows i] > tbody > tr > th,
table[rules=cols i] > tbody > tr > td, table[rules=cols i] > tbody > tr > th,
table[rules=all i] > tbody > tr > td, table[rules=all i] > tbody > tr > th,
table[rules=none i] > tfoot > tr > td, table[rules=none i] > tfoot > tr > th,
table[rules=groups i] > tfoot > tr > td, table[rules=groups i] > tfoot > tr > th,
table[rules=rows i] > tfoot > tr > td, table[rules=rows i] > tfoot > tr > th,
table[rules=cols i] > tfoot > tr > td, table[rules=cols i] > tfoot > tr > th,
table[rules=all i] > tfoot > tr > td, table[rules=all i] > tfoot > tr > th {
  border-color: black;
}

The following rules are also expected to apply, as presentational hints:

@namespace url(http://www.w3.org/1999/xhtml);

table[align=left i] { float: left; }
table[align=right i] { float: right; }
table[align=center i] { margin-inline-start: auto; margin-inline-end: auto; }
thead[align=absmiddle i], tbody[align=absmiddle i], tfoot[align=absmiddle i],
tr[align=absmiddle i], td[align=absmiddle i], th[align=absmiddle i] {
  text-align: center;
}

caption[align=bottom i] { caption-side: bottom; }
p[align=left i], h1[align=left i], h2[align=left i], h3[align=left i],
h4[align=left i], h5[align=left i], h6[align=left i] {
  text-align: left;
}
p[align=right i], h1[align=right i], h2[align=right i], h3[align=right i],
h4[align=right i], h5[align=right i], h6[align=right i] {
  text-align: right;
}
p[align=center i], h1[align=center i], h2[align=center i], h3[align=center i],
h4[align=center i], h5[align=center i], h6[align=center i] {
  text-align: center;
}
p[align=justify i], h1[align=justify i], h2[align=justify i], h3[align=justify i],
h4[align=justify i], h5[align=justify i], h6[align=justify i] {
  text-align: justify;
}
thead[valign=top i], tbody[valign=top i], tfoot[valign=top i],
tr[valign=top i], td[valign=top i], th[valign=top i] {
  vertical-align: top;
}
thead[valign=middle i], tbody[valign=middle i], tfoot[valign=middle i],
tr[valign=middle i], td[valign=middle i], th[valign=middle i] {
  vertical-align: middle;
}
thead[valign=bottom i], tbody[valign=bottom i], tfoot[valign=bottom i],
tr[valign=bottom i], td[valign=bottom i], th[valign=bottom i] {
  vertical-align: bottom;
}
thead[valign=baseline i], tbody[valign=baseline i], tfoot[valign=baseline i],
tr[valign=baseline i], td[valign=baseline i], th[valign=baseline i] {
  vertical-align: baseline;
}

td[nowrap], th[nowrap] { white-space: nowrap; }

table[rules=none i], table[rules=groups i], table[rules=rows i],
table[rules=cols i], table[rules=all i] {
  border-style: hidden;
  border-collapse: collapse;
}
table[border] { border-style: outset; } /* only if border is not equivalent to zero */
table[frame=void i] { border-style: hidden; }
table[frame=above i] { border-style: outset hidden hidden hidden; }
table[frame=below i] { border-style: hidden hidden outset hidden; }
table[frame=hsides i] { border-style: outset hidden outset hidden; }
table[frame=lhs i] { border-style: hidden hidden hidden outset; }
table[frame=rhs i] { border-style: hidden outset hidden hidden; }
table[frame=vsides i] { border-style: hidden outset; }
table[frame=box i], table[frame=border i] { border-style: outset; }

table[border] > tr > td, table[border] > tr > th,
table[border] > thead > tr > td, table[border] > thead > tr > th,
table[border] > tbody > tr > td, table[border] > tbody > tr > th,
table[border] > tfoot > tr > td, table[border] > tfoot > tr > th {
  /* only if border is not equivalent to zero */
  border-width: 1px;
  border-style: inset;
}
table[rules=none i] > tr > td, table[rules=none i] > tr > th,
table[rules=none i] > thead > tr > td, table[rules=none i] > thead > tr > th,
table[rules=none i] > tbody > tr > td, table[rules=none i] > tbody > tr > th,
table[rules=none i] > tfoot > tr > td, table[rules=none i] > tfoot > tr > th,
table[rules=groups i] > tr > td, table[rules=groups i] > tr > th,
table[rules=groups i] > thead > tr > td, table[rules=groups i] > thead > tr > th,
table[rules=groups i] > tbody > tr > td, table[rules=groups i] > tbody > tr > th,
table[rules=groups i] > tfoot > tr > td, table[rules=groups i] > tfoot > tr > th,
table[rules=rows i] > tr > td, table[rules=rows i] > tr > th,
table[rules=rows i] > thead > tr > td, table[rules=rows i] > thead > tr > th,
table[rules=rows i] > tbody > tr > td, table[rules=rows i] > tbody > tr > th,
table[rules=rows i] > tfoot > tr > td, table[rules=rows i] > tfoot > tr > th {
  border-width: 1px;
  border-style: none;
}
table[rules=cols i] > tr > td, table[rules=cols i] > tr > th,
table[rules=cols i] > thead > tr > td, table[rules=cols i] > thead > tr > th,
table[rules=cols i] > tbody > tr > td, table[rules=cols i] > tbody > tr > th,
table[rules=cols i] > tfoot > tr > td, table[rules=cols i] > tfoot > tr > th {
  border-width: 1px;
  border-block-start-style: none;
  border-inline-end-style: solid;
  border-block-end-style: none;
  border-inline-start-style: solid;
}
table[rules=all i] > tr > td, table[rules=all i] > tr > th,
table[rules=all i] > thead > tr > td, table[rules=all i] > thead > tr > th,
table[rules=all i] > tbody > tr > td, table[rules=all i] > tbody > tr > th,
table[rules=all i] > tfoot > tr > td, table[rules=all i] > tfoot > tr > th {
  border-width: 1px;
  border-style: solid;
}

table[rules=groups i] > colgroup {
  border-inline-start-width: 1px;
  border-inline-start-style: solid;
  border-inline-end-width: 1px;
  border-inline-end-style: solid;
}
table[rules=groups i] > thead,
table[rules=groups i] > tbody,
table[rules=groups i] > tfoot {
  border-block-start-width: 1px;
  border-block-start-style: solid;
  border-block-end-width: 1px;
  border-block-end-style: solid;
}

table[rules=rows i] > tr, table[rules=rows i] > thead > tr,
table[rules=rows i] > tbody > tr, table[rules=rows i] > tfoot > tr {
  border-block-start-width: 1px;
  border-block-start-style: solid;
  border-block-end-width: 1px;
  border-block-end-style: solid;
}

In quirks mode, the following rules are also expected to apply:

@namespace url(http://www.w3.org/1999/xhtml);

table {
  font-weight: initial;
  font-style: initial;
  font-variant: initial;
  font-size: initial;
  line-height: initial;
  white-space: initial;
  text-align: initial;
}

For the purposes of the CSS table model, the col element is expected to be treated as if it was present as many times as its span attribute specifies.

For the purposes of the CSS table model, the colgroup element, if it contains no col element, is expected to be treated as if it had as many such children as its span attribute specifies.

For the purposes of the CSS table model, the colspan and rowspan attributes on td and th elements are expected to provide the special knowledge regarding cells spanning rows and columns.

In HTML documents, the following rules are also expected to apply:

@namespace url(http://www.w3.org/1999/xhtml);

:is(table, thead, tbody, tfoot, tr) > form { display: none !important; }

The table element's cellspacing attribute maps to the pixel length property 'border-spacing' on the element.

The table element's cellpadding attribute maps to the pixel length properties 'padding-top', 'padding-right', 'padding-bottom', and 'padding-left' of any td and th elements that have corresponding cells in the table corresponding to the table element.

The table element's height attribute maps to the dimension property (ignoring zero) 'height' on the table element.

The table element's width attribute maps to the dimension property (ignoring zero) 'width' on the table element.

The col element's width attribute maps to the dimension property 'width' on the col element.

The thead, tbody, and tfoot elements' height attribute maps to the dimension property 'height' on the element.

The tr element's height attribute maps to the dimension property (ignoring zero) 'height' on the tr element.

The td and th elements' height attributes map to the dimension property (ignoring zero) 'height' on the element.

The td and th elements' width attributes map to the dimension property (ignoring zero) 'width' on the element.


The thead, tbody, tfoot, tr, td, and th elements, when they have an align attribute whose value is an ASCII case-insensitive match for either the string "center" or the string "middle", are expected to center text within themselves, as if they had their 'text-align' property set to 'center' in a presentational hint, and to align descendants to the center.

The thead, tbody, tfoot, tr, td, and th elements, when they have an align attribute whose value is an ASCII case-insensitive match for the string "left", are expected to left-align text within themselves, as if they had their 'text-align' property set to 'left' in a presentational hint, and to align descendants to the left.

The thead, tbody, tfoot, tr, td, and th elements, when they have an align attribute whose value is an ASCII case-insensitive match for the string "right", are expected to right-align text within themselves, as if they had their 'text-align' property set to 'right' in a presentational hint, and to align descendants to the right.

The thead, tbody, tfoot, tr, td, and th elements, when they have an align attribute whose value is an ASCII case-insensitive match for the string "justify", are expected to full-justify text within themselves, as if they had their 'text-align' property set to 'justify' in a presentational hint, and to align descendants to the left.

User agents are expected to have a rule in their user agent style sheet that matches th elements that have a parent node whose computed value for the 'text-align' property is its initial value, whose declaration block consists of just a single declaration that sets the 'text-align' property to the value 'center'.


When a table, thead, tbody, tfoot, tr, td, or th element has a background attribute set to a non-empty value, the new value is expected to be parsed relative to the element's node document, and if this is successful, the user agent is expected to treat the attribute as a presentational hint setting the element's 'background-image' property to the resulting URL string.

When a table, thead, tbody, tfoot, tr, td, or th element has a bgcolor attribute set, the new value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'background-color' property to the resulting color.

When a table element has a bordercolor attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'border-top-color', 'border-right-color', 'border-bottom-color', and 'border-left-color' properties to the resulting color.


The table element's border attribute maps to the pixel length properties 'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width' on the element. If the attribute is present but parsing the attribute's value using the rules for parsing non-negative integers generates an error, a default value of 1px is expected to be used for that property instead.

Rules marked "only if border is not equivalent to zero" in the CSS block above is expected to only be applied if the border attribute mentioned in the selectors for the rule is not only present but, when parsed using the rules for parsing non-negative integers, is also found to have a value other than zero or to generate an error.


In quirks mode, a td element or a th element that has a nowrap attribute but also has a width attribute whose value, when parsed using the rules for parsing nonzero dimension values, is found to be a length (not an error or a number classified as a percentage), is expected to have a presentational hint setting the element's 'white-space' property to 'normal', overriding the rule in the CSS block above that sets it to 'nowrap'.

15.3.9 Margin collapsing quirks

A node is substantial if it is a text node that is not inter-element whitespace, or if it is an element node.

A node is blank if it is an element that contains no substantial nodes.

The elements with default margins are the following elements: blockquote, dir, dl, h1, h2, h3, h4, h5, h6, listing, menu, ol, p, plaintext, pre, ul, xmp

In quirks mode, any element with default margins that is the child of a body, td, or th element and has no substantial previous siblings is expected to have a user-agent level style sheet rule that sets its 'margin-block-start' property to zero.

In quirks mode, any element with default margins that is the child of a body, td, or th element, has no substantial previous siblings, and is blank, is expected to have a user-agent level style sheet rule that sets its 'margin-block-end' property to zero also.

In quirks mode, any element with default margins that is the child of a td or th element, has no substantial following siblings, and is blank, is expected to have a user-agent level style sheet rule that sets its 'margin-block-start' property to zero.

In quirks mode, any p element that is the child of a td or th element and has no substantial following siblings, is expected to have a user-agent level style sheet rule that sets its 'margin-block-end' property to zero.

15.3.10 Form controls

@namespace url(http://www.w3.org/1999/xhtml);

input, select, button, textarea {
  letter-spacing: initial;
  word-spacing: initial;
  line-height: initial;
  text-transform: initial;
  text-indent: initial;
  text-shadow: initial;
}

input, select, textarea {
  text-align: initial;
}

input:is([type=reset i], [type=button i], [type=submit i]), button {
  text-align: center;
}

input:is([type=reset i], [type=button i], [type=submit i], [type=color i]), button {
  display: inline-block;
}

input:is([type=radio i], [type=checkbox i], [type=reset i], [type=button i],
[type=submit i], [type=color i], [type=search i]), select, button {
  box-sizing: border-box;
}

textarea { white-space: pre-wrap; }

In quirks mode, the following rules are also expected to apply:

@namespace url(http://www.w3.org/1999/xhtml);

input:not([type=image i]), textarea { box-sizing: border-box; }

Each kind of form control is also described in the Widgets section, which describes the look and feel of the control.

15.3.11 The hr element

@namespace url(http://www.w3.org/1999/xhtml);

hr {
  color: gray;
  border-style: inset;
  border-width: 1px;
  margin-block-start: 0.5em;
  margin-inline-end: auto;
  margin-block-end: 0.5em;
  margin-inline-start: auto;
  overflow: hidden;
}

The following rules are also expected to apply, as presentational hints:

@namespace url(http://www.w3.org/1999/xhtml);

hr[align=left i] { margin-left: 0; margin-right: auto; }
hr[align=right i] { margin-left: auto; margin-right: 0; }
hr[align=center i] { margin-left: auto; margin-right: auto; }
hr[color], hr[noshade] { border-style: solid; }

If an hr element has either a color attribute or a noshade attribute, and furthermore also has a size attribute, and parsing that attribute's value using the rules for parsing non-negative integers doesn't generate an error, then the user agent is expected to use the parsed value divided by two as a pixel length for presentational hints for the properties 'border-top-width', 'border-right-width', 'border-bottom-width', and 'border-left-width' on the element.

Otherwise, if an hr element has neither a color attribute nor a noshade attribute, but does have a size attribute, and parsing that attribute's value using the rules for parsing non-negative integers doesn't generate an error, then: if the parsed value is one, then the user agent is expected to use the attribute as a presentational hint setting the element's 'border-bottom-width' to 0; otherwise, if the parsed value is greater than one, then the user agent is expected to use the parsed value minus two as a pixel length for presentational hints for the 'height' property on the element.

The width attribute on an hr element maps to the dimension property 'width' on the element.

When an hr element has a color attribute, its value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'color' property to the resulting color.

15.3.12 The fieldset and legend elements

@namespace url(http://www.w3.org/1999/xhtml);

fieldset {
  display: block;
  margin-inline-start: 2px;
  margin-inline-end: 2px;
  border: groove 2px ThreeDFace;
  padding-block-start: 0.35em;
  padding-inline-end: 0.75em;
  padding-block-end: 0.625em;
  padding-inline-start: 0.75em;
  min-inline-size: min-content;
}

legend {
  padding-inline-start: 2px; padding-inline-end: 2px;
}

legend[align=left i] {
  justify-self: left;
}

legend[align=center i] {
  justify-self: center;
}

legend[align=right i] {
  justify-self: right;
}

The fieldset element, when it generates a CSS box, is expected to act as follows:

A fieldset element's rendered legend, if any, is expected to act as follows:

A fieldset element's anonymous fieldset content box is expected to act as follows:

fieldset's margin legend padding legend's margin padding anonymous fieldset content box content
The legend is rendered over the top border, and the top border area reserves vertical space for the legend. The fieldset's top margin starts at the top margin edge of the legend. The legend's horizontal margins, or the 'justify-self' property, gives its horizontal position. The anonymous fieldset content box appears below the legend.

15.4 Replaced elements

The following elements can be replaced elements: audio, canvas, embed, iframe, img, input, object, and video.

15.4.1 Embedded content

The embed, iframe, and video elements are expected to be treated as replaced elements.

A canvas element that represents embedded content is expected to be treated as a replaced element; the contents of such elements are the element's bitmap, if any, or else a transparent black bitmap with the same intrinsic dimensions as the element. Other canvas elements are expected to be treated as ordinary elements in the rendering model.

An object element that represents an image, plugin, or its nested browsing context is expected to be treated as a replaced element. Other object elements are expected to be treated as ordinary elements in the rendering model.

The audio element, when it is exposing a user interface, is expected to be treated as a replaced element about one line high, as wide as is necessary to expose the user agent's user interface features. When an audio element is not exposing a user interface, the user agent is expected to force its 'display' property to compute to 'none', irrespective of CSS rules.

Whether a video element is exposing a user interface is not expected to affect the size of the rendering; controls are expected to be overlaid above the page content without causing any layout changes, and are expected to disappear when the user does not need them.

When a video element represents a poster frame or frame of video, the poster frame or frame of video is expected to be rendered at the largest size that maintains the aspect ratio of that poster frame or frame of video without being taller or wider than the video element itself, and is expected to be centered in the video element.

Any subtitles or captions are expected to be overlayed directly on top of their video element, as defined by the relevant rendering rules; for WebVTT, those are the rules for updating the display of WebVTT text tracks. [WEBVTT]

When the user agent starts exposing a user interface for a video element, the user agent should run the rules for updating the text track rendering of each of the text tracks in the video element's list of text tracks that are showing and whose text track kind is one of subtitles or captions (e.g., for text tracks based on WebVTT, the rules for updating the display of WebVTT text tracks). [WEBVTT]

Resizing video and canvas elements does not interrupt video playback or clear the canvas.


The following CSS rules are expected to apply:

@namespace url(http://www.w3.org/1999/xhtml);

iframe { border: 2px inset; }
video { object-fit: contain; }

15.4.2 Images

User agents are expected to render img elements and input elements whose type attributes are in the Image Button state, according to the first applicable rules from the following list:

If the element represents an image
The user agent is expected to treat the element as a replaced element and render the image according to the rules for doing so defined in CSS.
If the element does not represent an image and either:
The user agent is expected to treat the element as a replaced element whose content is the text that the element represents, if any, optionally alongside an icon indicating that the image is being obtained (if applicable). For input elements, the element is expected to appear button-like to indicate that the element is a button.
If the element is an img element that represents some text and the user agent does not expect this to change
The user agent is expected to treat the element as a non-replaced phrasing element whose content is the text, optionally with an icon indicating that an image is missing, so that the user can request the image be displayed or investigate why it is not rendering. In non-graphical contexts, such an icon should be omitted.
If the element is an img element that represents nothing and the user agent does not expect this to change
The user agent is expected to treat the element as a replaced element whose intrinsic dimensions are 0. (In the absence of further styles, this will cause the element to essentially not be rendered.)
If the element is an input element that does not represent an image and the user agent does not expect this to change
The user agent is expected to treat the element as a replaced element consisting of a button whose content is the element's alternative text. The intrinsic dimensions of the button are expected to be about one line in height and whatever width is necessary to render the text on one line.

The icons mentioned above are expected to be relatively small so as not to disrupt most text but be easily clickable. In a visual environment, for instance, icons could be 16 pixels by 16 pixels square, or 1em by 1em if the images are scalable. In an audio environment, the icon could be a short bleep. The icons are intended to indicate to the user that they can be used to get to whatever options the UA provides for images, and, where appropriate, are expected to provide access to the context menu that would have come up if the user interacted with the actual image.


All animated images with the same absolute URL and the same image data are expected to be rendered synchronized to the same timeline as a group, with the timeline starting at the time of the least recent addition to the group.

In other words, when a second image with the same absolute URL and animated image data is inserted into a document, it jumps to the point in the animation cycle that is currently being displayed by the first image.

When a user agent is to restart the animation for an img element showing an animated image, all animated images with the same absolute URL and the same image data in that img element's node document are expected to restart their animation from the beginning.


The following CSS rules are expected to apply when the Document is in quirks mode:

@namespace url(http://www.w3.org/1999/xhtml);

img[align=left i] { margin-right: 3px; }
img[align=right i] { margin-left: 3px; }

15.4.3 Attributes for embedded content and images

The following CSS rules are expected to apply as presentational hints:

@namespace url(http://www.w3.org/1999/xhtml);

iframe[frameborder='0'], iframe[frameborder=no i] { border: none; }

embed[align=left i], iframe[align=left i], img[align=left i],
input[type=image i][align=left i], object[align=left i] {
  float: left;
}

embed[align=right i], iframe[align=right i], img[align=right i],
input[type=image i][align=right i], object[align=right i] {
  float: right;
}

embed[align=top i], iframe[align=top i], img[align=top i],
input[type=image i][align=top i], object[align=top i] {
  vertical-align: top;
}

embed[align=baseline i], iframe[align=baseline i], img[align=baseline i],
input[type=image i][align=baseline i], object[align=baseline i] {
  vertical-align: baseline;
}

embed[align=texttop i], iframe[align=texttop i], img[align=texttop i],
input[type=image i][align=texttop i], object[align=texttop i] {
  vertical-align: text-top;
}

embed[align=absmiddle i], iframe[align=absmiddle i], img[align=absmiddle i],
input[type=image i][align=absmiddle i], object[align=absmiddle i],
embed[align=abscenter i], iframe[align=abscenter i], img[align=abscenter i],
input[type=image i][align=abscenter i], object[align=abscenter i] {
  vertical-align: middle;
}

embed[align=bottom i], iframe[align=bottom i], img[align=bottom i],
input[type=image i][align=bottom i], object[align=bottom i] {
  vertical-align: bottom;
}

When an embed, iframe, img, or object element, or an input element whose type attribute is in the Image Button state, has an align attribute whose value is an ASCII case-insensitive match for the string "center" or the string "middle", the user agent is expected to act as if the element's 'vertical-align' property was set to a value that aligns the vertical middle of the element with the parent element's baseline.

The hspace attribute of embed, img, or object elements, and input elements with a type attribute in the Image Button state, maps to the dimension properties 'margin-left' and 'margin-right' on the element.

The vspace attribute of embed, img, or object elements, and input elements with a type attribute in the Image Button state, maps to the dimension properties 'margin-top' and 'margin-bottom' on the element.

When an img element, object element, or input element with a type attribute in the Image Button state has a border attribute whose value, when parsed using the rules for parsing non-negative integers, is found to be a number greater than zero, the user agent is expected to use the parsed value for eight presentational hints: four setting the parsed value as a pixel length for the element's 'border-top-width', 'border-right-width', 'border-bottom-width', and 'border-left-width' properties, and four setting the element's 'border-top-style', 'border-right-style', 'border-bottom-style', and 'border-left-style' properties to the value 'solid'.

The width and height attributes on embed, iframe, img, object or video elements, and input elements with a type attribute in the Image Button state and that either represents an image or that the user expects will eventually represent an image, map to the dimension properties 'width' and 'height' on the element respectively.

The intrinsic aspect ratio for an img element img is computed as follows:

  1. If img's current request is available and has an intrinsic aspect ratio, then use that intrinsic aspect ratio.

  2. If img's width and height attribute values, when parsed using the rules for parsing dimension values, are both not an error, not a percentage, and non-zero, then use the ratio resulting from dividing the width attribute value by the height attribute value.

  3. Otherwise, img has no intrinsic aspect ratio.

15.4.4 Image maps

Shapes on an image map are expected to act, for the purpose of the CSS cascade, as elements independent of the original area element that happen to match the same style rules but inherit from the img or object element.

For the purposes of the rendering, only the 'cursor' property is expected to have any effect on the shape.

Thus, for example, if an area element has a style attribute that sets the 'cursor' property to 'help', then when the user designates that shape, the cursor would change to a Help cursor.

Similarly, if an area element had a CSS rule that set its 'cursor' property to 'inherit' (or if no rule setting the 'cursor' property matched the element at all), the shape's cursor would be inherited from the img or object element of the image map, not from the parent of the area element.

15.5 微件

15.5.1 简介

本节中定义的元素可以在以下提供的指导方针范围内以多种方式呈现。鼓励用户代理设置'appearance' CSS 属性以适当的实现微件的原生外观,并期望实现适合于平台的相关动画等。

15.5.2 Button layout

Button layout is as follows:

15.5.3 button 元素

button 元素应该被渲染为一个 'inline-block' 盒,内部为元素内容的按钮。

15.5.4 detailssummary 元素

@namespace url(http://www.w3.org/1999/xhtml);

summary {
  display: list-item;
  counter-increment: list-item 0;
  list-style: disclosure-closed inside;
}
details[open] > summary {
  list-style-type: disclosure-open;
}

details 元素应该被渲染成 block box。该元素的 Shadow 树应该获取元素的第一个 summary 子元素(如果有),并放入第一个 block box 容器中,然后将其它的后代(如果有) 放入第二个 block box 容器中。

第一个容器应该允许用户请求显示或者隐藏详情。

details 元素没有 open 属性时,第二个容器 应当在渲染时被移除。

15.5.5 input 元素作为文本输入微件

type 属性为 Text, Search, Telephone, URL, 或 E-mail 状态的 input 元素应当被渲染为描绘一个输入框的 'inline-block' 盒。此外,'line-height' 属性如果 计算值 小于 1.0,其使用值必须为 1.0。

An input element whose type attribute is in the Password state is expected to render as an 'inline-block' box depicting a text control that obscures data entry.

If these text controls provide a text selection, then, when the user changes the current selection, the user agent is expected to queue a task, using the user interaction task source, to fire an event named select at the element, with the bubbles attribute initialized to true.

If an input element whose type attribute is in one of the above states has a size attribute, and parsing that attribute's value using the rules for parsing non-negative integers doesn't generate an error, then the user agent is expected to use the attribute as a presentational hint for the 'width' property on the element, with the value obtained from applying the converting a character width to pixels algorithm to the value of the attribute.

If an input element whose type attribute is in one of the above states does not have a size attribute, then the user agent is expected to act as if it had a user-agent-level style sheet rule setting the 'width' property on the element to the value obtained from applying the converting a character width to pixels algorithm to the number 20.

The converting a character width to pixels algorithm returns (size-1)×avg + max, where size is the character width to convert, avg is the average character width of the primary font for the element for which the algorithm is being run, in pixels, and max is the maximum character width of that same font, also in pixels. (The element's 'letter-spacing' property does not affect the result.)

15.5.6 The input element as domain-specific widgets

An input element whose type attribute is in the Date state is expected to render as an 'inline-block' box depicting a date control.

An input element whose type attribute is in the Month state is expected to render as an 'inline-block' box depicting a month control.

An input element whose type attribute is in the Week state is expected to render as an 'inline-block' box depicting a week control.

An input element whose type attribute is in the Time state is expected to render as an 'inline-block' box depicting a time control.

An input element whose type attribute is in the Local Date and Time state is expected to render as an 'inline-block' box depicting a local date and time control.

An input element whose type attribute is in the Number state is expected to render as an 'inline-block' box depicting a number control.

These controls are all expected to be about one line high, and about as wide as necessary to show the widest possible value.

15.5.7 The input element as a range control

An input element whose type attribute is in the Range state is expected to render as an 'inline-block' box depicting a slider control.

When the control is wider than it is tall (or square), the control is expected to be a horizontal slider, with the lowest value on the right if the 'direction' property on this element has a computed value of 'rtl', and on the left otherwise. When the control is taller than it is wide, it is expected to be a vertical slider, with the lowest value on the bottom.

Predefined suggested values (provided by the list attribute) are expected to be shown as tick marks on the slider, which the slider can snap to.

User agents are expected to use the used value of the 'direction' property on the element to determine the direction in which the slider operates. Typically, a left-to-right ('ltr') horizontal control would have the lowest value on the left and the highest value on the right, and vice versa.

15.5.8 The input element as a color well

An input element whose type attribute is in the Color state is expected to depict a color well, which, when activated, provides the user with a color picker (e.g. a color wheel or color palette) from which the color can be changed. The element, when it generates a CSS box, is expected to use button layout, that has no child boxes of the anonymous button content box. The anonymous button content box is expected to have a presentational hint setting the 'background-color' property to the element's value.

Predefined suggested values (provided by the list attribute) are expected to be shown in the color picker interface, not on the color well itself.

15.5.9 The input element as a checkbox and radio button widgets

An input element whose type attribute is in the Checkbox state is expected to render as an 'inline-block' box containing a single checkbox control, with no label.

An input element whose type attribute is in the Radio Button state is expected to render as an 'inline-block' box containing a single radio button control, with no label.

15.5.10 The input element as a file upload control

An input element whose type attribute is in the File Upload state, when it generates a CSS box, is expected to render as an 'inline-block' box containing a span of text giving the file name(s) of the selected files, if any, followed by a button that, when activated, provides the user with a file picker from which the selection can be changed. The button is expected to use button layout and the contents of the anonymous button content box are expected to be implementation-defined (and possibly locale-specific) text, for example "Choose file".

15.5.11 The input element as a button

An input element whose type attribute is in the Submit Button, Reset Button, or Button state, when it generates a CSS box, is expected to depict a button and use button layout and the contents of the anonymous button content box are expected to be the text of the element's value attribute, if any, or text derived from the element's type attribute in an implementation-defined (and probably locale-specific) fashion, if not.

15.5.12 The marquee element

@namespace url(http://www.w3.org/1999/xhtml);

marquee {
  display: inline-block;
  text-align: initial;
}

The marquee element, while turned on, is expected to render in an animated fashion according to its attributes as follows:

If the element's behavior attribute is in the scroll state

Slide the contents of the element in the direction described by the direction attribute as defined below, such that it begins off the start side of the marquee, and ends flush with the inner end side.

For example, if the direction attribute is left (the default), then the contents would start such that their left edge are off the side of the right edge of the marquee's content area, and the contents would then slide up to the point where the left edge of the contents are flush with the left inner edge of the marquee's content area.

Once the animation has ended, the user agent is expected to increment the marquee current loop index. If the element is still turned on after this, then the user agent is expected to restart the animation.

If the element's behavior attribute is in the slide state

Slide the contents of the element in the direction described by the direction attribute as defined below, such that it begins off the start side of the marquee, and ends off the end side of the marquee.

For example, if the direction attribute is left (the default), then the contents would start such that their left edge are off the side of the right edge of the marquee's content area, and the contents would then slide up to the point where the right edge of the contents are flush with the left inner edge of the marquee's content area.

Once the animation has ended, the user agent is expected to increment the marquee current loop index. If the element is still turned on after this, then the user agent is expected to restart the animation.

If the element's behavior attribute is in the alternate state

When the marquee current loop index is even (or zero), slide the contents of the element in the direction described by the direction attribute as defined below, such that it begins flush with the start side of the marquee, and ends flush with the end side of the marquee.

When the marquee current loop index is odd, slide the contents of the element in the opposite direction than that described by the direction attribute as defined below, such that it begins flush with the end side of the marquee, and ends flush with the start side of the marquee.

For example, if the direction attribute is left (the default), then the contents would with their right edge flush with the right inner edge of the marquee's content area, and the contents would then slide up to the point where the left edge of the contents are flush with the left inner edge of the marquee's content area.

Once the animation has ended, the user agent is expected to increment the marquee current loop index. If the element is still turned on after this, then the user agent is expected to continue the animation.

The direction attribute has the meanings described in the following table:

direction attribute state Direction of animation Start edge End edge Opposite direction
left ← Right to left Right Left → Left to Right
right → Left to Right Left Right ← Right to left
up ↑ Up (Bottom to Top) Bottom Top ↓ Down (Top to Bottom)
down ↓ Down (Top to Bottom) Top Bottom ↑ Up (Bottom to Top)

In any case, the animation should proceed such that there is a delay given by the marquee scroll interval between each frame, and such that the content moves at most the distance given by the marquee scroll distance with each frame.

When a marquee element has a bgcolor attribute set, the value is expected to be parsed using the rules for parsing a legacy color value, and if that does not return an error, the user agent is expected to treat the attribute as a presentational hint setting the element's 'background-color' property to the resulting color.

The width and height attributes on a marquee element map to the dimension properties 'width' and 'height' on the element respectively.

The intrinsic height of a marquee element with its direction attribute in the up or down states is 200 CSS pixels.

The vspace attribute of a marquee element maps to the dimension properties 'margin-top' and 'margin-bottom' on the element. The hspace attribute of a marquee element maps to the dimension properties 'margin-left' and 'margin-right' on the element.

The 'overflow' property on the marquee element is expected to be ignored; overflow is expected to always be hidden.

15.5.13 The meter element

The meter element is expected to render as an 'inline-block' box with a 'height' of '1em' and a 'width' of '5em', a 'vertical-align' of '-0.2em', and with its contents depicting a gauge.

When the element is wider than it is tall (or square), the depiction is expected to be of a horizontal gauge, with the minimum value on the right if the 'direction' property on this element has a computed value of 'rtl', and on the left otherwise. When the element is taller than it is wide, it is expected to depict a vertical gauge, with the minimum value on the bottom.

User agents are expected to use a presentation consistent with platform conventions for gauges, if any.

Requirements for what must be depicted in the gauge are included in the definition of the meter element.

15.5.14 The progress element

The progress element is expected to render as an 'inline-block' box with a 'height' of '1em' and a 'width' of '10em', and a 'vertical-align' of '-0.2em'.

When the element is wider than it is tall, the element is expected to be depicted as a horizontal progress bar, with the start on the right and the end on the left if the 'direction' property on this element has a computed value of 'rtl', and with the start on the left and the end on the right otherwise. When the element is taller than it is wide, it is expected to be depicted as a vertical progress bar, with the lowest value on the bottom. When the element is square, it is expected to be depicted as a direction-independent progress widget (e.g. a circular progress ring).

User agents are expected to use a presentation consistent with platform conventions for progress bars. In particular, user agents are expected to use different presentations for determinate and indeterminate progress bars. User agents are also expected to vary the presentation based on the dimensions of the element.

For example, on some platforms for showing indeterminate progress there is a "spinner" progress indicator with square dimensions, which could be used when the element is square, and an indeterminate progress bar, which could be used when the element is wide.

Requirements for how to determine if the progress bar is determinate or indeterminate, and what progress a determinate progress bar is to show, are included in the definition of the progress element.

15.5.15 The select element

A select element is either a list box or a drop-down box, depending on its attributes.

A select element whose multiple attribute is present is expected to render as a multi-select list box.

A select element whose multiple attribute is absent, and whose display size is greater than 1, is expected to render as a single-select list box.

When the element renders as a list box, it is expected to render as an 'inline-block' box whose 'height' is the height necessary to contain as many rows for items as given by the element's display size, or four rows if the attribute is absent, and whose 'width' is the width of the select's labels plus the width of a scrollbar.

A select element whose multiple attribute is absent, and whose display size is 1, is expected to render as a one-line drop-down box whose width is the width of the select's labels.

In either case (list box or drop-down box), the element's items are expected to be the element's list of options, with the element's optgroup element children providing headers for groups of options where applicable.

An optgroup element is expected to be rendered by displaying the element's label attribute.

An option element is expected to be rendered by displaying the element's label, indented under its optgroup element if it has one.

The width of the select's labels is the wider of the width necessary to render the widest optgroup, and the width necessary to render the widest option element in the element's list of options (including its indent, if any).

If a select element contains a placeholder label option, the user agent is expected to render that option in a manner that conveys that it is a label, rather than a valid option of the control. This can include preventing the placeholder label option from being explicitly selected by the user. When the placeholder label option's selectedness is true, the control is expected to be displayed in a fashion that indicates that no valid option is currently selected.

User agents are expected to render the labels in a select in such a manner that any alignment remains consistent whether the label is being displayed as part of the page or in a menu control.

15.5.16 The textarea element

The textarea element is expected to render as an 'inline-block' box depicting a multiline text control. If this multiline text control provides a selection, then, when the user changes the current selection, the user agent is expected to queue an element task on the user interaction task source given the textarea element to fire an event named select at the element, with the bubbles attribute initialized to true.

If the element has a cols attribute, and parsing that attribute's value using the rules for parsing non-negative integers doesn't generate an error, then the user agent is expected to use the attribute as a presentational hint for the 'width' property on the element, with the value being the textarea effective width (as defined below). Otherwise, the user agent is expected to act as if it had a user-agent-level style sheet rule setting the 'width' property on the element to the textarea effective width.

The textarea effective width of a textarea element is size×avg + sbw, where size is the element's character width, avg is the average character width of the primary font of the element, in CSS pixels, and sbw is the width of a scrollbar, in CSS pixels. (The element's 'letter-spacing' property does not affect the result.)

If the element has a rows attribute, and parsing that attribute's value using the rules for parsing non-negative integers doesn't generate an error, then the user agent is expected to use the attribute as a presentational hint for the 'height' property on the element, with the value being the textarea effective height (as defined below). Otherwise, the user agent is expected to act as if it had a user-agent-level style sheet rule setting the 'height' property on the element to the textarea effective height.

The textarea effective height of a textarea element is the height in CSS pixels of the number of lines specified the element's character height, plus the height of a scrollbar in CSS pixels.

User agents are expected to apply the 'white-space' CSS property to textarea elements. For historical reasons, if the element has a wrap attribute whose value is an ASCII case-insensitive match for the string "off", then the user agent is expected to treat the attribute as a presentational hint setting the element's 'white-space' property to 'pre'.

15.6 Frames and framesets

User agent are expected to render frameset elements as a box with the height and width of the viewport, with a surface rendered according to the following layout algorithm:

  1. The cols and rows variables are lists of zero or more pairs consisting of a number and a unit, the unit being one of percentage, relative, and absolute.

    Use the rules for parsing a list of dimensions to parse the value of the element's cols attribute, if there is one. Let cols be the result, or an empty list if there is no such attribute.

    Use the rules for parsing a list of dimensions to parse the value of the element's rows attribute, if there is one. Let rows be the result, or an empty list if there is no such attribute.

  2. For any of the entries in cols or rows that have the number zero and the unit relative, change the entry's number to one.

  3. If cols has no entries, then add a single entry consisting of the value 1 and the unit relative to cols.

    If rows has no entries, then add a single entry consisting of the value 1 and the unit relative to rows.

  4. Invoke the algorithm defined below to convert a list of dimensions to a list of pixel values using cols as the input list, and the width of the surface that the frameset is being rendered into, in CSS pixels, as the input dimension. Let sized cols be the resulting list.

    Invoke the algorithm defined below to convert a list of dimensions to a list of pixel values using rows as the input list, and the height of the surface that the frameset is being rendered into, in CSS pixels, as the input dimension. Let sized rows be the resulting list.

  5. Split the surface into a grid of w×h rectangles, where w is the number of entries in sized cols and h is the number of entries in sized rows.

    Size the columns so that each column in the grid is as many CSS pixels wide as the corresponding entry in the sized cols list.

    Size the rows so that each row in the grid is as many CSS pixels high as the corresponding entry in the sized rows list.

  6. Let children be the list of frame and frameset elements that are children of the frameset element for which the algorithm was invoked.

  7. For each row of the grid of rectangles created in the previous step, from top to bottom, run these substeps:

    1. For each rectangle in the row, from left to right, run these substeps:

      1. If there are any elements left in children, take the first element in the list, and assign it to the rectangle.

        If this is a frameset element, then recurse the entire frameset layout algorithm for that frameset element, with the rectangle as the surface.

        Otherwise, it is a frame element; render its nested browsing context, positioned and sized to fit the rectangle.

      2. If there are any elements left in children, remove the first element from children.

  8. If the frameset element has a border, draw an outer set of borders around the rectangles, using the element's frame border color.

    For each rectangle, if there is an element assigned to that rectangle, and that element has a border, draw an inner set of borders around that rectangle, using the element's frame border color.

    For each (visible) border that does not abut a rectangle that is assigned a frame element with a noresize attribute (including rectangles in further nested frameset elements), the user agent is expected to allow the user to move the border, resizing the rectangles within, keeping the proportions of any nested frameset grids.

    A frameset or frame element has a border if the following algorithm returns true:

    1. If the element has a frameborder attribute whose value is not the empty string and whose first character is either a U+0031 DIGIT ONE (1) character, a U+0079 LATIN SMALL LETTER Y character (y), or a U+0059 LATIN CAPITAL LETTER Y character (Y), then return true.

    2. Otherwise, if the element has a frameborder attribute, return false.

    3. Otherwise, if the element has a parent element that is a frameset element, then return true if that element has a border, and false if it does not.

    4. Otherwise, return true.

    The frame border color of a frameset or frame element is the color obtained from the following algorithm:

    1. If the element has a bordercolor attribute, and applying the rules for parsing a legacy color value to that attribute's value does not result in an error, then return the color so obtained.

    2. Otherwise, if the element has a parent element that is a frameset element, then return the frame border color of that element.

    3. Otherwise, return gray.

The algorithm to convert a list of dimensions to a list of pixel values consists of the following steps:

  1. Let input list be the list of numbers and units passed to the algorithm.

    Let output list be a list of numbers the same length as input list, all zero.

    Entries in output list correspond to the entries in input list that have the same position.

  2. Let input dimension be the size passed to the algorithm.

  3. Let count percentage be the number of entries in input list whose unit is percentage.

    Let total percentage be the sum of all the numbers in input list whose unit is percentage.

    Let count relative be the number of entries in input list whose unit is relative.

    Let total relative be the sum of all the numbers in input list whose unit is relative.

    Let count absolute be the number of entries in input list whose unit is absolute.

    Let total absolute be the sum of all the numbers in input list whose unit is absolute.

    Let remaining space be the value of input dimension.

  4. If total absolute is greater than remaining space, then for each entry in input list whose unit is absolute, set the corresponding value in output list to the number of the entry in input list multiplied by remaining space and divided by total absolute. Then, set remaining space to zero.

    Otherwise, for each entry in input list whose unit is absolute, set the corresponding value in output list to the number of the entry in input list. Then, decrement remaining space by total absolute.

  5. If total percentage multiplied by the input dimension and divided by 100 is greater than remaining space, then for each entry in input list whose unit is percentage, set the corresponding value in output list to the number of the entry in input list multiplied by remaining space and divided by total percentage. Then, set remaining space to zero.

    Otherwise, for each entry in input list whose unit is percentage, set the corresponding value in output list to the number of the entry in input list multiplied by the input dimension and divided by 100. Then, decrement remaining space by total percentage multiplied by the input dimension and divided by 100.

  6. For each entry in input list whose unit is relative, set the corresponding value in output list to the number of the entry in input list multiplied by remaining space and divided by total relative.

  7. Return output list.

User agents working with integer values for frame widths (as opposed to user agents that can lay frames out with subpixel accuracy) are expected to distribute the remainder first to the last entry whose unit is relative, then equally (not proportionally) to each entry whose unit is percentage, then equally (not proportionally) to each entry whose unit is absolute, and finally, failing all else, to the last entry.


The contents of a frame element that does not have a frameset parent are expected to be rendered as transparent black; the user agent is expected to not render its nested browsing context in this case, and its nested browsing context is expected to have a viewport with zero width and zero height.

15.7 Interactive media

15.7.1 Links, forms, and navigation

User agents are expected to allow the user to control aspects of hyperlink activation and form submission, such as which browsing context is to be used for the subsequent navigation.

User agents are expected to allow users to discover the destination of hyperlinks and of forms before triggering their navigation.

User agents are expected to inform the user of whether a hyperlink includes hyperlink auditing, and to let them know at a minimum which domains will be contacted as part of such auditing.

User agents may allow users to navigate browsing contexts to the URLs indicated by the cite attributes on q, blockquote, ins, and del elements.

User agents may surface hyperlinks created by link elements in their user interface.

While link elements that create hyperlinks will match the :link or :visited pseudo-classes, will react to clicks if visible, and so forth, this does not extend to any browser interface constructs that expose those same links. Activating a link through the browser's interface, rather than in the page itself, does not trigger click events and the like.

15.7.2 The title attribute

Global_attributes/title

Support in all current engines.

FirefoxYesSafariYesChromeYes
OperaYesEdgeYes
Edge (Legacy)12+Internet ExplorerYes
Firefox AndroidYesSafari iOSYesChrome AndroidYesWebView AndroidYesSamsung InternetYesOpera AndroidYes

User agents are expected to expose the advisory information of elements upon user request, and to make the user aware of the presence of such information.

On interactive graphical systems where the user can use a pointing device, this could take the form of a tooltip. When the user is unable to use a pointing device, then the user agent is expected to make the content available in some other fashion, e.g. by making the element a focusable area and always displaying the advisory information of the currently focused element, or by showing the advisory information of the elements under the user's finger on a touch device as the user pans around the screen.

U+000A LINE FEED (LF) characters are expected to cause line breaks in the tooltip; U+0009 CHARACTER TABULATION (tab) characters are expected to render as a nonzero horizontal shift that lines up the next glyph with the next tab stop, with tab stops occurring at points that are multiples of 8 times the width of a U+0020 SPACE character.

For example, a visual user agent could make elements with a title attribute focusable, and could make any focused element with a title attribute show its tooltip under the element while the element has focus. This would allow a user to tab around the document to find all the advisory text.

As another example, a screen reader could provide an audio cue when reading an element with a tooltip, with an associated key to read the last tooltip for which a cue was played.

15.7.3 Editing hosts

The current text editing caret (i.e. the active range, if it is empty and in an editing host), if any, is expected to act like an inline replaced element with the vertical dimensions of the caret and with zero width for the purposes of the CSS rendering model.

This means that even an empty block can have the caret inside it, and that when the caret is in such an element, it prevents margins from collapsing through the element.

15.7.4 Text rendered in native user interfaces

User agents are expected to honor the Unicode semantics of text that is exposed in user interfaces, for example supporting the bidirectional algorithm in text shown in dialogs, title bars, popup menus, and tooltips. Text from the contents of elements is expected to be rendered in a manner that honors the directionality of the element from which the text was obtained. Text from attributes is expected to be rendered in a manner that honours the directionality of the attribute.

Consider the following markup, which has Hebrew text asking for a programming language, the languages being text for which a left-to-right direction is important given the punctuation in some of their names:

<p dir="rtl" lang="he">
 <label>
  בחר שפת תכנות:
  <select>
   <option dir="ltr">C++</option>
   <option dir="ltr">C#</option>
   <option dir="ltr">FreePascal</option>
   <option dir="ltr">F#</option>
  </select>
 </label>
</p>

If the select element was rendered as a drop down box, a correct rendering would ensure that the punctuation was the same both in the drop down, and in the box showing the current selection.

The directionality of attributes depends on the attribute and on the element's dir attribute, as the following example demonstrates. Consider this markup:

<table>
 <tr>
  <th abbr="(א" dir=ltr>A
  <th abbr="(א" dir=rtl>A
  <th abbr="(א" dir=auto>A
</table>

If the abbr attributes are rendered, e.g. in a tooltip or other user interface, the first will have a left parenthesis (because the direction is 'ltr'), the second will have a right parenthesis (because the direction is 'rtl'), and the third will have a right parenthesis (because the direction is determined from the attribute value to be 'rtl').

However, if instead the attribute was not a directionality-capable attribute, the results would be different:

<table>
 <tr>
  <th data-abbr="(א" dir=ltr>A
  <th data-abbr="(א" dir=rtl>A
  <th data-abbr="(א" dir=auto>A
</table>

In this case, if the user agent were to expose the data-abbr attribute in the user interface (e.g. in a debugging environment), the last case would be rendered with a left parenthesis, because the direction would be determined from the element's contents.

A string provided by a script (e.g. the argument to window.alert()) is expected to be treated as an independent set of one or more bidirectional algorithm paragraphs when displayed, as defined by the bidirectional algorithm, including, for instance, supporting the paragraph-breaking behavior of U+000A LINE FEED (LF) characters. For the purposes of determining the paragraph level of such text in the bidirectional algorithm, this specification does not provide a higher-level override of rules P2 and P3. [BIDI]

When necessary, authors can enforce a particular direction for a given paragraph by starting it with the Unicode U+200E LEFT-TO-RIGHT MARK or U+200F RIGHT-TO-LEFT MARK characters.

Thus, the following script:

alert('\u05DC\u05DE\u05D3 HTML \u05D4\u05D9\u05D5\u05DD!')

...would always result in a message reading "למד LMTH היום!" (not "דמל HTML םויה!"), regardless of the language of the user agent interface or the direction of the page or any of its elements.

For a more complex example, consider the following script:

/* Warning: this script does not handle right-to-left scripts correctly */
var s;
if (s = prompt('What is your name?')) {
  alert(s + '! Ok, Fred, ' + s + ', and Wilma will get the car.');
}

When the user enters "Kitty", the user agent would alert "Kitty! Ok, Fred, Kitty, and Wilma will get the car.". However, if the user enters "لا أفهم", then the bidirectional algorithm will determine that the direction of the paragraph is right-to-left, and so the output will be the following unintended mess: "لا أفهم! derF ,kO, لا أفهم, rac eht teg lliw amliW dna."

To force an alert that starts with user-provided text (or other text of unknown directionality) to render left-to-right, the string can be prefixed with a U+200E LEFT-TO-RIGHT MARK character:

var s;
if (s = prompt('What is your name?')) {
  alert('\u200E' + s + '! Ok, Fred, ' + s + ', and Wilma will get the car.');
}

User agents are expected to allow the user to request the opportunity to obtain a physical form (or a representation of a physical form) of a Document. For example, selecting the option to print a page or convert it to PDF format. [PDF]

When the user actually obtains a physical form (or a representation of a physical form) of a Document, the user agent is expected to create a new rendering of the Document for the print media.

15.9 Unstyled XML documents

HTML user agents may, in certain circumstances, find themselves rendering non-HTML documents that use vocabularies for which they lack any built-in knowledge. This section provides for a way for user agents to handle such documents in a somewhat useful manner.

While a Document is an unstyled document, the user agent is expected to render an unstyled document view.

A Document is an unstyled document while it matches the following conditions:

An unstyled document view is one where the DOM is not rendered according to CSS (which would, since there are no applicable styles in this context, just result in a wall of text), but is instead rendered in a manner that is useful for a developer. This could consist of just showing the Document object's source, maybe with syntax highlighting, or it could consist of displaying just the DOM tree, or simply a message saying that the page is not a styled document.

If a Document stops being an unstyled document, then the conditions above stop applying, and thus a user agent following these requirements will switch to using the regular CSS rendering.

16 废弃的特性

16.1 Obsolete but conforming features

Features listed in this section will trigger warnings in conformance checkers.

Authors should not specify a border attribute on an img element. If the attribute is present, its value must be the string "0". CSS should be used instead.

Authors should not specify a charset attribute on a script element. If the attribute is present, its value must be an ASCII case-insensitive match for "utf-8". (This has no effect in a document that conforms to the requirements elsewhere in this standard of being encoded as UTF-8.)

Authors should not specify a language attribute on a script element. If the attribute is present, its value must be an ASCII case-insensitive match for the string "JavaScript" and either the type attribute must be omitted or its value must be an ASCII case-insensitive match for the string "text/javascript". The attribute should be entirely omitted instead (with the value "JavaScript", it has no effect), or replaced with use of the type attribute.

Authors should not specify a value for the type attribute on script elements that is the empty string or a JavaScript MIME type essence match. Instead, they should omit the attribute, which has the same effect.

Authors should not specify a type attribute on a style element. If the attribute is present, its value must be an ASCII case-insensitive match for "text/css".

Authors should not specify the name attribute on a elements. If the attribute is present, its value must not be the empty string and must neither be equal to the value of any of the IDs in the element's tree other than the element's own ID, if any, nor be equal to the value of any of the other name attributes on a elements in the element's tree. If this attribute is present and the element has an ID, then the attribute's value must be equal to the element's ID. In earlier versions of the language, this attribute was intended as a way to specify possible targets for fragments in URLs. The id attribute should be used instead.

Authors should not, but may despite requirements to the contrary elsewhere in this specification, specify the maxlength and size attributes on input elements whose type attributes are in the Number state. One valid reason for using these attributes regardless is to help legacy user agents that do not support input elements with type="number" to still render the text control with a useful width.

16.1.1 Warnings for obsolete but conforming features

To ease the transition from HTML4 Transitional documents to the language defined in this specification, and to discourage certain features that are only allowed in very few circumstances, conformance checkers must warn the user when the following features are used in a document. These are generally old obsolete features that have no effect, and are allowed only to distinguish between likely mistakes (regular conformance errors) and mere vestigial markup or unusual and discouraged practices (these warnings).

The following features must be categorized as described above:

Conformance checkers must distinguish between pages that have no conformance errors and have none of these obsolete features, and pages that have no conformance errors but do have some of these obsolete features.

For example, a validator could report some pages as "Valid HTML" and others as "Valid HTML with warnings".

16.2 Non-conforming features

Elements in the following list are entirely obsolete, and must not be used by authors:

applet

Use embed or object instead.

acronym

Use abbr instead.

bgsound

Use audio instead.

dir

Use ul instead.

frame
frameset
noframes

Either use iframe and CSS instead, or use server-side includes to generate complete pages with the various invariant parts merged in.

isindex

Use an explicit form and text control combination instead.

keygen

For enterprise device management use cases, use native on-device management capabilities.

For certificate enrollment use cases, use the Web Cryptography API to generate a keypair for the certificate, and then export the certificate and key to allow the user to install them manually. [WEBCRYPTO]

listing

Use pre and code instead.

menuitem

To implement a custom context menu, use script to handle the contextmenu event.

nextid

Use GUIDs instead.

noembed

Use object instead of embed when fallback is necessary.

plaintext

Use the "text/plain" MIME type instead.

rb
rtc

Providing the ruby base directly inside the ruby element or using nested ruby elements is sufficient.

strike

Use del instead if the element is marking an edit, otherwise use s instead.

xmp

Use pre and code instead, and escape "<" and "&" characters as "&lt;" and "&amp;" respectively.

basefont
big
blink
center
font
marquee
multicol
nobr
spacer
tt

Use appropriate elements or CSS instead.

Where the tt element would have been used for marking up keyboard input, consider the kbd element; for variables, consider the var element; for computer code, consider the code element; and for computer output, consider the samp element.

Similarly, if the big element is being used to denote a heading, consider using the h1 element; if it is being used for marking up important passages, consider the strong element; and if it is being used for highlighting text for reference purposes, consider the mark element.

See also the text-level semantics usage summary for more suggestions with examples.


The following attributes are obsolete (though the elements are still part of the language), and must not be used by authors:

charset on a elements
charset on link elements

Use an HTTP `Content-Type` header on the linked resource instead.

charset on script elements (except as noted in the previous section)

Omit the attribute. Both documents and scripts are required to use UTF-8, so it is redundant to specify it on the script element since it inherits from the document.

coords on a elements
shape on a elements

Use area instead of a for image maps.

methods on a elements
methods on link elements

Use the HTTP OPTIONS feature instead.

name on a elements (except as noted in the previous section)
name on embed elements
name on img elements
name on option elements

Use the id attribute instead.

rev on a elements
rev on link elements

Use the rel attribute instead, with an opposite term. (For example, instead of rev="made", use rel="author".)

urn on a elements
urn on link elements

Specify the preferred persistent identifier using the href attribute instead.

accept on form elements

Use the accept attribute directly on the input elements instead.

hreflang on area elements
type on area elements

These attributes do not do anything useful, and for historical reasons there are no corresponding IDL attributes on area elements. Omit them altogether.

nohref on area elements

Omitting the href attribute is sufficient; the nohref attribute is unnecessary. Omit it altogether.

profile on head elements

Unnecessary. Omit it altogether.

version on html elements

Unnecessary. Omit it altogether.

ismap on input elements

Unnecessary. Omit it altogether. All input elements with a type attribute in the Image Button state are processed as server-side image maps.

usemap on input elements

Use img instead of input for image maps.

longdesc on iframe elements
longdesc on img elements

Use a regular a element to link to the description, or (in the case of images) use an image map to provide a link from the image to the image's description.

lowsrc on img elements

Use a progressive JPEG image (given in the src attribute), instead of using two separate images.

target on link elements

Unnecessary. Omit it altogether.

type on menu elements

To implement a custom context menu, use script to handle the contextmenu event. For toolbar menus, omit the attribute.

label on menu elements
contextmenu on all elements
onshow on all elements

To implement a custom context menu, use script to handle the contextmenu event.

scheme on meta elements

Use only one scheme per field, or make the scheme declaration part of the value.

archive on object elements
classid on object elements
code on object elements
codebase on object elements
codetype on object elements

Use the data and type attributes to invoke plugins. To set parameters with these names in particular, the param element can be used.

declare on object elements

Repeat the object element completely each time the resource is to be reused.

standby on object elements

Optimize the linked resource so that it loads quickly or, at least, incrementally.

typemustmatch on object elements

Avoid using object elements with untrusted resources.

type on param elements
valuetype on param elements

Use the name and value attributes without declaring value types.

language on script elements (except as noted in the previous section)

Omit the attribute for JavaScript; for data blocks, use the type attribute instead.

event on script elements
for on script elements

Use DOM events mechanisms to register event listeners. [DOM]

type on style elements (except as noted in the previous section)

Omit the attribute for CSS; for data blocks, use script as the container instead of style.

datapagesize on table elements

Unnecessary. Omit it altogether.

summary on table elements

Use one of the techniques for describing tables given in the table section instead.

abbr on td elements

Use text that begins in an unambiguous and terse manner, and include any more elaborate text after that. The title attribute can also be useful in including more detailed text, so that the cell's contents can be made terse. If it's a heading, use th (which has an abbr attribute).

axis on td and th elements

Use the scope attribute on the relevant th.

scope on td elements

Use th elements for heading cells.

datasrc on a, button, div, frame, iframe, img, input, label, legend, marquee, object, option, select, span, table, and textarea elements
datafld on a, button, div, fieldset, frame, iframe, img, input, label, legend, marquee, object, param, select, span, and textarea elements
dataformatas on button, div, input, label, legend, marquee, object, option, select, span, and table elements

Use script and a mechanism such as XMLHttpRequest to populate the page dynamically. [XHR]

dropzone on all elements

Use script to handle the dragenter and dragover events instead.

alink on body elements
bgcolor on body elements
bottommargin on body elements
leftmargin on body elements
link on body elements
marginheight on body elements
marginwidth on body elements
rightmargin on body elements
text on body elements
topmargin on body elements
vlink on body elements
clear on br elements
align on caption elements
align on col elements
char on col elements
charoff on col elements
valign on col elements
width on col elements
align on div elements
compact on dl elements
align on embed elements
hspace on embed elements
vspace on embed elements
align on hr elements
color on hr elements
noshade on hr elements
size on hr elements
width on hr elements
align on h1h6 elements
align on iframe elements
allowtransparency on iframe elements
frameborder on iframe elements
framespacing on iframe elements
hspace on iframe elements
marginheight on iframe elements
marginwidth on iframe elements
scrolling on iframe elements
vspace on iframe elements
align on input elements
border on input elements
hspace on input elements
vspace on input elements
align on img elements
border on img elements (except as noted in the previous section)
hspace on img elements
vspace on img elements
align on legend elements
type on li elements
compact on menu elements
align on object elements
border on object elements
hspace on object elements
vspace on object elements
compact on ol elements
align on p elements
width on pre elements
align on table elements
bgcolor on table elements
border on table elements
bordercolor on table elements
cellpadding on table elements
cellspacing on table elements
frame on table elements
height on table elements
rules on table elements
width on table elements
align on tbody, thead, and tfoot elements
char on tbody, thead, and tfoot elements
charoff on tbody, thead, and tfoot elements
height on thead, tbody, and tfoot elements
valign on tbody, thead, and tfoot elements
align on td and th elements
bgcolor on td and th elements
char on td and th elements
charoff on td and th elements
height on td and th elements
nowrap on td and th elements
valign on td and th elements
width on td and th elements
align on tr elements
bgcolor on tr elements
char on tr elements
charoff on tr elements
height on tr elements
valign on tr elements
compact on ul elements
type on ul elements
background on body, table, thead, tbody, tfoot, tr, td, and th elements

Use CSS instead.

16.3 Requirements for implementations

16.3.1 The marquee element

The marquee element is a presentational element that animates content. CSS transitions and animations are a more appropriate mechanism. [CSSANIMATIONS] [CSSTRANSITIONS]

The marquee element must implement the HTMLMarqueeElement interface.

[Exposed=Window]
interface HTMLMarqueeElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString behavior;
  [CEReactions] attribute DOMString bgColor;
  [CEReactions] attribute DOMString direction;
  [CEReactions] attribute DOMString height;
  [CEReactions] attribute unsigned long hspace;
  [CEReactions] attribute long loop;
  [CEReactions] attribute unsigned long scrollAmount;
  [CEReactions] attribute unsigned long scrollDelay;
  [CEReactions] attribute boolean trueSpeed;
  [CEReactions] attribute unsigned long vspace;
  [CEReactions] attribute DOMString width;

  attribute EventHandler onbounce;
  attribute EventHandler onfinish;
  attribute EventHandler onstart;

  undefined start();
  undefined stop();
};

A marquee element can be turned on or turned off. When it is created, it is turned on.

When the start() method is called, the marquee element must be turned on.

When the stop() method is called, the marquee element must be turned off.

When a marquee element is created, the user agent must queue an element task on the DOM manipulation task source given the marquee element to fire an event named start at the element.


The behavior content attribute on marquee elements is an enumerated attribute with the following keywords (all non-conforming):

Keyword State
scroll scroll
slide slide
alternate alternate

The missing value default and invalid value default are the scroll state.


The direction content attribute on marquee elements is an enumerated attribute with the following keywords (all non-conforming):

Keyword State
left left
right right
up up
down down

The missing value default and invalid value default are the left state.


The truespeed content attribute on marquee elements is a boolean attribute.


A marquee element has a marquee scroll interval, which is obtained as follows:

  1. If the element has a scrolldelay attribute, and parsing its value using the rules for parsing non-negative integers does not return an error, then let delay be the parsed value. Otherwise, let delay be 85.

  2. If the element does not have a truespeed attribute, and the delay value is less than 60, then let delay be 60 instead.

  3. The marquee scroll interval is delay, interpreted in milliseconds.


A marquee element has a marquee scroll distance, which, if the element has a scrollamount attribute, and parsing its value using the rules for parsing non-negative integers does not return an error, is the parsed value interpreted in CSS pixels, and otherwise is 6 CSS pixels.


A marquee element has a marquee loop count, which, if the element has a loop attribute, and parsing its value using the rules for parsing integers does not return an error or a number less than 1, is the parsed value, and otherwise is −1.

The loop IDL attribute, on getting, must return the element's marquee loop count; and on setting, if the new value is different than the element's marquee loop count and either greater than zero or equal to −1, must set the element's loop content attribute (adding it if necessary) to the valid integer that represents the new value. (Other values are ignored.)

A marquee element also has a marquee current loop index, which is zero when the element is created.

The rendering layer will occasionally increment the marquee current loop index, which must cause the following steps to be run:

  1. If the marquee loop count is −1, then return.

  2. Increment the marquee current loop index by one.

  3. If the marquee current loop index is now equal to or greater than the element's marquee loop count, turn off the marquee element and queue an element task on the DOM manipulation task source given the marquee element to fire an event named finish at the marquee element.

    Otherwise, if the behavior attribute is in the alternate state, then queue an element task on the DOM manipulation task source given the marquee element to fire an event named bounce at the marquee element.

    Otherwise, queue an element task on the DOM manipulation task source given the marquee element to fire an event named start at the marquee element.


The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler content attributes and event handler IDL attributes, by marquee elements:

Event handler Event handler event type
onbounce bounce
onfinish finish
onstart start

The behavior, direction, height, hspace, vspace, and width IDL attributes must reflect the respective content attributes of the same name.

The bgColor IDL attribute must reflect the bgcolor content attribute.

The scrollAmount IDL attribute must reflect the scrollamount content attribute. The default value is 6.

The scrollDelay IDL attribute must reflect the scrolldelay content attribute. The default value is 85.

The trueSpeed IDL attribute must reflect the truespeed content attribute.

16.3.2 Frames

The frameset element acts as the body element in documents that use frames.

The frameset element must implement the HTMLFrameSetElement interface.

[Exposed=Window]
interface HTMLFrameSetElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString cols;
  [CEReactions] attribute DOMString rows;
};
HTMLFrameSetElement includes WindowEventHandlers;

The cols and rows IDL attributes of the frameset element must reflect the respective content attributes of the same name.

The frameset element exposes as event handler content attributes a number of the event handlers of the Window object. It also mirrors their event handler IDL attributes.

The event handlers of the Window object named by the Window-reflecting body element event handler set, exposed on the frameset element, replace the generic event handlers with the same names normally supported by HTML elements.


The frame element has a nested browsing context similar to the iframe element, but rendered within a frameset element.

A frame element is said to be an active frame element when it is in a document.

When a frame element element is created as an active frame element, or becomes an active frame element after not having been one, the user agent must run these steps:

  1. Create a new nested browsing context for element.

  2. Process the frame attributes for element, with initialInsertion set to true.

When a frame element stops being an active frame element, the user agent must discard the element's nested browsing context, and then set the element's nested browsing context to null.

Whenever a frame element with a non-null nested browsing context has its src attribute set, changed, or removed, the user agent must process the frame attributes.

To process the frame attributes for an element element, with an optional boolean initialInsertion:

  1. If initialInsertion is true, then do nothing.

  2. Otherwise, run the otherwise steps for iframe or frame elements given element.

The frame element potentially delays the load event.

The frame element must implement the HTMLFrameElement interface.

[Exposed=Window]
interface HTMLFrameElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString scrolling;
  [CEReactions] attribute USVString src;
  [CEReactions] attribute DOMString frameBorder;
  [CEReactions] attribute USVString longDesc;
  [CEReactions] attribute boolean noResize;
  readonly attribute Document? contentDocument;
  readonly attribute WindowProxy? contentWindow;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString marginHeight;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString marginWidth;
};

The name, scrolling, and src IDL attributes of the frame element must reflect the respective content attributes of the same name. For the purposes of reflection, the frame element's src content attribute is defined as containing a URL.

The frameBorder IDL attribute of the frame element must reflect the element's frameborder content attribute.

The longDesc IDL attribute of the frame element must reflect the element's longdesc content attribute, which for the purposes of reflection is defined as containing a URL.

The noResize IDL attribute of the frame element must reflect the element's noresize content attribute.

The contentDocument IDL attribute, on getting, must return the frame element's content document.

The contentWindow IDL attribute must return the WindowProxy object of the frame element's nested browsing context, if the element's nested browsing context is non-null, or return null otherwise.

The marginHeight IDL attribute of the frame element must reflect the element's marginheight content attribute.

The marginWidth IDL attribute of the frame element must reflect the element's marginwidth content attribute.

16.3.3 Other elements, attributes and APIs

User agents must treat acronym elements in a manner equivalent to abbr elements in terms of semantics and for purposes of rendering.


partial interface HTMLAnchorElement {
  [CEReactions] attribute DOMString coords;
  [CEReactions] attribute DOMString charset;
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute DOMString rev;
  [CEReactions] attribute DOMString shape;
};

The coords, charset, name, rev, and shape IDL attributes of the a element must reflect the respective content attributes of the same name.


partial interface HTMLAreaElement {
  [CEReactions] attribute boolean noHref;
};

The noHref IDL attribute of the area element must reflect the element's nohref content attribute.


partial interface HTMLBodyElement {
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString text;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString link;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString vLink;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString aLink;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString bgColor;
  [CEReactions] attribute DOMString background;
};

The text IDL attribute of the body element must reflect the element's text content attribute.

The link IDL attribute of the body element must reflect the element's link content attribute.

The aLink IDL attribute of the body element must reflect the element's alink content attribute.

The vLink IDL attribute of the body element must reflect the element's vlink content attribute.

The bgColor IDL attribute of the body element must reflect the element's bgcolor content attribute.

The background IDL attribute of the body element must reflect the element's background content attribute. (The background content is not defined to contain a URL, despite rules regarding its handling in the rendering section above.)


partial interface HTMLBRElement {
  [CEReactions] attribute DOMString clear;
};

The clear IDL attribute of the br element must reflect the content attribute of the same name.


partial interface HTMLTableCaptionElement {
  [CEReactions] attribute DOMString align;
};

The align IDL attribute of the caption element must reflect the content attribute of the same name.


partial interface HTMLTableColElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString ch;
  [CEReactions] attribute DOMString chOff;
  [CEReactions] attribute DOMString vAlign;
  [CEReactions] attribute DOMString width;
};

The align and width IDL attributes of the col element must reflect the respective content attributes of the same name.

The ch IDL attribute of the col element must reflect the element's char content attribute.

The chOff IDL attribute of the col element must reflect the element's charoff content attribute.

The vAlign IDL attribute of the col element must reflect the element's valign content attribute.


User agents must treat dir elements in a manner equivalent to ul elements in terms of semantics and for purposes of rendering.

The dir element must implement the HTMLDirectoryElement interface.

[Exposed=Window]
interface HTMLDirectoryElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute boolean compact;
};

The compact IDL attribute of the dir element must reflect the content attribute of the same name.


partial interface HTMLDivElement {
  [CEReactions] attribute DOMString align;
};

The align IDL attribute of the div element must reflect the content attribute of the same name.


partial interface HTMLDListElement {
  [CEReactions] attribute boolean compact;
};

The compact IDL attribute of the dl element must reflect the content attribute of the same name.


partial interface HTMLEmbedElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString name;
};

The name and align IDL attributes of the embed element must reflect the respective content attributes of the same name.


The font element must implement the HTMLFontElement interface.

[Exposed=Window]
interface HTMLFontElement : HTMLElement {
  [HTMLConstructor] constructor();

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString color;
  [CEReactions] attribute DOMString face;
  [CEReactions] attribute DOMString size; 
};

The color, face, and size IDL attributes of the font element must reflect the respective content attributes of the same name.


partial interface HTMLHeadingElement {
  [CEReactions] attribute DOMString align;
};

The align IDL attribute of the h1h6 elements must reflect the content attribute of the same name.


The profile IDL attribute on head elements (with the HTMLHeadElement interface) is intentionally omitted. Unless so required by another applicable specification, implementations would therefore not support this attribute. (It is mentioned here as it was defined in a previous version of DOM.)


partial interface HTMLHRElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString color;
  [CEReactions] attribute boolean noShade;
  [CEReactions] attribute DOMString size;
  [CEReactions] attribute DOMString width;
};

The align, color, size, and width IDL attributes of the hr element must reflect the respective content attributes of the same name.

The noShade IDL attribute of the hr element must reflect the element's noshade content attribute.


partial interface HTMLHtmlElement {
  [CEReactions] attribute DOMString version;
};

The version IDL attribute of the html element must reflect the content attribute of the same name.


partial interface HTMLIFrameElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString scrolling;
  [CEReactions] attribute DOMString frameBorder;
  [CEReactions] attribute USVString longDesc;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString marginHeight;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString marginWidth;
};

The align and scrolling IDL attributes of the iframe element must reflect the respective content attributes of the same name.

The frameBorder IDL attribute of the iframe element must reflect the element's frameborder content attribute.

The longDesc IDL attribute of the iframe element must reflect the element's longdesc content attribute, which for the purposes of reflection is defined as containing a URL.

The marginHeight IDL attribute of the iframe element must reflect the element's marginheight content attribute.

The marginWidth IDL attribute of the iframe element must reflect the element's marginwidth content attribute.


partial interface HTMLImageElement {
  [CEReactions] attribute DOMString name;
  [CEReactions] attribute USVString lowsrc;
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute unsigned long hspace;
  [CEReactions] attribute unsigned long vspace;
  [CEReactions] attribute USVString longDesc;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString border;
};

The name, align, border, hspace, and vspace IDL attributes of the img element must reflect the respective content attributes of the same name.

The longDesc IDL attribute of the img element must reflect the element's longdesc content attribute, which for the purposes of reflection is defined as containing a URL.

The lowsrc IDL attribute of the img element must reflect the element's lowsrc content attribute, which for the purposes of reflection is defined as containing a URL.


partial interface HTMLInputElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString useMap;
};

The align IDL attribute of the input element must reflect the content attribute of the same name.

The useMap IDL attribute of the input element must reflect the element's usemap content attribute.


partial interface HTMLLegendElement {
  [CEReactions] attribute DOMString align;
};

The align IDL attribute of the legend element must reflect the content attribute of the same name.


partial interface HTMLLIElement {
  [CEReactions] attribute DOMString type;
};

The type IDL attribute of the li element must reflect the content attribute of the same name.


partial interface HTMLLinkElement {
  [CEReactions] attribute DOMString charset;
  [CEReactions] attribute DOMString rev;
  [CEReactions] attribute DOMString target;
};

The charset, rev, and target IDL attributes of the link element must reflect the respective content attributes of the same name.


User agents must treat listing elements in a manner equivalent to pre elements in terms of semantics and for purposes of rendering.


partial interface HTMLMenuElement {
  [CEReactions] attribute boolean compact;
};

The compact IDL attribute of the menu element must reflect the content attribute of the same name.


partial interface HTMLMetaElement {
  [CEReactions] attribute DOMString scheme;
};

User agents may treat the scheme content attribute on the meta element as an extension of the element's name content attribute when processing a meta element with a name attribute whose value is one that the user agent recognizes as supporting the scheme attribute.

User agents are encouraged to ignore the scheme attribute and instead process the value given to the metadata name as if it had been specified for each expected value of the scheme attribute.

For example, if the user agent acts on meta elements with name attributes having the value "eGMS.subject.keyword", and knows that the scheme attribute is used with this metadata name, then it could take the scheme attribute into account, acting as if it was an extension of the name attribute. Thus the following two meta elements could be treated as two elements giving values for two different metadata names, one consisting of a combination of "eGMS.subject.keyword" and "LGCL", and the other consisting of a combination of "eGMS.subject.keyword" and "ORLY":

<!-- this markup is invalid -->
<meta name="eGMS.subject.keyword" scheme="LGCL" content="Abandoned vehicles">
<meta name="eGMS.subject.keyword" scheme="ORLY" content="Mah car: kthxbye">

The suggested processing of this markup, however, would be equivalent to the following:

<meta name="eGMS.subject.keyword" content="Abandoned vehicles">
<meta name="eGMS.subject.keyword" content="Mah car: kthxbye">

The scheme IDL attribute of the meta element must reflect the content attribute of the same name.


partial interface HTMLObjectElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString archive;
  [CEReactions] attribute DOMString code;
  [CEReactions] attribute boolean declare;
  [CEReactions] attribute unsigned long hspace;
  [CEReactions] attribute DOMString standby;
  [CEReactions] attribute unsigned long vspace;
  [CEReactions] attribute DOMString codeBase;
  [CEReactions] attribute DOMString codeType;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString border;
};

The align, archive, border, code, declare, hspace, standby, and vspace IDL attributes of the object element must reflect the respective content attributes of the same name.

The codeBase IDL attribute of the object element must reflect the element's codebase content attribute, which for the purposes of reflection is defined as containing a URL.

The codeType IDL attribute of the object element must reflect the element's codetype content attribute.


partial interface HTMLOListElement {
  [CEReactions] attribute boolean compact;
};

The compact IDL attribute of the ol element must reflect the content attribute of the same name.


partial interface HTMLParagraphElement {
  [CEReactions] attribute DOMString align;
};

The align IDL attribute of the p element must reflect the content attribute of the same name.


partial interface HTMLParamElement {
  [CEReactions] attribute DOMString type;
  [CEReactions] attribute DOMString valueType;
};

The type IDL attribute of the param element must reflect the content attribute of the same name.

The valueType IDL attribute of the param element must reflect the element's valuetype content attribute.


User agents must treat plaintext elements in a manner equivalent to pre elements in terms of semantics and for purposes of rendering. (The parser has special behavior for this element, though.)


partial interface HTMLPreElement {
  [CEReactions] attribute long width;
};

The width IDL attribute of the pre element must reflect the content attribute of the same name.


partial interface HTMLStyleElement {
  [CEReactions] attribute DOMString type;
};

The type IDL attribute of the style element must reflect the element's type content attribute.


partial interface HTMLScriptElement {
  [CEReactions] attribute DOMString charset;
  [CEReactions] attribute DOMString event;
  [CEReactions] attribute DOMString htmlFor;
};

The charset and event IDL attributes of the script element must reflect the respective content attributes of the same name.

The htmlFor IDL attribute of the script element must reflect the element's for content attribute.


partial interface HTMLTableElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString border;
  [CEReactions] attribute DOMString frame;
  [CEReactions] attribute DOMString rules;
  [CEReactions] attribute DOMString summary;
  [CEReactions] attribute DOMString width;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString bgColor;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString cellPadding;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString cellSpacing;
};

The align, border, frame, summary, rules, and width, IDL attributes of the table element must reflect the respective content attributes of the same name.

The bgColor IDL attribute of the table element must reflect the element's bgcolor content attribute.

The cellPadding IDL attribute of the table element must reflect the element's cellpadding content attribute.

The cellSpacing IDL attribute of the table element must reflect the element's cellspacing content attribute.


partial interface HTMLTableSectionElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString ch;
  [CEReactions] attribute DOMString chOff;
  [CEReactions] attribute DOMString vAlign;
};

The align IDL attribute of the tbody, thead, and tfoot elements must reflect the content attribute of the same name.

The ch IDL attribute of the tbody, thead, and tfoot elements must reflect the elements' char content attributes.

The chOff IDL attribute of the tbody, thead, and tfoot elements must reflect the elements' charoff content attributes.

The vAlign IDL attribute of the tbody, thead, and tfoot element must reflect the elements' valign content attributes.


partial interface HTMLTableCellElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString axis;
  [CEReactions] attribute DOMString height;
  [CEReactions] attribute DOMString width;

  [CEReactions] attribute DOMString ch;
  [CEReactions] attribute DOMString chOff;
  [CEReactions] attribute boolean noWrap;
  [CEReactions] attribute DOMString vAlign;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString bgColor;
};

The align, axis, height, and width IDL attributes of the td and th elements must reflect the respective content attributes of the same name.

The ch IDL attribute of the td and th elements must reflect the elements' char content attributes.

The chOff IDL attribute of the td and th elements must reflect the elements' charoff content attributes.

The noWrap IDL attribute of the td and th elements must reflect the elements' nowrap content attributes.

The vAlign IDL attribute of the td and th elements must reflect the elements' valign content attributes.

The bgColor IDL attribute of the td and th elements must reflect the elements' bgcolor content attributes.


partial interface HTMLTableRowElement {
  [CEReactions] attribute DOMString align;
  [CEReactions] attribute DOMString ch;
  [CEReactions] attribute DOMString chOff;
  [CEReactions] attribute DOMString vAlign;

  [CEReactions] attribute [LegacyNullToEmptyString] DOMString bgColor;
};

The align IDL attribute of the tr element must reflect the content attribute of the same name.

The ch IDL attribute of the tr element must reflect the element's char content attribute.

The chOff IDL attribute of the tr element must reflect the element's charoff content attribute.

The vAlign IDL attribute of the tr element must reflect the element's valign content attribute.

The bgColor IDL attribute of the tr element must reflect the element's bgcolor content attribute.


partial interface HTMLUListElement {
  [CEReactions] attribute boolean compact;
  [CEReactions] attribute DOMString type;
};

The compact and type IDL attributes of the ul element must reflect the respective content attributes of the same name.


User agents must treat xmp elements in a manner equivalent to pre elements in terms of semantics and for purposes of rendering. (The parser has special behavior for this element though.)


partial interface Document {
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString fgColor;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString linkColor;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString vlinkColor;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString alinkColor;
  [CEReactions] attribute [LegacyNullToEmptyString] DOMString bgColor;

  [SameObject] readonly attribute HTMLCollection anchors;
  [SameObject] readonly attribute HTMLCollection applets;

  undefined clear();
  undefined captureEvents();
  undefined releaseEvents();

  [SameObject] readonly attribute HTMLAllCollection all;
};

The attributes of the Document object listed in the first column of the following table must reflect the content attribute on the body element with the name given in the corresponding cell in the second column on the same row, if the body element is a body element (as opposed to a frameset element). When there is no body element or if it is a frameset element, the attributes must instead return the empty string on getting and do nothing on setting.

IDL attribute Content attribute
fgColor text
linkColor link
vlinkColor vlink
alinkColor alink
bgColor bgcolor

The anchors attribute must return an HTMLCollection rooted at the Document node, whose filter matches only a elements with name attributes.

The applets attribute must return an HTMLCollection rooted at the Document node, whose filter matches nothing. (It exists for historical reasons.)

The clear(), captureEvents(), and releaseEvents() methods must do nothing.


The all attribute must return an HTMLAllCollection rooted at the Document node, whose filter matches all elements.


partial interface Window {
  undefined captureEvents();
  undefined releaseEvents();

  [Replaceable, SameObject] readonly attribute External external;
};

The captureEvents() and releaseEvents() methods must do nothing.

The external attribute of the Window interface must return an instance of the External interface:

[Exposed=Window]
interface External {
  undefined AddSearchProvider();
  undefined IsSearchProviderInstalled();
};

The AddSearchProvider() and IsSearchProviderInstalled() methods must do nothing.

17 IANA 注意事项

17.1 text/html

This registration is for community review and will be submitted to the IESG for review, approval, and registration with IANA.

Type name:
text
Subtype name:
html
Required parameters:
No required parameters
Optional parameters:
charset

The charset parameter may be provided to specify the document's character encoding, overriding any character encoding declarations in the document other than a Byte Order Mark (BOM). The parameter's value must be one of the labels of the character encoding used to serialize the file. [ENCODING]

Encoding considerations:
8bit (see the section on character encoding declarations)
Security considerations:

Entire novels have been written about the security considerations that apply to HTML documents. Many are listed in this document, to which the reader is referred for more details. Some general concerns bear mentioning here, however:

HTML is scripted language, and has a large number of APIs (some of which are described in this document). Script can expose the user to potential risks of information leakage, credential leakage, cross-site scripting attacks, cross-site request forgeries, and a host of other problems. While the designs in this specification are intended to be safe if implemented correctly, a full implementation is a massive undertaking and, as with any software, user agents are likely to have security bugs.

Even without scripting, there are specific features in HTML which, for historical reasons, are required for broad compatibility with legacy content but that expose the user to unfortunate security problems. In particular, the img element can be used in conjunction with some other features as a way to effect a port scan from the user's location on the Internet. This can expose local network topologies that the attacker would otherwise not be able to determine.

HTML relies on a compartmentalization scheme sometimes known as the same-origin policy. An origin in most cases consists of all the pages served from the same host, on the same port, using the same protocol.

It is critical, therefore, to ensure that any untrusted content that forms part of a site be hosted on a different origin than any sensitive content on that site. Untrusted content can easily spoof any other page on the same origin, read data from that origin, cause scripts in that origin to execute, submit forms to and from that origin even if they are protected from cross-site request forgery attacks by unique tokens, and make use of any third-party resources exposed to or rights granted to that origin.

Interoperability considerations:
Rules for processing both conforming and non-conforming content are defined in this specification.
Published specification:
This document is the relevant specification. Labeling a resource with the text/html type asserts that the resource is an HTML document using the HTML syntax.
Applications that use this media type:
Web browsers, tools for processing Web content, HTML authoring tools, search engines, validators.
Additional information:
Magic number(s):
No sequence of bytes can uniquely identify an HTML document. More information on detecting HTML documents is available in the WHATWG MIME Sniffing standard. [MIMESNIFF]
File extension(s):
"html" and "htm" are commonly, but certainly not exclusively, used as the extension for HTML documents.
Macintosh file type code(s):
TEXT
Person & email address to contact for further information:
Ian Hickson <ian@hixie.ch>
Intended usage:
Common
Restrictions on usage:
No restrictions apply.
Author:
Ian Hickson <ian@hixie.ch>
Change controller:
W3C

Fragments used with text/html resources either refer to the indicated part of the document or provide state information for in-page scripts.

17.2 multipart/x-mixed-replace

这个注册用于社区评审,之后会提交给 IESG 评审通过,通过 IANA 注册。

类型名:
multipart
子类型名:
x-mixed-replace
必选参数:
可选参数:
编码注意事项:
binary
安全注意事项:
multipart/x-mixed-replace 的子资源可能是任意类型,包括 有明显的安全性问题的资源,比如 text/html
可互操作性注意事项:
已发布规范:
本规范描述了 Web 浏览器的处理规则。 产生这一类型资源的一致性要求同 multipart/mixed[RFC2046]
使用该媒体类型的应用:
这个类型用于由 Web 服务器产生的资源,由 Web 浏览器读取。
更多信息:
神奇数字:
不存在可以标识 multipart/x-mixed-replace 资源的字节序列。
文件扩展名:
该类型没有特定的文件扩展名。
Mac 文件类型码:
该类型没有推荐的 Mac 文件类型码。
更多信息请联系的人和电子邮件地址:
Ian Hickson <ian@hixie.ch>
用途:
通用
使用限制:
没有限制。
作者:
Ian Hickson <ian@hixie.ch>
变更控制:
W3C

multipart/x-mixed-replace 资源一起使用的 Fragments 的语义: 每个 body 部分适用那个 body 部分使用的类型的定义。

17.3 application/xhtml+xml

这个注册用于社区评审,之后会提交给 IESG 评审通过,通过 IANA 注册。

类型名:
application
子类型名:
xhtml+xml
必选参数:
application/xml [RFC7303]
可选参数:
application/xml [RFC7303]
编码注意事项:
application/xml [RFC7303]
安全注意事项:
application/xml [RFC7303]
可互操作性注意事项:
application/xml [RFC7303]
已发布规范:
将资源标记为 application/xhtml+xml 类型断言了 该资源是一个 XML 文档,且可能有一个 HTML 命名空间文档元素。 因此,相关标准是 XML 规范,XML 规范中的 Namespaces,以及本规范。 [XML] [XMLNS]
使用该媒体类型的应用:
application/xml [RFC7303]
更多信息:
神奇数字:
application/xml [RFC7303]
文件扩展名:
有一个 HTML 命名空间文档元素 的 XML 资源 有时候用 "xhtml" 和 "xht" 扩展名。
Mac 文件类型码:
TEXT
更多信息请联系的人和电子邮件地址:
Ian Hickson <ian@hixie.ch>
用途:
通用
使用限制:
没有限制。
作者:
Ian Hickson <ian@hixie.ch>
变更控制:
W3C

application/xhtml+xml 资源一起使用的 Fragments 的语义同 XML MIME type[RFC7303]

17.4 text/cache-manifest

这个注册用于社区评审,之后会提交给 IESG 评审通过,通过 IANA 注册。

类型名:
text
子类型名:
cache-manifest
必选参数:
可选参数:
charset

可以提供 charset 参数。 该参数的值必须是 "utf-8"。 该参数没有意义;只是为了与遗留服务器兼容。

编码注意事项:
8bit (总是 UTF-8)
安全注意事项:

Cache 清单自己不会直接引起风险,除非其中包含了敏感信息。 但是要求实现方基于缓存清单填充缓存时遵循特定的规则, 来确保遵守了那些基于域的限制。 没有正确地实现这些规则可能导致信息泄露,跨站脚本攻击,以及类似的事情。

可互操作性注意事项:
无论是符合规范的内容还是不合规范的内容,处理规则都定义在本规范中。
已发布规范:
本文档就是相关规范。
使用该媒体类型的应用:
Web 浏览器。
更多信息:
神奇数字:
Cache 清单以字符串 "CACHE MANIFEST" 开始, 紧接着一个 U+0020 SPACE 字符,一个 U+0009 CHARACTER TABULATION (tab) 字符, 一个 U+000A LINE FEED (LF) 字符,或一个 U+000D CARRIAGE RETURN (CR) 字符。
文件扩展名:
"appcache"
Mac 文件类型码:
该类型没有推荐的 Mac 文件类型码。
更多信息请联系的人和电子邮件地址:
Ian Hickson <ian@hixie.ch>
用途:
通用
使用限制:
没有限制。
作者:
Ian Hickson <ian@hixie.ch>
变更控制:
W3C

Fragmentstext/cache-manifest 资源没有语义。

17.5 text/ping

This registration is for community review and will be submitted to the IESG for review, approval, and registration with IANA.

Type name:
text
Subtype name:
ping
Required parameters:
No parameters
Optional parameters:
charset

The charset parameter may be provided. The parameter's value must be "utf-8". This parameter serves no purpose; it is only allowed for compatibility with legacy servers.

Encoding considerations:
Not applicable.
Security considerations:

If used exclusively in the fashion described in the context of hyperlink auditing, this type introduces no new security concerns.

Interoperability considerations:
Rules applicable to this type are defined in this specification.
Published specification:
This document is the relevant specification.
Applications that use this media type:
Web browsers.
Additional information:
Magic number(s):
text/ping resources always consist of the four bytes 0x50 0x49 0x4E 0x47 (`PING`).
File extension(s):
No specific file extension is recommended for this type.
Macintosh file type code(s):
No specific Macintosh file type codes are recommended for this type.
Person & email address to contact for further information:
Ian Hickson <ian@hixie.ch>
Intended usage:
Common
Restrictions on usage:
Only intended for use with HTTP POST requests generated as part of a web browser's processing of the ping attribute.
Author:
Ian Hickson <ian@hixie.ch>
Change controller:
W3C

Fragments have no meaning with text/ping resources.

17.6 application/microdata+json

这个注册用于社区评审,之后会提交给 IESG 评审通过,通过 IANA 注册。

类型名:
application
子类型名:
microdata+json
必选参数:
application/json [JSON]
可选参数:
application/json [JSON]
编码注意事项:
8bit (总是 UTF-8)
安全注意事项:
application/json [JSON]
可互操作性注意事项:
application/json [JSON]
已发布规范:
将资源标记为 application/microdata+json 类型断言了 该资源是一个 JSON 文本,包含一个只有一个 "items" 属性的对象,这个属性由一个数组组成,每个都是一个对象。 该对象有一个 "id" 属性,其值为字符串; 有一个 "type" 属性,其值为字符串; 有一个 "properties" 属性,其属性值为对象或字符串构成的数组, 其中的对象与上述 "items" 属性的格式一致。 因此,相关规范是 JSON 规范和本规范。 [JSON]
使用该媒体类型的应用:

传输用于 HTML 的元数据特性的数据的那些应用。尤其是用于拖放操作的那类应用。

更多信息:
神奇数字:
application/json [JSON]
文件扩展名:
application/json [JSON]
Mac 文件类型码:
application/json [JSON]
更多信息请联系的人和电子邮件地址:
Ian Hickson <ian@hixie.ch>
用途:
通用
使用限制:
没有限制。
作者:
Ian Hickson <ian@hixie.ch>
变更控制:
W3C

application/microdata+json 资源一起使用的 Fragments 的语义同 application/json(也就是说写这篇文档时还没有额外的语义)。 [JSON]

17.7 text/event-stream

This registration is for community review and will be submitted to the IESG for review, approval, and registration with IANA.

Type name:
text
Subtype name:
event-stream
Required parameters:
No parameters
Optional parameters:
charset

The charset parameter may be provided. The parameter's value must be "utf-8". This parameter serves no purpose; it is only allowed for compatibility with legacy servers.

Encoding considerations:
8bit (always UTF-8)
Security considerations:

An event stream from an origin distinct from the origin of the content consuming the event stream can result in information leakage. To avoid this, user agents are required to apply CORS semantics. [FETCH]

Event streams can overwhelm a user agent; a user agent is expected to apply suitable restrictions to avoid depleting local resources because of an overabundance of information from an event stream.

Servers can be overwhelmed if a situation develops in which the server is causing clients to reconnect rapidly. Servers should use a 5xx status code to indicate capacity problems, as this will prevent conforming clients from reconnecting automatically.

Interoperability considerations:
Rules for processing both conforming and non-conforming content are defined in this specification.
Published specification:
This document is the relevant specification.
Applications that use this media type:
Web browsers and tools using web services.
Additional information:
Magic number(s):
No sequence of bytes can uniquely identify an event stream.
File extension(s):
No specific file extensions are recommended for this type.
Macintosh file type code(s):
No specific Macintosh file type codes are recommended for this type.
Person & email address to contact for further information:
Ian Hickson <ian@hixie.ch>
Intended usage:
Common
Restrictions on usage:
This format is only expected to be used by dynamic open-ended streams served using HTTP or a similar protocol. Finite resources are not expected to be labeled with this type.
Author:
Ian Hickson <ian@hixie.ch>
Change controller:
W3C

Fragments have no meaning with text/event-stream resources.

17.8 `Cross-Origin-Embedder-Policy`

This section describes a header for registration in the Permanent Message Header Field Registry. [RFC3864]

Header field name:
Cross-Origin-Embedder-Policy
Applicable protocol:
http
Status:
standard
Author/Change controller:
WHATWG
Specification document(s):
This document is the relevant specification.
Related information:
None.

17.9 `Cross-Origin-Embedder-Policy-Report-Only`

This section describes a header for registration in the Permanent Message Header Field Registry. [RFC3864]

Header field name:
Cross-Origin-Embedder-Policy-Report-Only
Applicable protocol:
http
Status:
standard
Author/Change controller:
WHATWG
Specification document(s):
This document is the relevant specification.
Related information:
None.

17.10 `Cross-Origin-Opener-Policy`

This section describes a header for registration in the Permanent Message Header Field Registry. [RFC3864]

Header field name:
Cross-Origin-Opener-Policy
Applicable protocol:
http
Status:
standard
Author/Change controller:
WHATWG
Specification document(s):
This document is the relevant specification.
Related information:
None.

17.11 `Origin-Isolation`

This section describes a header for registration in the Permanent Message Header Field Registry. [RFC3864]

Header field name:
Origin-Isolation
Applicable protocol:
http
Status:
standard
Author/Change controller:
WHATWG
Specification document(s):
This document is the relevant specification.
Related information:
None.

17.12 `Ping-From`

本小节描述了 Permanent Message Header Field Registry 中的一个头部注册项。 [RFC3864]

头部字段名:
Ping-From
适用协议:
http
状态:
标准
作者/变更控制:
W3C
规范文档:
本文档就是相关规范。
相关信息:

17.13 `Ping-To`

本小节描述了 Permanent Message Header Field Registry 中的一个头部注册项。 [RFC3864]

头部字段名:
Ping-To
适用协议:
http
状态:
标准
作者/变更控制:
W3C
规范文档:
本文档就是相关规范。
相关信息:

17.14 `Refresh`

This section describes a header for registration in the Permanent Message Header Field Registry. [RFC3864]

Header field name:
Refresh
Applicable protocol:
http
Status:
standard
Author/Change controller:
WHATWG
Specification document(s):
This document is the relevant specification.
Related information:
None.

17.15 `Last-Event-ID`

本小节描述了 Permanent Message Header Field Registry 中的一个头部注册项。 [RFC3864]

头部字段名:
Last-Event-ID
适用协议:
http
状态:
标准
作者/变更控制:
W3C
规范文档:
本文档就是相关规范。
相关信息:

17.16 `X-Frame-Options`

This section describes a header for registration in the Permanent Message Header Field Registry. [RFC3864]

Header field name:
X-Frame-Options
Applicable protocol:
http
Status:
standard
Author/Change controller:
WHATWG
Specification document(s):
This document is the relevant specification.
Related information:
None.

17.17 web+ scheme prefix

This section describes a convention for use with the IANA URI scheme registry. It does not itself register a specific scheme. [RFC7595]

Scheme name:
Schemes starting with the four characters "web+" followed by one or more letters in the range a-z.
Status:
Permanent
Scheme syntax:
Scheme-specific.
Scheme semantics:
Scheme-specific.
Encoding considerations:
All "web+" schemes should use UTF-8 encodings where relevant.
Applications/protocols that use this scheme name:
Scheme-specific.
Interoperability considerations:
The scheme is expected to be used in the context of web applications.
Security considerations:
Any web page is able to register a handler for all "web+" schemes. As such, these schemes must not be used for features intended to be core platform features (e.g. network transfer protocols like HTTP or FTP). Similarly, such schemes must not store confidential information in their URLs, such as usernames, passwords, personal information, or confidential project names.
Contact:
Ian Hickson <ian@hixie.ch>
Change controller:
Ian Hickson <ian@hixie.ch>
References:
Custom scheme handlers, HTML Living Standard: https://html.spec.whatwg.org/#custom-handlers

索引

以下章节只涵盖合规的元素和特性。

Elements

This section is non-normative.

List of elements
Element Description Categories Parents† Children Attributes Interface
aHyperlinkflow; phrasing*; interactive; palpablephrasingtransparent*globals; href; target; download; ping; rel; hreflang; type; referrerpolicyHTMLAnchorElement
abbrAbbreviationflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
addressContact information for a page or article elementflow; palpableflowflow*globalsHTMLElement
areaHyperlink or dead area on an image mapflow; phrasingphrasing*emptyglobals; alt; coords; shape; href; target; download; ping; rel; referrerpolicyHTMLAreaElement
articleSelf-contained syndicatable or reusable compositionflow; sectioning; palpableflowflowglobalsHTMLElement
asideSidebar for tangentially related contentflow; sectioning; palpableflowflowglobalsHTMLElement
audioAudio playerflow; phrasing; embedded; interactive; palpable*phrasingsource*; track*; transparent*globals; src; crossorigin; preload; autoplay; loop; muted; controlsHTMLAudioElement
bKeywordsflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
baseBase URL and default target browsing context for hyperlinks and formsmetadataheademptyglobals; href; targetHTMLBaseElement
bdiText directionality isolationflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
bdoText directionality formattingflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
blockquoteA section quoted from another sourceflow; sectioning root; palpableflowflowglobals; citeHTMLQuoteElement
bodyDocument bodysectioning roothtmlflowglobals; onafterprint; onbeforeprint; onbeforeunload; onhashchange; onlanguagechange; onmessage; onmessageerror; onoffline; ononline; onpagehide; onpageshow; onpopstate; onrejectionhandled; onstorage; onunhandledrejection; onunloadHTMLBodyElement
brLine break, e.g. in poem or postal addressflow; phrasingphrasingemptyglobalsHTMLBRElement
buttonButton controlflow; phrasing; interactive; listed; labelable; submittable; form-associated; palpablephrasingphrasing*globals; disabled; form; formaction; formenctype; formmethod; formnovalidate; formtarget; name; type; valueHTMLButtonElement
canvasScriptable bitmap canvasflow; phrasing; embedded; palpablephrasingtransparentglobals; width; heightHTMLCanvasElement
captionTable captionnonetableflow*globalsHTMLTableCaptionElement
citeTitle of a workflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
codeComputer codeflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
colTable columnnonecolgroupemptyglobals; spanHTMLTableColElement
colgroupGroup of columns in a tablenonetablecol*; template*globals; spanHTMLTableColElement
dataMachine-readable equivalentflow; phrasing; palpablephrasingphrasingglobals; valueHTMLDataElement
datalistContainer for options for combo box controlflow; phrasingphrasingphrasing*; option*; script-supporting elements*globalsHTMLDataListElement
ddContent for corresponding dt element(s)nonedl; div*flowglobalsHTMLElement
delA removal from the documentflow; phrasing*phrasingtransparentglobals; cite; datetimeHTMLModElement
detailsDisclosure control for hiding detailsflow; sectioning root; interactive; palpableflowsummary*; flowglobals; openHTMLDetailsElement
dfnDefining instanceflow; phrasing; palpablephrasingphrasing*globalsHTMLElement
dialogDialog box or windowflow; sectioning rootflowflowglobals; openHTMLDialogElement
divGeneric flow container, or container for name-value groups in dl elementsflow; palpableflow; dlflowglobalsHTMLDivElement
dlAssociation list consisting of zero or more name-value groupsflow; palpableflowdt*; dd*; div*; script-supporting elementsglobalsHTMLDListElement
dtLegend for corresponding dd element(s)nonedl; div*flow*globalsHTMLElement
emStress emphasisflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
embedPluginflow; phrasing; embedded; interactive; palpablephrasingemptyglobals; src; type; width; height; any*HTMLEmbedElement
fieldsetGroup of form controlsflow; sectioning root; listed; form-associated; palpableflowlegend*; flowglobals; disabled; form; nameHTMLFieldSetElement
figcaptionCaption for figurenonefigureflowglobalsHTMLElement
figureFigure with optional captionflow; sectioning root; palpableflowfigcaption*; flowglobalsHTMLElement
footerFooter for a page or sectionflow; palpableflowflow*globalsHTMLElement
formUser-submittable formflow; palpableflowflow*globals; accept-charset; action; autocomplete; enctype; method; name; novalidate; targetHTMLFormElement
h1, h2, h3, h4, h5, h6Section headingflow; heading; palpablelegend; summary; flowphrasingglobalsHTMLHeadingElement
headContainer for document metadatanonehtmlmetadata content*globalsHTMLHeadElement
headerIntroductory or navigational aids for a page or sectionflow; palpableflowflow*globalsHTMLElement
hgroupheading groupflow; heading; palpable legend; summary; flowh1; h2; h3; h4; h5; h6; script-supporting elementsglobalsHTMLElement
hrThematic breakflowflowemptyglobalsHTMLHRElement
htmlRoot elementnonenone*head*; body*globals; manifestHTMLHtmlElement
iAlternate voiceflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
iframeNested browsing contextflow; phrasing; embedded; interactive; palpablephrasingemptyglobals; src; srcdoc; name; sandbox; allow; allowfullscreen; width; height; referrerpolicy; loadingHTMLIFrameElement
imgImageflow; phrasing; embedded; interactive*; form-associated; palpablephrasing; pictureemptyglobals; alt; src; srcset; sizes; crossorigin; usemap; ismap; width; height; referrerpolicy; decoding; loadingHTMLImageElement
inputForm controlflow; phrasing; interactive*; listed; labelable; submittable; resettable; form-associated; palpable*phrasingemptyglobals; accept; alt; autocomplete; checked; dirname; disabled; form; formaction; formenctype; formmethod; formnovalidate; formtarget; height; list; max; maxlength; min; minlength; multiple; name; pattern; placeholder; readonly; required; size; src; step; type; value; widthHTMLInputElement
insAn addition to the documentflow; phrasing*; palpablephrasingtransparentglobals; cite; datetimeHTMLModElement
kbdUser inputflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
labelCaption for a form controlflow; phrasing; interactive; palpablephrasingphrasing*globals; forHTMLLabelElement
legendCaption for fieldsetnonefieldsetphrasing; heading contentglobalsHTMLLegendElement
liList itemnoneol; ul; menu*flowglobals; value*HTMLLIElement
linkLink metadatametadata; flow*; phrasing*head; noscript*; phrasing*emptyglobals; href; crossorigin; rel; as; media; hreflang; type; sizes; imagesrcset; imagesizes; referrerpolicy; integrity; color; disabled HTMLLinkElement
mainContainer for the dominant contents of the documentflow; palpableflow*flowglobalsHTMLElement
mapImage mapflow; phrasing*; palpablephrasingtransparent; area*globals; nameHTMLMapElement
markHighlightflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
MathML mathMathML rootflow; phrasing; embedded; palpablephrasingper [MATHML]per [MATHML]Element
menuMenu of commandsflow; palpable*flowli; script-supporting elementsglobalsHTMLMenuElement
metaText metadatametadata; flow*; phrasing*head; noscript*; phrasing*emptyglobals; name; http-equiv; content; charsetHTMLMetaElement
meterGaugeflow; phrasing; labelable; palpablephrasingphrasing*globals; value; min; max; low; high; optimumHTMLMeterElement
navSection with navigational linksflow; sectioning; palpableflowflowglobalsHTMLElement
noscriptFallback content for scriptmetadata; flow; phrasinghead*; phrasing*varies*globalsHTMLElement
objectImage, nested browsing context, or pluginflow; phrasing; embedded; interactive*; listed; submittable; form-associated; palpablephrasingparam*; transparentglobals; data; type; name; usemap; form; width; heightHTMLObjectElement
olOrdered listflow; palpable*flowli; script-supporting elementsglobals; reversed; start; typeHTMLOListElement
optgroupGroup of options in a list boxnoneselectoption; script-supporting elementsglobals; disabled; labelHTMLOptGroupElement
optionOption in a list box or combo box controlnoneselect; datalist; optgrouptext*globals; disabled; label; selected; valueHTMLOptionElement
outputCalculated output valueflow; phrasing; listed; labelable; resettable; form-associated; palpablephrasingphrasingglobals; for; form; nameHTMLOutputElement
pParagraphflow; palpableflowphrasingglobalsHTMLParagraphElement
paramParameter for objectnoneobjectemptyglobals; name; valueHTMLParamElement
pictureImageflow; phrasing; embeddedphrasingsource*; one img; script-supporting elementsglobalsHTMLPictureElement
preBlock of preformatted textflow; palpableflowphrasingglobalsHTMLPreElement
progressProgress barflow; phrasing; labelable; palpablephrasingphrasing*globals; value; maxHTMLProgressElement
qQuotationflow; phrasing; palpablephrasingphrasingglobals; citeHTMLQuoteElement
rpParenthesis for ruby annotation textnonerubytextglobalsHTMLElement
rtRuby annotation textnonerubyphrasingglobalsHTMLElement
rubyRuby annotation(s)flow; phrasing; palpablephrasingphrasing; rt; rp*globalsHTMLElement
sInaccurate textflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
sampComputer outputflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
scriptEmbedded scriptmetadata; flow; phrasing; script-supportinghead; phrasing; script-supportingscript, data, or script documentation*globals; src; type; async; defer; crossorigin; integrity; referrerpolicyHTMLScriptElement
sectionGeneric document or application sectionflow; sectioning; palpableflowflowglobalsHTMLElement
selectList box controlflow; phrasing; interactive; listed; labelable; submittable; resettable; form-associated; palpablephrasingoption; optgroup; script-supporting elementsglobals; autocomplete; disabled; form; multiple; name; required; sizeHTMLSelectElement
slotShadow tree slotflow; phrasingphrasingtransparentglobals; nameHTMLSlotElement
smallSide commentflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
sourceImage source for img or media source for video or audiononepicture; video; audioemptyglobals; src; type; srcset; sizes; mediaHTMLSourceElement
spanGeneric phrasing containerflow; phrasing; palpablephrasingphrasingglobalsHTMLSpanElement
strongImportanceflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
styleEmbedded styling informationmetadatahead; noscript*text*globals; mediaHTMLStyleElement
subSubscriptflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
summaryCaption for detailsnonedetailsphrasing; heading contentglobalsHTMLElement
supSuperscriptflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
SVG svgSVG rootflow; phrasing; embedded; palpablephrasingper [SVG]per [SVG]SVGSVGElement
tableTableflow; palpableflowcaption*; colgroup*; thead*; tbody*; tfoot*; tr*; script-supporting elementsglobalsHTMLTableElement
tbodyGroup of rows in a tablenonetabletr; script-supporting elementsglobalsHTMLTableSectionElement
tdTable cellsectioning roottrflowglobals; colspan; rowspan; headersHTMLTableCellElement
templateTemplatemetadata; flow; phrasing; script-supportingmetadata; phrasing; script-supporting; colgroup*emptyglobalsHTMLTemplateElement
textareaMultiline text controlsflow; phrasing; interactive; listed; labelable; submittable; resettable; form-associated; palpablephrasingtextglobals; cols; dirname; disabled; form; maxlength; minlength; name; placeholder; readonly; required; rows; wrapHTMLTextAreaElement
tfootGroup of footer rows in a tablenonetabletr; script-supporting elementsglobalsHTMLTableSectionElement
thTable header cellinteractive*trflow*globals; colspan; rowspan; headers; scope; abbrHTMLTableCellElement
theadGroup of heading rows in a tablenonetabletr; script-supporting elementsglobalsHTMLTableSectionElement
timeMachine-readable equivalent of date- or time-related dataflow; phrasing; palpablephrasingphrasingglobals; datetimeHTMLTimeElement
titleDocument titlemetadataheadtext*globalsHTMLTitleElement
trTable rownonetable; thead; tbody; tfootth*; td; script-supporting elementsglobalsHTMLTableRowElement
trackTimed text tracknoneaudio; videoemptyglobals; default; kind; label; src; srclangHTMLTrackElement
uUnarticulated annotationflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
ulListflow; palpable*flowli; script-supporting elementsglobalsHTMLUListElement
varVariableflow; phrasing; palpablephrasingphrasingglobalsHTMLElement
videoVideo playerflow; phrasing; embedded; interactive; palpablephrasingsource*; track*; transparent*globals; src; crossorigin; poster; preload; autoplay; playsinline; loop; muted; controls; width; heightHTMLVideoElement
wbrLine breaking opportunityflow; phrasingphrasingemptyglobalsHTMLElement
autonomous custom elementsAuthor-defined elementsflow; phrasing; palpableflow; phrasingtransparentglobals; any, as decided by the element's authorSupplied by the element's author (inherits from HTMLElement)

An asterisk (*) in a cell indicates that the actual rules are more complicated than indicated in the table above.

† Categories in the "Parents" column refer to parents that list the given categories in their content model, not to elements that themselves are in those categories. For example, the a element's "Parents" column says "phrasing", so any element whose content model contains the "phrasing" category could be a parent of an a element. Since the "flow" category includes all the "phrasing" elements, that means the th element could be a parent to an a element.

Element content categories

This section is non-normative.

List of element content categories
Category Elements Elements with exceptions
Metadata content base; link; meta; noscript; script; style; template; title
Flow content a; abbr; address; article; aside; audio; b; bdi; bdo; blockquote; br; button; canvas; cite; code; data; datalist; del; details; dfn; dialog; div; dl; em; embed; fieldset; figure; footer; form; h1; h2; h3; h4; h5; h6; header; hgroup; hr; i; iframe; img; input; ins; kbd; label; map; mark; MathML math; menu; meter; nav; noscript; object; ol; output; p; picture; pre; progress; q; ruby; s; samp; script; section; select; slot; small; span; strong; sub; sup; SVG svg; table; template; textarea; time; u; ul; var; video; wbr; autonomous custom elements; Text area (if it is a descendant of a map element); link (if it is allowed in the body); main (if it is a hierarchically correct main element); meta (if the itemprop attribute is present)
Sectioning content article; aside; nav; section
Heading content h1; h2; h3; h4; h5; h6; hgroup
Phrasing content a; abbr; audio; b; bdi; bdo; br; button; canvas; cite; code; data; datalist; del; dfn; em; embed; i; iframe; img; input; ins; kbd; label; map; mark; MathML math; meter; noscript; object; output; picture; progress; q; ruby; s; samp; script; select; slot; small; span; strong; sub; sup; SVG svg; template; textarea; time; u; var; video; wbr; autonomous custom elements; Text area (if it is a descendant of a map element); link (if it is allowed in the body); meta (if the itemprop attribute is present)
Embedded content audio; canvas; embed; iframe; img; MathML math; object; picture; SVG svg; video
Interactive content button; details; embed; iframe; label; select; textarea a (if the href attribute is present); audio (if the controls attribute is present); img (if the usemap attribute is present); input (if the type attribute is not in the Hidden state); object (if the usemap attribute is present); video (if the controls attribute is present)
Sectioning roots blockquote; body; details; dialog; fieldset; figure; td
Form-associated elements button; fieldset; input; label; object; output; select; textarea; img; form-associated custom elements
Listed elements button; fieldset; input; object; output; select; textarea; form-associated custom elements
Submittable elements button; input; object; select; textarea; form-associated custom elements
Resettable elements input; output; select; textarea; form-associated custom elements
Autocapitalize-inheriting elements button; fieldset; input; output; select; textarea
Labelable elements button; input; meter; output; progress; select; textarea; form-associated custom elements
Palpable content a; abbr; address; article; aside; b; bdi; bdo; blockquote; button; canvas; cite; code; data; details; dfn; div; em; embed; fieldset; figure; footer; form; h1; h2; h3; h4; h5; h6; header; hgroup; i; iframe; img; ins; kbd; label; main; map; mark; MathML math; meter; nav; object; output; p; pre; progress; q; ruby; s; samp; section; select; small; span; strong; sub; sup; SVG svg; table; textarea; time; u; var; video; autonomous custom elements audio (if the controls attribute is present); dl (if the element's children include at least one name-value group); input (if the type attribute is not in the Hidden state); menu (if the element's children include at least one li element); ol (if the element's children include at least one li element); ul (if the element's children include at least one li element); Text that is not inter-element whitespace
Script-supporting elements script; template

Attributes

This section is non-normative.

List of attributes (excluding event handler content attributes)
Attribute Element(s) Description Value
abbr th Alternative label to use for the header cell when referencing the cell in other contexts Text*
accept input Hint for expected file type in file upload controls Set of comma-separated tokens* consisting of valid MIME type strings with no parameters or audio/*, video/*, or image/*
accept-charset form Character encodings to use for form submission ASCII case-insensitive match for "UTF-8"
accesskey HTML elements Keyboard shortcut to activate or focus element Ordered set of unique space-separated tokens, none of which are identical to another, each consisting of one code point in length
action form URL to use for form submission Valid non-empty URL potentially surrounded by spaces
allow iframe Permissions policy to be applied to the iframe's contents Serialized permissions policy
allowfullscreen iframe Whether to allow the iframe's contents to use requestFullscreen() Boolean attribute
alt area; img; input Replacement text for use when images are not available Text*
as link Potential destination for a preload request (for rel="preload" and rel="modulepreload") Potential destination, for rel="preload"; script-like destination, for rel="modulepreload"
async script Execute script when available, without blocking while fetching Boolean attribute
autocapitalize HTML elements Recommended autocapitalization behavior (for supported input methods) "on"; "off"; "none"; "sentences"; "words"; "characters"
autocomplete form Default setting for autofill feature for controls in the form "on"; "off"
autocomplete input; select; textarea Hint for form autofill feature Autofill field name and related tokens*
autofocus HTML elements Automatically focus the element when the page is loaded Boolean attribute
autoplay audio; video Hint that the media resource can be started automatically when the page is loaded Boolean attribute
charset meta Character encoding declaration "utf-8"
checked input Whether the control is checked Boolean attribute
cite blockquote; del; ins; q Link to the source of the quotation or more information about the edit Valid URL potentially surrounded by spaces
class HTML elements Classes to which the element belongs Set of space-separated tokens
color link Color to use when customizing a site's icon (for rel="mask-icon") CSS <color>
cols textarea Maximum number of characters per line Valid non-negative integer greater than zero
colspan td; th Number of columns that the cell is to span Valid non-negative integer greater than zero
content meta Value of the element Text*
contenteditable HTML elements Whether the element is editable "true"; "false"
controls audio; video Show user agent controls Boolean attribute
coords area Coordinates for the shape to be created in an image map Valid list of floating-point numbers*
crossorigin audio; img; link; script; video How the element handles crossorigin requests "anonymous"; "use-credentials"
data object Address of the resource Valid non-empty URL potentially surrounded by spaces
datetime del; ins Date and (optionally) time of the change Valid date string with optional time
datetime time Machine-readable value Valid month string, valid date string, valid yearless date string, valid time string, valid local date and time string, valid time-zone offset string, valid global date and time string, valid week string, valid non-negative integer, or valid duration string
decoding img Decoding hint to use when processing this image for presentation "sync"; "async"; "auto"
default track Enable the track if no other text track is more suitable Boolean attribute
defer script Defer script execution Boolean attribute
dir HTML elements The text directionality of the element "ltr"; "rtl"; "auto"
dir bdo The text directionality of the element "ltr"; "rtl"
dirname input; textarea Name of form control to use for sending the element's directionality in form submission Text*
disabled button; input; optgroup; option; select; textarea; form-associated custom elements Whether the form control is disabled Boolean attribute
disabled fieldset Whether the descendant form controls, except any inside legend, are disabled Boolean attribute
disabled link Whether the link is disabled Boolean attribute
download a; area Whether to download the resource instead of navigating to it, and its file name if so Text
draggable HTML elements Whether the element is draggable "true"; "false"
enctype form Entry list encoding type to use for form submission "application/x-www-form-urlencoded"; "multipart/form-data"; "text/plain"
enterkeyhint HTML elements Hint for selecting an enter key action "enter"; "done"; "go"; "next"; "previous"; "search"; "send"
for label Associate the label with form control ID*
for output Specifies controls from which the output was calculated Unordered set of unique space-separated tokens consisting of IDs*
form button; fieldset; input; object; output; select; textarea; form-associated custom elements Associates the element with a form element ID*
formaction button; input URL to use for form submission Valid non-empty URL potentially surrounded by spaces
formenctype button; input Entry list encoding type to use for form submission "application/x-www-form-urlencoded"; "multipart/form-data"; "text/plain"
formmethod button; input Variant to use for form submission "GET"; "POST"; "dialog"
formnovalidate button; input Bypass form control validation for form submission Boolean attribute
formtarget button; input Browsing context for form submission Valid browsing context name or keyword
headers td; th The header cells for this cell Unordered set of unique space-separated tokens consisting of IDs*
height canvas; embed; iframe; img; input; object; video Vertical dimension Valid non-negative integer
hidden HTML elements Whether the element is relevant Boolean attribute
high meter Low limit of high range Valid floating-point number*
href a; area Address of the hyperlink Valid URL potentially surrounded by spaces
href link Address of the hyperlink Valid non-empty URL potentially surrounded by spaces
href base Document base URL Valid URL potentially surrounded by spaces
hreflang a; link Language of the linked resource Valid BCP 47 language tag
http-equiv meta Pragma directive "content-type"; "default-style"; "refresh"; "x-ua-compatible"; "content-security-policy"
id HTML elements The element's ID Text*
imagesizes link Image sizes for different page layouts (for rel="preload") Valid source size list
imagesrcset link Images to use in different situations, e.g., high-resolution displays, small monitors, etc. (for rel="preload") Comma-separated list of image candidate strings
inputmode HTML elements Hint for selecting an input modality "none"; "text"; "tel"; "email"; "url"; "numeric"; "decimal"; "search"
integrity link; script Integrity metadata used in Subresource Integrity checks [SRI] Text
is HTML elements Creates a customized built-in element Valid custom element name of a defined customized built-in element
ismap img Whether the image is a server-side image map Boolean attribute
itemid HTML elements Global identifier for a microdata item Valid URL potentially surrounded by spaces
itemprop HTML elements Property names of a microdata item Unordered set of unique space-separated tokens consisting of valid absolute URLs, defined property names, or text*
itemref HTML elements Referenced elements Unordered set of unique space-separated tokens consisting of IDs*
itemscope HTML elements Introduces a microdata item Boolean attribute
itemtype HTML elements Item types of a microdata item Unordered set of unique space-separated tokens consisting of valid absolute URLs*
kind track The type of text track "subtitles"; "captions"; "descriptions"; "chapters"; "metadata"
label optgroup; option; track User-visible label Text
lang HTML elements Language of the element Valid BCP 47 language tag or the empty string
list input List of autocomplete options ID*
loading img; iframe Used when determining loading deferral "lazy"; "eager"
loop audio; video Whether to loop the media resource Boolean attribute
low meter High limit of low range Valid floating-point number*
manifest html Application cache manifest Valid non-empty URL potentially surrounded by spaces
max input Maximum value Varies*
max meter; progress Upper bound of range Valid floating-point number*
maxlength input; textarea Maximum length of value Valid non-negative integer
media link; source; style Applicable media Valid media query list
method form Variant to use for form submission "GET"; "POST"; "dialog"
min input Minimum value Varies*
min meter Lower bound of range Valid floating-point number*
minlength input; textarea Minimum length of value Valid non-negative integer
multiple input; select Whether to allow multiple values Boolean attribute
muted audio; video Whether to mute the media resource by default Boolean attribute
name button; fieldset; input; output; select; textarea; form-associated custom elements Name of the element to use for form submission and in the form.elements API Text*
name form Name of form to use in the document.forms API Text*
name iframe; object Name of nested browsing context Valid browsing context name or keyword
name map Name of image map to reference from the usemap attribute Text*
name meta Metadata name Text*
name param Name of parameter Text
name slot Name of shadow tree slot Text
nomodule script Prevents execution in user agents that support module scripts Boolean attribute
nonce HTML elements Cryptographic nonce used in Content Security Policy checks [CSP] Text
novalidate form Bypass form control validation for form submission Boolean attribute
open details Whether the details are visible Boolean attribute
open dialog Whether the dialog box is showing Boolean attribute
optimum meter Optimum value in gauge Valid floating-point number*
pattern input Pattern to be matched by the form control's value Regular expression matching the JavaScript Pattern production
ping a; area URLs to ping Set of space-separated tokens consisting of valid non-empty URLs
placeholder input; textarea User-visible label to be placed within the form control Text*
playsinline video Encourage the user agent to display video content within the element's playback area Boolean attribute
poster video Poster frame to show prior to video playback Valid non-empty URL potentially surrounded by spaces
preload audio; video Hints how much buffering the media resource will likely need "none"; "metadata"; "auto"
readonly input; textarea Whether to allow the value to be edited by the user Boolean attribute
readonly form-associated custom elements Affects willValidate, plus any behavior added by the custom element author Boolean attribute
referrerpolicy a; area; iframe; img; link; script Referrer policy for fetches initiated by the element Referrer policy
rel a; area Relationship between the location in the document containing the hyperlink and the destination resource Unordered set of unique space-separated tokens*
rel link Relationship between the document containing the hyperlink and the destination resource Unordered set of unique space-separated tokens*
required input; select; textarea Whether the control is required for form submission Boolean attribute
reversed ol Number the list backwards Boolean attribute
rows textarea Number of lines to show Valid non-negative integer greater than zero
rowspan td; th Number of rows that the cell is to span Valid non-negative integer
sandbox iframe Security rules for nested content Unordered set of unique space-separated tokens, ASCII case-insensitive, consisting of "allow-forms", "allow-modals", "allow-orientation-lock", "allow-pointer-lock", "allow-popups", "allow-popups-to-escape-sandbox", "allow-presentation", "allow-same-origin", "allow-scripts" and "allow-top-navigation"
scope th Specifies which cells the header cell applies to "row"; "col"; "rowgroup"; "colgroup"
selected option Whether the option is selected by default Boolean attribute
shape area The kind of shape to be created in an image map "circle"; "default"; "poly"; "rect"
size input; select Size of the control Valid non-negative integer greater than zero
sizes link Sizes of the icons (for rel="icon") Unordered set of unique space-separated tokens, ASCII case-insensitive, consisting of sizes*
sizes img; source Image sizes for different page layouts Valid source size list
slot HTML elements The element's desired slot Text
span col; colgroup Number of columns spanned by the element Valid non-negative integer greater than zero
spellcheck HTML elements Whether the element is to have its spelling and grammar checked "true"; "false"
src audio; embed; iframe; img; input; script; source; track; video Address of the resource Valid non-empty URL potentially surrounded by spaces
srcdoc iframe A document to render in the iframe The source of an iframe srcdoc document*
srclang track Language of the text track Valid BCP 47 language tag
srcset img; source Images to use in different situations, e.g., high-resolution displays, small monitors, etc. Comma-separated list of image candidate strings
start ol Starting value of the list Valid integer
step input Granularity to be matched by the form control's value Valid floating-point number greater than zero, or "any"
style HTML elements Presentational and formatting instructions CSS declarations*
tabindex HTML elements Whether the element is focusable and sequentially focusable, and the relative order of the element for the purposes of sequential focus navigation Valid integer
target a; area Browsing context for hyperlink navigation Valid browsing context name or keyword
target base Default browsing context for hyperlink navigation and form submission Valid browsing context name or keyword
target form Browsing context for form submission Valid browsing context name or keyword
title HTML elements Advisory information for the element Text
title abbr; dfn Full term or expansion of abbreviation Text
title input Description of pattern (when used with pattern attribute) Text
title link Title of the link Text
title link; style CSS style sheet set name Text
translate HTML elements Whether the element is to be translated when the page is localized "yes"; "no"
type a; link Hint for the type of the referenced resource Valid MIME type string
type button Type of button "submit"; "reset"; "button"
type embed; object; source Type of embedded resource Valid MIME type string
type input Type of form control input type keyword
type ol Kind of list marker "1"; "a"; "A"; "i"; "I"
type script Type of script "module"; a valid MIME type string that is not a JavaScript MIME type essence match
usemap img; object Name of image map to use Valid hash-name reference*
value button; option Value to be used for form submission Text
value data Machine-readable value Text*
value input Value of the form control Varies*
value li Ordinal value of the list item Valid integer
value meter; progress Current value of the element Valid floating-point number
value param Value of parameter Text
width canvas; embed; iframe; img; input; object; video Horizontal dimension Valid non-negative integer
wrap textarea How the value of the form control is to be wrapped for form submission "soft"; "hard"

An asterisk (*) in a cell indicates that the actual rules are more complicated than indicated in the table above.


GlobalEventHandlers/ondrag

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+

GlobalEventHandlers/ondragend

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+

GlobalEventHandlers/ondragenter

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+

GlobalEventHandlers/ondragleave

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+

GlobalEventHandlers/ondragover

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+

GlobalEventHandlers/ondragstart

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+

GlobalEventHandlers/ondrop

Support in all current engines.

Firefox9+Safari3.1+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
List of event handler content attributes
Attribute Element(s) Description Value
onabort HTML elements abort event handler Event handler content attribute
onauxclick HTML elements auxclick event handler Event handler content attribute
onafterprint body afterprint event handler for Window object Event handler content attribute
onbeforeprint body beforeprint event handler for Window object Event handler content attribute
onbeforeunload body beforeunload event handler for Window object Event handler content attribute
onblur HTML elements blur event handler Event handler content attribute
oncancel HTML elements cancel event handler Event handler content attribute
oncanplay HTML elements canplay event handler Event handler content attribute
oncanplaythrough HTML elements canplaythrough event handler Event handler content attribute
onchange HTML elements change event handler Event handler content attribute
onclick HTML elements click event handler Event handler content attribute
onclose HTML elements close event handler Event handler content attribute
oncontextmenu HTML elements contextmenu event handler Event handler content attribute
oncopy HTML elements copy event handler Event handler content attribute
oncuechange HTML elements cuechange event handler Event handler content attribute
oncut HTML elements cut event handler Event handler content attribute
ondblclick HTML elements dblclick event handler Event handler content attribute
ondrag HTML elements drag event handler Event handler content attribute
ondragend HTML elements dragend event handler Event handler content attribute
ondragenter HTML elements dragenter event handler Event handler content attribute
ondragleave HTML elements dragleave event handler Event handler content attribute
ondragover HTML elements dragover event handler Event handler content attribute
ondragstart HTML elements dragstart event handler Event handler content attribute
ondrop HTML elements drop event handler Event handler content attribute
ondurationchange HTML elements durationchange event handler Event handler content attribute
onemptied HTML elements emptied event handler Event handler content attribute
onended HTML elements ended event handler Event handler content attribute
onerror HTML elements error event handler Event handler content attribute
onfocus HTML elements focus event handler Event handler content attribute
onformdata HTML elements formdata event handler Event handler content attribute
onhashchange body hashchange event handler for Window object Event handler content attribute
oninput HTML elements input event handler Event handler content attribute
oninvalid HTML elements invalid event handler Event handler content attribute
onkeydown HTML elements keydown event handler Event handler content attribute
onkeypress HTML elements keypress event handler Event handler content attribute
onkeyup HTML elements keyup event handler Event handler content attribute
onlanguagechange body languagechange event handler for Window object Event handler content attribute
onload HTML elements load event handler Event handler content attribute
onloadeddata HTML elements loadeddata event handler Event handler content attribute
onloadedmetadata HTML elements loadedmetadata event handler Event handler content attribute
onloadstart HTML elements loadstart event handler Event handler content attribute
onmessage body message event handler for Window object Event handler content attribute
onmessageerror body messageerror event handler for Window object Event handler content attribute
onmousedown HTML elements mousedown event handler Event handler content attribute
onmouseenter HTML elements mouseenter event handler Event handler content attribute
onmouseleave HTML elements mouseleave event handler Event handler content attribute
onmousemove HTML elements mousemove event handler Event handler content attribute
onmouseout HTML elements mouseout event handler Event handler content attribute
onmouseover HTML elements mouseover event handler Event handler content attribute
onmouseup HTML elements mouseup event handler Event handler content attribute
onoffline body offline event handler for Window object Event handler content attribute
ononline body online event handler for Window object Event handler content attribute
onpagehide body pagehide event handler for Window object Event handler content attribute
onpageshow body pageshow event handler for Window object Event handler content attribute
onpaste HTML elements paste event handler Event handler content attribute
onpause HTML elements pause event handler Event handler content attribute
onplay HTML elements play event handler Event handler content attribute
onplaying HTML elements playing event handler Event handler content attribute
onpopstate body popstate event handler for Window object Event handler content attribute
onprogress HTML elements progress event handler Event handler content attribute
onratechange HTML elements ratechange event handler Event handler content attribute
onreset HTML elements reset event handler Event handler content attribute
onresize HTML elements resize event handler Event handler content attribute
onrejectionhandled body rejectionhandled event handler for Window object Event handler content attribute
onscroll HTML elements scroll event handler Event handler content attribute
onsecuritypolicyviolation HTML elements securitypolicyviolation event handler Event handler content attribute
onseeked HTML elements seeked event handler Event handler content attribute
onseeking HTML elements seeking event handler Event handler content attribute
onselect HTML elements select event handler Event handler content attribute
onslotchange HTML elements slotchange event handler Event handler content attribute
onstalled HTML elements stalled event handler Event handler content attribute
onstorage body storage event handler for Window object Event handler content attribute
onsubmit HTML elements submit event handler Event handler content attribute
onsuspend HTML elements suspend event handler Event handler content attribute
ontimeupdate HTML elements timeupdate event handler Event handler content attribute
ontoggle HTML elements toggle event handler Event handler content attribute
onunhandledrejection body unhandledrejection event handler for Window object Event handler content attribute
onunload body unload event handler for Window object Event handler content attribute
onvolumechange HTML elements volumechange event handler Event handler content attribute
onwaiting HTML elements waiting event handler Event handler content attribute
onwheel HTML elements wheel event handler Event handler content attribute

Element Interfaces

This section is non-normative.

List of interfaces for elements
Element(s) Interface(s)
a HTMLAnchorElement : HTMLElement
abbr HTMLElement
address HTMLElement
area HTMLAreaElement : HTMLElement
article HTMLElement
aside HTMLElement
audio HTMLAudioElement : HTMLMediaElement : HTMLElement
b HTMLElement
base HTMLBaseElement : HTMLElement
bdi HTMLElement
bdo HTMLElement
blockquote HTMLQuoteElement : HTMLElement
body HTMLBodyElement : HTMLElement
br HTMLBRElement : HTMLElement
button HTMLButtonElement : HTMLElement
canvas HTMLCanvasElement : HTMLElement
caption HTMLTableCaptionElement : HTMLElement
cite HTMLElement
code HTMLElement
col HTMLTableColElement : HTMLElement
colgroup HTMLTableColElement : HTMLElement
data HTMLDataElement : HTMLElement
datalist HTMLDataListElement : HTMLElement
dd HTMLElement
del HTMLModElement : HTMLElement
details HTMLDetailsElement : HTMLElement
dfn HTMLElement
dialog HTMLDialogElement : HTMLElement
div HTMLDivElement : HTMLElement
dl HTMLDListElement : HTMLElement
dt HTMLElement
em HTMLElement
embed HTMLEmbedElement : HTMLElement
fieldset HTMLFieldSetElement : HTMLElement
figcaption HTMLElement
figure HTMLElement
footer HTMLElement
form HTMLFormElement : HTMLElement
h1 HTMLHeadingElement : HTMLElement
h2 HTMLHeadingElement : HTMLElement
h3 HTMLHeadingElement : HTMLElement
h4 HTMLHeadingElement : HTMLElement
h5 HTMLHeadingElement : HTMLElement
h6 HTMLHeadingElement : HTMLElement
head HTMLHeadElement : HTMLElement
header HTMLElement
hgroup HTMLElement
hr HTMLHRElement : HTMLElement
html HTMLHtmlElement : HTMLElement
i HTMLElement
iframe HTMLIFrameElement : HTMLElement
img HTMLImageElement : HTMLElement
input HTMLInputElement : HTMLElement
ins HTMLModElement : HTMLElement
kbd HTMLElement
label HTMLLabelElement : HTMLElement
legend HTMLLegendElement : HTMLElement
li HTMLLIElement : HTMLElement
link HTMLLinkElement : HTMLElement
main HTMLElement
map HTMLMapElement : HTMLElement
mark HTMLElement
menu HTMLMenuElement : HTMLElement
meta HTMLMetaElement : HTMLElement
meter HTMLMeterElement : HTMLElement
nav HTMLElement
noscript HTMLElement
object HTMLObjectElement : HTMLElement
ol HTMLOListElement : HTMLElement
optgroup HTMLOptGroupElement : HTMLElement
option HTMLOptionElement : HTMLElement
output HTMLOutputElement : HTMLElement
p HTMLParagraphElement : HTMLElement
param HTMLParamElement : HTMLElement
picture HTMLPictureElement : HTMLElement
pre HTMLPreElement : HTMLElement
progress HTMLProgressElement : HTMLElement
q HTMLQuoteElement : HTMLElement
rp HTMLElement
rt HTMLElement
ruby HTMLElement
s HTMLElement
samp HTMLElement
script HTMLScriptElement : HTMLElement
section HTMLElement
select HTMLSelectElement : HTMLElement
slot HTMLSlotElement : HTMLElement
small HTMLElement
source HTMLSourceElement : HTMLElement
span HTMLSpanElement : HTMLElement
strong HTMLElement
style HTMLStyleElement : HTMLElement
sub HTMLElement
summary HTMLElement
sup HTMLElement
table HTMLTableElement : HTMLElement
tbody HTMLTableSectionElement : HTMLElement
td HTMLTableCellElement : HTMLElement
template HTMLTemplateElement : HTMLElement
textarea HTMLTextAreaElement : HTMLElement
tfoot HTMLTableSectionElement : HTMLElement
th HTMLTableCellElement : HTMLElement
thead HTMLTableSectionElement : HTMLElement
time HTMLTimeElement : HTMLElement
title HTMLTitleElement : HTMLElement
tr HTMLTableRowElement : HTMLElement
track HTMLTrackElement : HTMLElement
u HTMLElement
ul HTMLUListElement : HTMLElement
var HTMLElement
video HTMLVideoElement : HTMLMediaElement : HTMLElement
wbr HTMLElement
custom elements supplied by the element's author (inherits from HTMLElement)

所有接口

This section is non-normative.

Events

This section is non-normative.

List of events
Event Interface Interesting targets Description
abort Event Window Fired at the Window when the download was aborted by the user
DOMContentLoaded

Window/DOMContentLoaded_event

Support in all current engines.

Firefox1+Safari3.1+Chrome1+
Opera9+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android10.1+
Event Document Fired at the Document once the parser has finished
afterprint

Window/afterprint_event

Support in all current engines.

Firefox6+Safari13+Chrome63+
Opera50+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android6+Safari iOS13+Chrome Android63+WebView Android63+Samsung Internet8.0+Opera Android46+
Event Window Fired at the Window after printing
beforeprint

Window/beforeprint_event

Support in all current engines.

Firefox6+Safari13+Chrome63+
Opera50+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android6+Safari iOS13+Chrome Android63+WebView Android63+Samsung Internet8.0+Opera Android46+
Event Window Fired at the Window before printing
beforeunload

Window/beforeunload_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera12+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
BeforeUnloadEvent Window Fired at the Window when the page is about to be unloaded, in case the page would like to show a warning prompt
blur Event Window, elements Fired at nodes when they stop being focused
cancel

HTMLDialogElement/cancel_event

Support in all current engines.

Firefox98+Safari15.4+Chrome37+
Opera24+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOS15.4+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo
Event dialog elements Fired at dialog elements when they are canceled by the user (e.g. by pressing the Escape key)
change Event Form controls Fired at controls when the user commits a value change (see also the input event)
click MouseEvent Elements Normally a mouse event; also synthetically fired at an element before its activation behavior is run, when an element is activated from a non-pointer input device (e.g. a keyboard)
close

HTMLDialogElement/close_event

Support in all current engines.

Firefox98+Safari15.4+Chrome37+
Opera24+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android98+Safari iOS15.4+Chrome AndroidNoWebView AndroidNoSamsung InternetNoOpera AndroidNo
Event or CloseEvent dialog elements, WebSocket Fired at dialog elements when they are closed, and at WebSocket objects when the connection is terminated
connect

SharedWorkerGlobalScope/connect_event

Firefox29+SafariNoChrome4+
Opera10.6+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android29+Safari iOSNoChrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
MessageEvent SharedWorkerGlobalScope Fired at a shared worker's global scope when a new client connects
contextmenu MouseEvent Elements Fired at elements when the user requests their context menu
copy Event Elements Fired at elements when the user copies data to the clipboard
cut Event Elements Fired at elements when the user copies the selected data on the clipboard and removes the selection from the document
error

EventSource/error_event

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12+
Event or ErrorEvent Global scope objects, Worker objects, elements, networking-related objects Fired when unexpected errors occur (e.g. networking errors, script errors, decoding errors)
focus Event Window, elements Fired at nodes gaining focus
formdata

HTMLFormElement/formdata_event

Support in all current engines.

Firefox72+Safari15+Chrome77+
Opera64+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox AndroidNoSafari iOS15+Chrome Android77+WebView Android77+Samsung Internet12.0+Opera Android55+
FormDataEvent form elements Fired at a form element when it is constructing the entry list
hashchange

Window/hashchange_event

Support in all current engines.

Firefox3.6+Safari5+Chrome8+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11+
HashChangeEvent Window Fired at the Window when the fragment part of the document's URL changes
input

HTMLElement/input_event

Support in all current engines.

Firefox6+Safari3.1+Chrome1+
Opera11.6+Edge79+
Edge (Legacy)NoInternet Explorer🔰 9+
Firefox Android6+Safari iOS2+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android12+
Event Form controls Fired at controls when the user changes the value (see also the change event)
invalid

HTMLInputElement/invalid_event

Support in all current engines.

Firefox4+Safari5+Chrome10+
Opera10+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android64+Safari iOS5+Chrome Android18+WebView Android4+Samsung Internet4.0+Opera Android12+
Event Form controls Fired at controls during form validation if they do not satisfy their constraints
languagechange

Window/languagechange_event

Support in all current engines.

Firefox32+Safari10.1+Chrome37+
Opera24+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android4+Safari iOS10.3+Chrome Android37+WebView Android37+Samsung Internet4.0+Opera Android24+

WorkerGlobalScope/languagechange_event

Support in all current engines.

Firefox74+Safari4+Chrome4+
Opera11.5+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS5+Chrome Android40+WebView Android37+Samsung Internet4.0+Opera Android27+
Event Global scope objects Fired at the global scope object when the user's preferred languages change
load Event Window, elements Fired at the Window when the document has finished loading; fired at an element containing a resource (e.g. img, embed) when its resource has finished loading
message

BroadcastChannel/message_event

Support in all current engines.

Firefox38+Safari15.4+Chrome54+
Opera41+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android38+Safari iOS15.4+Chrome Android54+WebView Android54+Samsung Internet6.0+Opera Android41+

DedicatedWorkerGlobalScope/message_event

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11.5+

EventSource/message_event

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12+

MessagePort/message_event

Support in all current engines.

Firefox41+Safari5+Chrome1+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android41+Safari iOS4.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11.5+

Window/message_event

Support in all current engines.

Firefox9+Safari4+Chrome60+
Opera47+Edge79+
Edge (Legacy)12+Internet Explorer8+
Firefox Android9+Safari iOS4+Chrome Android60+WebView Android60+Samsung Internet8.0+Opera Android47+

Worker/message_event

Support in all current engines.

Firefox3.5+Safari4+Chrome4+
Opera10.6+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android11.5+
MessageEvent Window, EventSource, WebSocket, MessagePort, BroadcastChannel, DedicatedWorkerGlobalScope, Worker, ServiceWorkerContainer Fired at an object when it receives a message
messageerror

BroadcastChannel/messageerror_event

Support in all current engines.

Firefox57+Safari15.4+Chrome60+
Opera47+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android57+Safari iOS15.4+Chrome Android60+WebView Android60+Samsung Internet8.0+Opera Android47+

DedicatedWorkerGlobalScope/messageerror_event

Firefox57+SafariNoChrome60+
Opera47+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android57+Safari iOSNoChrome Android60+WebView Android60+Samsung Internet8.0+Opera Android47+

MessagePort/messageerror_event

Firefox57+SafariNoChrome60+
Opera47+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android57+Safari iOSNoChrome Android60+WebView Android60+Samsung Internet8.0+Opera Android47+

Window/messageerror_event

Firefox57+SafariNoChrome60+
Opera47+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android57+Safari iOSNoChrome Android60+WebView Android60+Samsung Internet8.0+Opera Android47+

Worker/messageerror_event

Firefox57+SafariNoChrome60+
Opera47+Edge79+
Edge (Legacy)18Internet ExplorerNo
Firefox Android57+Safari iOSNoChrome Android60+WebView Android60+Samsung Internet8.0+Opera Android47+
MessageEvent Window, MessagePort, BroadcastChannel, DedicatedWorkerGlobalScope, Worker, ServiceWorkerContainer Fired at an object when it receives a message that cannot be deserialized
offline

Window/offline_event

Support in all current engines.

Firefox9+Safari4+Chrome3+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
Event Global scope objects Fired at the global scope object when the network connections fails
online

Window/online_event

Support in all current engines.

Firefox9+Safari4+Chrome3+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android9+Safari iOS3+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
Event Global scope objects Fired at the global scope object when the network connections returns
open

EventSource/open_event

Support in all current engines.

Firefox6+Safari5+Chrome6+
Opera12+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android45+Safari iOS5+Chrome Android18+WebView Android4.4+Samsung Internet1.0+Opera Android12+
Event EventSource, WebSocket Fired at networking-related objects when a connection is established
pagehide

Window/pagehide_event

Support in all current engines.

Firefox6+Safari5+Chrome3+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android6+Safari iOS4.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
PageTransitionEvent Window Fired at the Window when the page's entry in the session history stops being the current entry
pageshow

Window/pageshow_event

Support in all current engines.

Firefox6+Safari5+Chrome3+
Opera15+Edge79+
Edge (Legacy)12+Internet Explorer11
Firefox Android6+Safari iOS4.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
PageTransitionEvent Window Fired at the Window when the page's entry in the session history becomes the current entry
paste Event Elements Fired at elements when the user will insert the clipboard data in the most suitable format (if any) supported for the given context
popstate

Window/popstate_event

Support in all current engines.

Firefox4+Safari5+Chrome5+
Opera11.5+Edge79+
Edge (Legacy)12+Internet Explorer10+
Firefox Android4+Safari iOS4.2+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android11.5+
PopStateEvent Window Fired at the Window when the user navigates the session history
readystatechange

Document/readystatechange_event

Support in all current engines.

Firefox4+Safari5.1+Chrome9+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS5+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
Event Document Fired at the Document when it finishes parsing and again when all its subresources have finished loading
rejectionhandled PromiseRejectionEvent Global scope objects Fired at global scope objects when a previously-unhandled promise rejection becomes handled
reset

HTMLFormElement/reset_event

Support in all current engines.

Firefox6+Safari3+Chrome1+
Opera12.1+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android6+Safari iOS1+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android12.1+
Event form elements Fired at a form element when it is reset
securitypolicyviolation Event Elements Fired at elements when a Content Security Policy violation is generated [CSP]
select Event Form controls Fired at form controls when their text selection is adjusted (whether by an API or by the user)
slotchange

HTMLSlotElement/slotchange_event

Support in all current engines.

Firefox63+Safari10.1+Chrome53+
Opera40+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android63+Safari iOS10.3+Chrome Android53+WebView Android53+Samsung Internet6.0+Opera Android41+
Event slot elements Fired at slot elements when their assigned nodes change
storage

Window/storage_event

Support in all current engines.

Firefox45+Safari4+Chrome1+
Opera15+Edge79+
Edge (Legacy)15+Internet Explorer9+
Firefox Android45+Safari iOS4+Chrome Android18+WebView Android37+Samsung Internet1.0+Opera Android14+
StorageEvent Window Fired at Window event when the corresponding localStorage or sessionStorage storage areas change
submit

HTMLFormElement/submit_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera8+Edge79+
Edge (Legacy)12+Internet Explorer9+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
Event form elements Fired at a form element when it is submitted
toggle

HTMLDetailsElement/toggle_event

Support in all current engines.

Firefox49+Safari10.1+Chrome36+
Opera23+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android49+Safari iOS10.3+Chrome Android36+WebView Android37+Samsung Internet3.0+Opera Android24+
Event details element Fired at details elements when they open or close
unhandledrejection

Window/unhandledrejection_event

Support in all current engines.

Firefox69+Safari11+Chrome49+
Opera36+Edge79+
Edge (Legacy)NoInternet ExplorerNo
Firefox Android79+Safari iOS11.3+Chrome Android49+WebView Android49+Samsung Internet5.0+Opera Android36+
PromiseRejectionEvent Global scope objects Fired at global scope objects when a promise rejection goes unhandled
unload

Window/unload_event

Support in all current engines.

Firefox1+Safari3+Chrome1+
Opera4+Edge79+
Edge (Legacy)12+Internet Explorer4+
Firefox Android4+Safari iOS1+Chrome Android18+WebView Android1+Samsung Internet1.0+Opera Android10.1+
Event Window Fired at the Window object when the page is going away

See also media element events, application cache events, and drag-and-drop events.

MIME 类型

This section is non-normative.

本规范中提到了以下 MIME 类型:

application/atom+xml
Atom [ATOM]
application/ecmascript
JavaScript (遗留类型) [JAVASCRIPT]
application/javascript
JavaScript (遗留类型) [JAVASCRIPT]
application/json
JSON [JSON]
application/x-ecmascript
JavaScript (遗留类型) [JAVASCRIPT]
application/x-javascript
JavaScript (遗留类型) [JAVASCRIPT]
application/octet-stream
通用二进制数据 [RFC2046]
application/microdata+json
JSON 格式的元数据
application/rss+xml
RSS
application/x-www-form-urlencoded
表单提交
application/xhtml+xml
HTML
application/xml
XML [XML] [RFC7303]
image/gif
GIF 图片 [GIF]
image/jpeg
JPEG 图片 [JPEG]
image/png
PNG 图片 [PNG]
image/svg+xml
SVG 图片 [SVG]
multipart/form-data
表单提交 [RFC7578]
multipart/mixed
通用混合内容 [RFC2046]
multipart/x-mixed-replace
流式服务器推送
text/cache-manifest
离线应用缓存清单
text/css
CSS [CSS]
text/ecmascript
JavaScript (遗留类型) [JAVASCRIPT]
text/event-stream
服务器发送的事件流
text/javascript
JavaScript [JAVASCRIPT]
text/javascript1.0
JavaScript (遗留类型) [JAVASCRIPT]
text/javascript1.1
JavaScript (遗留类型) [JAVASCRIPT]
text/javascript1.2
JavaScript (遗留类型) [JAVASCRIPT]
text/javascript1.3
JavaScript (遗留类型) [JAVASCRIPT]
text/javascript1.4
JavaScript (遗留类型) [JAVASCRIPT]
text/javascript1.5
JavaScript (遗留类型) [JAVASCRIPT]
text/jscript
JavaScript (遗留类型) [JAVASCRIPT]
text/json
JSON (遗留类型)
text/livescript
JavaScript (遗留类型) [JAVASCRIPT]
text/plain
通用纯文本 [RFC2046] [RFC3676]
text/html
HTML
text/ping
超链接审计
text/uri-list
URL 列表 [RFC2483]
text/vcard
vCard [RFC6350]
text/vtt
WebVTT [WEBVTT]
text/x-ecmascript
JavaScript (遗留类型) [JAVASCRIPT]
text/x-javascript
JavaScript (遗留类型) [JAVASCRIPT]
text/xml
XML [XML] [RFC7303]
video/mp4
MPEG-4 视频 [RFC4337]
video/mpeg
MPEG 视频 [RFC2046]

References

All references are normative unless marked "Non-normative".

[ABNF]
Augmented BNF for Syntax Specifications: ABNF, D. Crocker, P. Overell. IETF.
[ABOUT]
The 'about' URI scheme, S. Moonesamy. IETF.
[APNG]
(Non-normative) APNG Specification. S. Parmenter, V. Vukicevic, A. Smith. Mozilla.
[ARIA]
Accessible Rich Internet Applications (WAI-ARIA), J. Diggs, J. Nurthen, M. Cooper. W3C.
[ARIAHTML]
ARIA in HTML, S. Faulkner, S. O'Hara. W3C.
[ATAG]
(Non-normative) Authoring Tool Accessibility Guidelines (ATAG) 2.0, J. Richards, J. Spellman, J. Treviranus. W3C.
[ATOM]
(Non-normative) The Atom Syndication Format, M. Nottingham, R. Sayre. IETF.
[BATTERY]
(Non-normative) Battery Status API, A. Kostiainen, M. Lamouri. W3C.
[BCP47]
Tags for Identifying Languages; Matching of Language Tags, A. Phillips, M. Davis. IETF.
[BEZIER]
Courbes à poles, P. de Casteljau. INPI, 1959.
[BIDI]
UAX #9: Unicode Bidirectional Algorithm, M. Davis. Unicode Consortium.
[BOCU1]
(Non-normative) UTN #6: BOCU-1: MIME-Compatible Unicode Compression, M. Scherer, M. Davis. Unicode Consortium.
[CESU8]
(Non-normative) UTR #26: Compatibility Encoding Scheme For UTF-16: 8-BIT (CESU-8), T. Phipps. Unicode Consortium.
[CHARMOD]
(Non-normative) Character Model for the World Wide Web 1.0: Fundamentals, M. Dürst, F. Yergeau, R. Ishida, M. Wolf, T. Texin. W3C.
[COMPOSITE]
Compositing and Blending, R. Cabanier, N. Andronikos. W3C.
[COMPUTABLE]
(Non-normative) On computable numbers, with an application to the Entscheidungsproblem, A. Turing. In Proceedings of the London Mathematical Society, series 2, volume 42, pages 230-265. London Mathematical Society, 1937.
[COOKIES]
HTTP State Management Mechanism, A. Barth. IETF.
[CSP]
Content Security Policy, M. West, D. Veditz. W3C.
[CSS]
Cascading Style Sheets Level 2 Revision 2, B. Bos, T. Çelik, I. Hickson, H. Lie. W3C.
[CSSALIGN]
CSS Box Alignment, E. Etemad, T. Atkins. W3C.
[CSSANIMATIONS]
CSS Animations, D. Jackson, D. Hyatt, C. Marrin, S. Galineau, L. Baron. W3C.
[CSSATTR]
CSS Style Attributes, T. Çelik, E. Etemad. W3C.
[CSSBG]
CSS Backgrounds and Borders, B. Bos, E. Etemad, B. Kemper. W3C.
[CSSCASCADE]
CSS Cascading and Inheritance, E. Etemad, T. Atkins. W3C.
[CSSCOLOR]
CSS Color Module, T. Çelik, C. Lilley, L. Baron. W3C.
[CSSCOLORADJUST]
CSS Color Adjustment Module, E. Etemad, R. Atanassov, R. Lillesveen, T. Atkins. W3C.
[CSSDISPLAY]
CSS Display, T. Atkins, E. Etemad. W3C.
[CSSFONTLOAD]
CSS Font Loading, T. Atkins, J. Daggett. W3C.
[CSSFONTS]
CSS Fonts, J. Daggett. W3C.
[CSSFLEXBOX]
CSS Flexible Box Layout, T. Atkins, E. Etemad, R. Atanassov. W3C.
[CSSGC]
CSS Generated Content, H. Lie, E. Etemad, I. Hickson. W3C.
[CSSGRID]
CSS Grid Layout, T. Atkins, E. Etemad, R. Atanassov. W3C.
[CSSIMAGES]
CSS Images Module, E. Etemad, T. Atkins, L. Verou. W3C.
[CSSIMAGES4]
CSS Images Module Level 4, E. Etemad, T. Atkins, L. Verou. W3C.
[CSSINLINE]
CSS Inline Layout, D. Cramer, E. Etemad. W3C.
[CSSLISTS]
CSS Lists and Counters, T. Atkins. W3C.
[CSSLOGICAL]
CSS Logical Properties, R. Atanassov, E. Etemad. W3C.
[CSSMULTICOL]
CSS Multi-column Layout, H. Lie, F. Rivoal, R. Andrew. W3C.
[CSSOM]
Cascading Style Sheets Object Model (CSSOM), S. Pieters, G. Adams. W3C.
[CSSOMVIEW]
CSSOM View Module, S. Pieters, G. Adams. W3C.
[CSSOVERFLOW]
CSS Overflow Module, L. Baron, F. Rivoal. W3C.
[CSSPAINT]
(Non-normative) CSS Painting API, I. Kilpatrick, D. Jackson. W3C.
[CSSPOSITION]
CSS Positioned Layout, R. Atanassov, A. Eicholz. W3C.
[CSSRUBY]
CSS3 Ruby Module, R. Ishida. W3C.
[CSSSCOPING]
CSS Scoping Module, T. Atkins. W3C.
[CSSSIZING]
CSS Intrinsic & Extrinsic Sizing Module, T. Atkins, E. Etemad. W3C.
[CSSTRANSITIONS]
(Non-normative) CSS Transitions, D. Jackson, D. Hyatt, C. Marrin, L. Baron. W3C.
[CSSUI]
CSS3 Basic User Interface Module, T. Çelik. W3C.
[CSSSYNTAX]
CSS Syntax, T. Atkins, S. Sapin. W3C.
[CSSTABLE]
CSS Table, F. Remy, G. Whitworth. W3C.
[CSSTEXT]
CSS Text, E. Etemad, K. Ishii. W3C.
[CSSVALUES]
CSS3 Values and Units, H. Lie, T. Atkins, E. Etemad. W3C.
[CSSWM]
CSS Writing Modes, E. Etemad, K. Ishii. W3C.
[DASH]
Dynamic adaptive streaming over HTTP (DASH). ISO.
[DOM]
DOM, A. van Kesteren, A. Gregor, Ms2ger. WHATWG.
[DOMPARSING]
DOM Parsing and Serialization, T. Leithead. W3C.
[DOT]
(Non-normative) The DOT Language. Graphviz.
[E163]
Recommendation E.163 — Numbering Plan for The International Telephone Service, CCITT Blue Book, Fascicle II.2, pp. 128-134, November 1988.
[ENCODING]
Encoding, A. van Kesteren, J. Bell. WHATWG.
[EXECCOMMAND]
execCommand, J. Wilm, A. Gregor. W3C Editing APIs CG.
[EXIF]
(Non-normative) Exchangeable image file format. JEITA.
[FETCH]
Fetch, A. van Kesteren. WHATWG.
[FILEAPI]
File API, A. Ranganathan. W3C.
[FILTERS]
Filter Effects, D. Jackson, E. Dahlström, D. Schulze. W3C.
[FULLSCREEN]
Fullscreen, A. van Kesteren, T. Çelik. WHATWG.
[GEOMETRY]
Geometry Interfaces. S. Pieters, D. Schulze, R. Cabanier. W3C.
[GIF]
(Non-normative) Graphics Interchange Format. CompuServe.
[GRAPHICS]
(Non-normative) Computer Graphics: Principles and Practice in C, Second Edition, J. Foley, A. van Dam, S. Feiner, J. Hughes. Addison-Wesley. ISBN 0-201-84840-6.
[GREGORIAN]
(Non-normative) Inter Gravissimas, A. Lilius, C. Clavius. Gregory XIII Papal Bull, February 1582.
[HRT]
High Resolution Time, I. Grigorik, J. Simonsen, J. Mann. W3C.
[HTMLAAM]
HTML Accessibility API Mappings 1.0, S. Faulkner, A. Surkov, S. O'Hara. W3C.
[HTTP]
Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing, R. Fielding, J. Reschke. IETF.
Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content, R. Fielding, J. Reschke. IETF.
Hypertext Transfer Protocol (HTTP/1.1): Conditional Requests, R. Fielding, J. Reschke. IETF.
Hypertext Transfer Protocol (HTTP/1.1): Range Requests, R. Fielding, Y. Lafon, J. Reschke. IETF.
Hypertext Transfer Protocol (HTTP/1.1): Caching, R. Fielding, M. Nottingham, J. Reschke. IETF.
Hypertext Transfer Protocol (HTTP/1.1): Authentication, R. Fielding, J. Reschke. IETF.
[INDEXEDDB]
Indexed Database API, A. Alabbas, J. Bell. W3C.
[INBAND]
Sourcing In-band Media Resource Tracks from Media Containers into HTML, S. Pfeiffer, B. Lund. W3C.
[INFRA]
Infra, A. van Kesteren, D. Denicola. WHATWG.
[INTERSECTIONOBSERVER]
Intersection Observer, S. Zager. W3C.
[ISO3166]
ISO 3166: Codes for the representation of names of countries and their subdivisions. ISO.
[ISO4217]
ISO 4217: Codes for the representation of currencies and funds. ISO.
[ISO8601]
(Non-normative) ISO8601: Data elements and interchange formats — Information interchange — Representation of dates and times. ISO.
[JAVASCRIPT]
ECMAScript Language Specification. Ecma International.
[JLREQ]
Requirements for Japanese Text Layout. W3C.
[JPEG]
JPEG File Interchange Format, E. Hamilton.
[JSERRORSTACKS]
(Non-normative) Error Stacks. Ecma International.
[JSINTL]
ECMAScript Internationalization API Specification. Ecma International.
[JSON]
The JavaScript Object Notation (JSON) Data Interchange Format, T. Bray. IETF.
[LONGTASKS]
Long Tasks, D. Denicola, I. Grigorik, S. Panicker. W3C.
[MAILTO]
(Non-normative) The 'mailto' URI scheme, M. Duerst, L. Masinter, J. Zawinski. IETF.
[MANIFEST]
Web App Manifest, M. Caceres, K. Rohde Christiansen, M. Lamouri, A. Kostiainen, M. Giuca, A. Gustafson. W3C.
[MATHML]
Mathematical Markup Language (MathML), D. Carlisle, P. Ion, R. Miner. W3C.
[MEDIAFRAG]
Media Fragments URI, R. Troncy, E. Mannens, S. Pfeiffer, D. Van Deursen. W3C.
[MEDIASOURCE]
Media Source Extensions, A. Colwell, A. Bateman, M. Watson. W3C.
[MEDIASTREAM]
Media Capture and Streams, D. Burnett, A. Bergkvist, C. Jennings, A. Narayanan. W3C.
[REPORTING]
Reporting, D. Creager, I. Clelland, M. West. W3C.
[MFREL]
Microformats Wiki: existing rel values. Microformats.
[MIMESNIFF]
MIME Sniffing, G. Hemsley. WHATWG.
[MIX]
Mixed Content, M. West. W3C.
[MNG]
MNG (Multiple-image Network Graphics) Format. G. Randers-Pehrson.
[MPEG2]
ISO/IEC 13818-1: Information technology — Generic coding of moving pictures and associated audio information: Systems. ISO/IEC.
[MPEG4]
ISO/IEC 14496-12: ISO base media file format. ISO/IEC.
[MQ]
Media Queries, H. Lie, T. Çelik, D. Glazman, A. van Kesteren. W3C.
[MULTIPLEBUFFERING]
(Non-normative) Multiple buffering. Wikipedia.
[NAVMODEL]
A Model of Navigation History. C. Brewster, A. Jeffrey.
[NPAPI]
(Non-normative) Gecko Plugin API Reference. Mozilla.
[OGGSKELETONHEADERS]
SkeletonHeaders. Xiph.Org.
[OPENSEARCH]
Autodiscovery in HTML/XHTML. In OpenSearch 1.1 Draft 4, Section 4.6.2. OpenSearch.org.
[ORIGIN]
(Non-normative) The Web Origin Concept, A. Barth. IETF.
[PAINTTIMING]
Paint Timing, S. Panicker. W3C.
[PAGEVIS]
(Non-normative) Page Visibility Level 2, I. Grigorik, A. Jain, J. Mann. W3C.
[PAYMENTREQUEST]
Payment Request API, M. Cáceres, D. Wang, R. Solomakhin, I. Jacobs. W3C.
[PDF]
(Non-normative) Document management — Portable document format — Part 1: PDF. ISO.
[PERMISSIONSPOLICY]
Permissions Policy, I. Clelland, W3C.
[PINGBACK]
Pingback 1.0, S. Langridge, I. Hickson.
[PNG]
Portable Network Graphics (PNG) Specification, D. Duce. W3C.
[POINTEREVENTS]
Pointer Events, J. Rossi, M. Brubeck, R. Byers, P. H. Lauke. W3C.
[POINTERLOCK]
Pointer Lock, V. Scheib. W3C.
[PPUTF8]
(Non-normative) The Properties and Promises of UTF-8, M. Dürst. University of Zürich. In Proceedings of the 11th International Unicode Conference.
[PRELOAD]
Preload, I. Grigorik. W3C.
[PRESENTATION]
Presentation API, M. Foltz, D. Röttsches. W3C.
[REFERRERPOLICY]
Referrer Policy, J. Eisinger, E. Stark. W3C.
[REQUESTIDLECALLBACK]
Cooperative Scheduling of Background Tasks, R. McIlroy, I. Grigorik. W3C.
[RESOURCEHINTS]
Resource Hints, I. Grigorik. W3C.
[RFC1034]
Domain Names - Concepts and Facilities, P. Mockapetris. IETF, November 1987.
[RFC1123]
Requirements for Internet Hosts -- Application and Support, R. Braden. IETF, October 1989.
[RFC2046]
Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types, N. Freed, N. Borenstein. IETF.
[RFC2397]
The "data" URL scheme, L. Masinter. IETF.
[RFC5545]
Internet Calendaring and Scheduling Core Object Specification (iCalendar), B. Desruisseaux. IETF.
[RFC2483]
URI Resolution Services Necessary for URN Resolution, M. Mealling, R. Daniel. IETF.
[RFC3676]
The Text/Plain Format and DelSp Parameters, R. Gellens. IETF.
[RFC3864]
Registration Procedures for Message Header Fields, G. Klyne, M. Nottingham, J. Mogul. IETF.
[RFC4329]
(Non-normative) Scripting Media Types, B. Höhrmann. IETF.
[RFC4337]
(Non-normative) MIME Type Registration for MPEG-4, Y. Lim, D. Singer. IETF.
[RFC7595]
Guidelines and Registration Procedures for URI Schemes, D. Thaler, T. Hansen, T. Hardie. IETF.
[RFC5322]
Internet Message Format, P. Resnick. IETF.
[RFC6381]
The 'Codecs' and 'Profiles' Parameters for "Bucket" Media Types, R. Gellens, D. Singer, P. Frojdh. IETF.
[RFC6266]
Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP), J. Reschke. IETF.
[RFC6350]
vCard Format Specification, S. Perreault. IETF.
[RFC6596]
The Canonical Link Relation, M. Ohye, J. Kupke. IETF.
[RFC7034]
(Non-normative) HTTP Header Field X-Frame-Options, D. Ross, T. Gondrom. IETF.
[RFC7303]
XML Media Types, H. Thompson, C. Lilley. IETF.
[RFC7578]
Returning Values from Forms: multipart/form-data, L. Masinter. IETF.
[SCREENORIENTATION]
Screen Orientation API, M. Lamouri, M. Cáceres. W3C.
[SCSU]
(Non-normative) UTR #6: A Standard Compression Scheme For Unicode, M. Wolf, K. Whistler, C. Wicksteed, M. Davis, A. Freytag, M. Scherer. Unicode Consortium.
[SECURE-CONTEXTS]
Secure Contexts, M. West. W3C.
[SELECTION]
Selection API, R. Niwa. W3C.
[SELECTORS]
Selectors, E. Etemad, T. Çelik, D. Glazman, I. Hickson, P. Linss, J. Williams. W3C.
[SMS]
(Non-normative) URI Scheme for Global System for Mobile Communications (GSM) Short Message Service (SMS), E. Wilde, A. Vaha-Sipila. IETF.
[STRUCTURED-FIELDS]
Structured Field Values for HTTP, M. Nottingham, P-H. Kamp. IETF.
[SRGB]
IEC 61966-2-1: Multimedia systems and equipment — Colour measurement and management — Part 2-1: Colour management — Default RGB colour space — sRGB. IEC.
[SRI]
Subresource Integrity, D. Akhawe, F. Braun, F. Marier, J. Weinberger. W3C.
[STORAGE]
Storage, A. van Kesteren. WHATWG.
[SVG]
Scalable Vector Graphics (SVG) 2, N Andronikos, R. Atanassov, T. Bah, B. Birtles, B. Brinza, C. Concolato, E. Dahlström, C. Lilley, C. McCormack, D. Schepers, R. Schwerdtfeger, D. Storey, S. Takagi, J. Watt. W3C.
[SW]
Service Workers, A. Russell, J. Song, J. Archibald. W3C.
[TOR]
(Non-normative) Tor.
[TOUCH]
Touch Events, D. Schepers, S. Moon, M. Brubeck, A. Barstow, R. Byers. W3C.
[TZDATABASE]
(Non-normative) Time Zone Database. IANA.
[UAAG]
(Non-normative) User Agent Accessibility Guidelines (UAAG) 2.0, J. Allan, K. Ford, J. Richards, J. Spellman. W3C.
[UIEVENTS]
UI Events Specification, G. Kacmarcik, T. Leithead. W3C.
[UNICODE]
The Unicode Standard. Unicode Consortium.
[UNIVCHARDET]
(Non-normative) A composite approach to language/encoding detection, S. Li, K. Momoi. Netscape. In Proceedings of the 19th International Unicode Conference.
[URL]
URL, A. van Kesteren. WHATWG.
[URN]
URN Syntax, R. Moats. IETF.
[UTF7]
(Non-normative) UTF-7: A Mail-Safe Transformation Format of Unicode, D. Goldsmith, M. Davis. IETF.
[UTF8DET]
(Non-normative) Multilingual form encoding, M. Dürst. W3C.
[UTR36]
(Non-normative) UTR #36: Unicode Security Considerations, M. Davis, M. Suignard. Unicode Consortium.
[WASMJS]
(Non-normative) WebAssembly JavaScript Interface, D. Ehrenberg. W3C.
[WCAG]
(Non-normative) Web Content Accessibility Guidelines (WCAG) 2.0, B. Caldwell, M. Cooper, L. Reid, G. Vanderheiden. W3C.
[WEBANIMATIONS]
Web Animations, B. Birtles, S. Stephens, D. Stockwell. W3C.
[WEBAUDIO]
(Non-normative) Web Audio API, P. Adenot, H. Choi. W3C.
[WEBCRYPTO]
(Non-normative) Web Cryptography API, M. Watson. W3C.
[WEBGL]
WebGL Specifications, D. Jackson, J. Gilbert. Khronos Group.
[WEBIDL]
Web IDL, C. McCormack. W3C.
Web Linking, M. Nottingham. IETF.
[WEBMCG]
WebM Container Guidelines. The WebM Project.
[WEBVTT]
WebVTT, S. Pieters. W3C.
[WHATWGWIKI]
The WHATWG Wiki. WHATWG.
[WSP]
The WebSocket protocol, I. Fette, A. Melnikov. IETF.
[X121]
Recommendation X.121 — International Numbering Plan for Public Data Networks, CCITT Blue Book, Fascicle VIII.3, pp. 317-332.
[XFN]
XFN 1.1 profile, T. Çelik, M. Mullenweg, E. Meyer. GMPG.
[XHR]
XMLHttpRequest, A. van Kesteren. WHATWG.
[XKCD1288]
(Non-normative) Substitutions, Randall Munroe. xkcd.
[XML]
Extensible Markup Language, T. Bray, J. Paoli, C. Sperberg-McQueen, E. Maler, F. Yergeau. W3C.
[XMLENTITY]
(Non-normative) XML Entity Definitions for Characters, D. Carlisle, P. Ion. W3C.
[XMLNS]
Namespaces in XML, T. Bray, D. Hollander, A. Layman, R. Tobin. W3C.
[XMLSSPI]
Associating Style Sheets with XML documents, J. Clark, S. Pieters, H. Thompson. W3C.
[XPATH10]
XML Path Language (XPath) Version 1.0, J. Clark, S. DeRose. W3C.
[XSLT10]
(Non-normative) XSL Transformations (XSLT) Version 1.0, J. Clark. W3C.
[XSLTP]
(Non-normative) DOM XSLTProcessor, WHATWG Wiki. WHATWG.

致谢

感谢 Tim Berners-Lee 发明了HTML,没有他,这一切都不会存在

感谢 Aankhen, Aaqa Ishtyaq, Aaron Boodman, Aaron Leventhal, Abhishek Gupta, Adam Barth, Adam de Boor, Adam Hepton, Adam Klein, Adam Roben, Addison Phillips, Adele Peterson, Adrian Bateman, Adrian Roselli, Adrian Sutton, Agustín Fernández, Aharon (Vladimir) Lanin, Ajai Tirumali, Ajay Poshak, Akatsuki Kitamura, Alan Plum, Alastair Campbell, Alejandro G. Castro, Alex Bishop, Alex Nicolaou, Alex Nozdriukhin, Alex Rousskov, Alexander Farkas, Alexander J. Vincent, Alexandre Dieulot, Alexandre Morgaut, Alexey Feldgendler, Алексей Проскуряков (Alexey Proskuryakov), Alexey Shvayka, Alexis Deveria, Alfred Agrell, Ali Juma, Alice Boxhall, Alice Wonder, Allan Clements, Allen Wirfs-Brock, Alex Komoroske, Alex Russell, Alphan Chen, Aman Ansari, Ami Fischman, Amos Jeffries, Amos Lim, Anders Carlsson, André Bargull, André E. Veltstra, Andrea Rendine, Andreas, Andreas Deuschlinger, Andreas Kling, Andrei Popescu, Andres Gomez, Andres Rios, Andreu Botella, Andrew Barfield, Andrew Clover, Andrew Gove, Andrew Grieve, Andrew Macpherson, Andrew Oakley, Andrew Sidwell, Andrew Simons, Andrew Smith, Andrew W. Hagen, Andrey V. Lukyanov, Andry Rendy, Andy Davies, Andy Earnshaw, Andy Heydon, Andy Paicu, Andy Palay, Anjana Vakil, Ankur Kaushal, Anna Belle Leiserson, Anthony Boyd, Anthony Bryan, Anthony Hickson, Anthony Ramine, Anthony Ricaud, Anton Vayvod, Antti Koivisto, Arfat Salman, Arkadiusz Michalski, Arne Thomassen, Aron Spohr, Arphen Lin, Arthur Stolyar, Arun Patole, Aryeh Gregor, Asbjørn Ulsberg, Ashley Gullen, Ashley Sheridan, Atsushi Takayama, Attila Haraszti, Aurelien Levy, Ave Wrigley, Avi Drissman, Axel Dahmen, Ben Boyle, Ben Godfrey, Ben Golightly, Ben Kelly, Ben Lerner, Ben Leslie, Ben Meadowcroft, Ben Millard, Benjamin Carl Wiley Sittler, Benjamin Hawkes-Lewis, Benji Bilheimer, Benoit Ren, Bert Bos, Bijan Parsia, Bil Corry, Bill Mason, Bill McCoy, Billy Wong, Billy Woods, Bjartur Thorlacius, Björn Höhrmann, Blake Frantz, Bob Lund, Bob Owen, Bobby Holley, Boris Zbarsky, Brad Fults, Brad Neuberg, Brad Spencer, Bradley Meck, Brady Eidson, Brandon Jones, Brendan Eich, Brenton Simpson, Brett Wilson, Brett Zamir, Brian Birtles, Brian Blakely, Brian Campbell, Brian Korver, Brian Kuhn, Brian M. Dube, Brian Ryner, Brian Smith, Brian Wilson, Bryan Sullivan, Bruce Bailey, Bruce D'Arcus, Bruce Lawson, Bruce Miller, Bugs Nash, C. Scott Ananian, C. Williams, Cameron McCormack, Cameron Zemek, Cao Yipeng, Carlos Amengual, Carlos Gabriel Cardona, Carlos Perelló Marín, Carolyn MacLeod, Casey Leask, Cătălin Badea, Cătălin Mariș, Cem Turesoy, ceving, Chao Cai, 윤석찬 (Channy Yun), Charl van Niekerk, Charlene Wright, Charles Iliya Krempeaux, Charles McCathie Nevile, Charlie Reis, 白丞祐 (Cheng-You Bai), Chris Apers, Chris Cressman, Chris Dumez, Chris Evans, Chris Harrelson, Chris Markiewicz, Chris Morris, Chris Nardi, Chris Needham, Chris Pearce, Chris Peterson, Chris Rebert, Chris Weber, Chris Wilson, Christian Biesinger, Christian Johansen, Christian Schmidt, Christoph Päper, Christophe Dumez, Christopher Aillon, Christopher Ferris, Chriswa, Clark Buehler, Cole Robison, Colin Fine, Collin Jackson, Corey Farwell, Corprew Reed, Craig Cockburn, Csaba Gabor, Csaba Marton, Cynthia Shelly, Cyrille Tuzi, Daksh Shah, Dan Callahan, Dan Yoder, Dane Foster, Daniel Barclay, Daniel Bratell, Daniel Brooks, Daniel Brumbaugh Keeney, Daniel Buchner, Daniel Cheng, Daniel Clark, Daniel Davis, Daniel Ehrenberg, Daniel Glazman, Daniel Holbert, Daniel Peng, Daniel Schattenkirchner, Daniel Spång, Daniel Steinberg, Daniel Tan, Daniel Trebbien, Danny Sullivan, Daphne Preston-Kendal, Darien Maillet Valentine, Darin Adler, Darin Fisher, Darxus, Dave Camp, Dave Cramer, Dave Hodder, Dave Lampton, Dave Singer, Dave Tapuska, Dave Townsend, David Baron, David Bloom, David Bruant, David Carlisle, David E. Cleary, David Egan Evans, David Fink, David Flanagan, David Gerard, David Grogan, David Håsäther, David Hyatt, David I. Lehn, David John Burrowes, David Matja, David Remahl, David Resseguie, David Smith, David Storey, David Vest, David Woolley, David Zbarsky, Dave Methvin, DeWitt Clinton, Dean Edridge, Dean Edwards, Dean Jackson, Debi Orton, Delan Azabani, Derek Featherstone, Derek Guenther, Devarshi Pant, Devdatta, Diego Ferreiro Val, Diego Ponce de León, Dimitri Glazkov, Dimitry Golubovsky, Dirk Pranke, Dirk Schulze, Dirkjan Ochtman, Divya Manian, Dmitry Lazutkin, Dmitry Titov, dolphinling, Dominic Cooney, Dominic Farolino, Dominique Hazaël-Massieux, Don Brutzman, Donovan Glover, Doron Rosenberg, Doug Kramer, Doug Simpkinson, Drew Wilson, Edgar Chen, Edmund Lai, Eduard Pascual, Eduardo Vela, Edward Welbourne, Edward Z. Yang, Ehsan Akhgari, Eira Monstad, Eitan Adler, Eli Friedman, Eli Grey, Eliot Graff, Elisabeth Robson, Elizabeth Castro, Elliott Sprehn, Elliotte Harold, Emilio Cobos Álvarez, Emily Stark, Eric Carlson, Eric Casler, Eric Lawrence, Eric Portis, Eric Rescorla, Eric Semling, Eric Willigers, Erik Arvidsson, Erik Charlebois, Erik Rose, 栗本 英理子 (Eriko Kurimoto), espretto, Evan Jacobs, Evan Martin, Evan Prodromou, Evan Stade, Evert, Evgeny Kapun, ExE-Boss, Ezequiel Garzón, fantasai, Félix Sanz, Felix Sasaki, Fernando Altomare Serboncini, Forbes Lindesay, Francesco Schwarz, Francis Brosnan Blazquez, Franck 'Shift' Quélain, François Marier, Frank Barchard, Frank Liberato, Fredrik Söderquist, 鵜飼文敏 (Fumitoshi Ukai), Futomi Hatano, Gavin Carothers, Gavin Kistner, Gareth Rees, Garrett Smith, Gary Blackwood, Gary Kacmarcik, Gary Katsevman, Geoff Richards, Geoffrey Garen, Georg Neis, George Lund, Gianmarco Armellin, Giovanni Campagna, Giuseppe Pascale, Glenn Adams, Glenn Maynard, Graham Klyne, Greg Botten, Greg Houston, Greg Wilkins, Gregg Tavares, Gregory J. Rosmaita, Gregory Terzian, Grey, Guilherme Johansson Tramontina, guest271314, Gytis Jakutonis, Håkon Wium Lie, Habib Virji, Hajime Morrita, Hallvord Reiar Michaelsen Steen, Hanna Laakso, Hans S. Tømmerhalt, Hans Stimer, Harald Alvestrand, Hayato Ito, 何志翔 (HE Zhixiang), Henri Sivonen, Henrik Lied, Henry Lewis, Henry Mason, Henry Story, Hermann Donfack Zeufack, 中川博貴 (Hiroki Nakagawa), Hiroshige Hayashizaki, Hitoshi Yoshida, Hongchan Choi, Hugh Bellamy, Hugh Guiney, Hugh Winkler, Ian Bicking, Ian Clelland, Ian Davis, Ian Fette, Ian Henderson, Ian Kilpatrick, Ibrahim Ahmed, Ido Green, Ignacio Javier, Igor Oliveira, Ingvar Stepanyan, isonmad, Iurii Kucherov, Ivan Enderlin, Ivan Nikulin, Ivo Emanuel Gonçalves, J. King, J.C. Jones, Jackson Ray Hamilton, Jacob Davies, Jacques Distler, Jake Archibald, Jake Verbaten, Jakub Vrána, Jakub Łopuszański, Jakub Wilk, James Craig, James Graham, James Greene, James Justin Harrell, James Kozianski, James M Snell, James Perrett, James Robinson, Jamie Liu, Jamie Lokier, Jan Kühle, Jan Miksovsky, Janice Shiu, Janusz Majnert, Jan-Ivar Bruaroey, Jan-Klaas Kollhof, Jared Jacobs, Jason Duell, Jason Kersey, Jason Lustig, Jason Orendorff, Jason White, Jasper Bryant-Greene, Jasper St. Pierre, Jatinder Mann, Jean-Yves Avenard, Jed Hartman, Jeff Balogh, Jeff Cutsinger, Jeff "=JeffH" Hodges, Jeff Schiller, Jeff Walden, Jeffrey Yasskin, Jeffrey Zeldman, 胡慧鋒 (Jennifer Braithwaite), Jellybean Stonerfish, Jennifer Apacible, Jens Bannmann, Jens Fendler, Jens Oliver Meiert, Jens Widell, Jer Noble, Jeremey Hustman, Jeremy Keith, Jeremy Orlow, Jeremy Roman, Jeroen van der Meer, Jerry Smith, Jesse Renée Beach, Jessica Jong, jfkthame, Jian Li, Jihye Hong, Jim Jewett, Jim Ley, Jim Meehan, Jim Michaels, Jinho Bang, Jinjiang (勾三股四), Jirka Kosek, Jjgod Jiang, Joaquim Medeiros, João Eiras, Jochen Eisinger, Joe Clark, Joe Gregorio, Joel Spolsky, Joel Verhagen, Joey Arhar, Johan Herland, Johanna Herman, John Boyer, John Bussjaeger, John Carpenter, John Daggett, John Fallows, John Foliot, John Harding, John Keiser, John Law, John Musgrave, John Snyders, John Stockton, John-Mark Bell, Johnny Stenback, Jon Coppeard, Jon Ferraiolo, Jon Gibbins, Jon Perlow, Jonas Sicking, Jonathan Cook, Jonathan Neal, Jonathan Oddy, Jonathan Rees, Jonathan Watt, Jonathan Worent, Jonny Axelsson, Joram Schrijver, Jordan Tucker, Jorgen Horstink, Joris van der Wel, Jorunn Danielsen Newth, Joseph Kesselman, Joseph Mansfield, Joseph Pecoraro, Josh Aas, Josh Hart, Josh Juran, Josh Levenberg, Josh Matthews, Joshua Bell, Joshua Randall, Juan Olvera, Juanmi Huertas, Jukka K. Korpela, Jules Clément-Ripoche, Julian Reschke, Julio Lopez, 小勝 純 (Jun Kokatsu), Jun Yang (harttle), Jungkee Song, Jürgen Jeka, Justin Lebar, Justin Novosad, Justin Rogers, Justin Schuh, Justin Sinclair, Juuso Lapinlampi, Ka-Sing Chou, Kagami Sascha Rosylight, Kai Hendry, Kamishetty Sreeja, 呂康豪 (KangHao Lu), Karl Dubost, Karl Tomlinson, Kartik Arora, Kartikaya Gupta, 葛依寧 (Kat Hackett), Kathy Walton, Keith Rollin, Keith Yeung, Kelly Ford, Kelly Norton, Ken Russell, Kenji Baheux, Kevin Benson, Kevin Cole, Kevin Gadd, Kevin Venkiteswaran, Kinuko Yasuda, Koji Ishii, Kornél Pál, Kornel Lesinski, 上野 康平 (UENO, Kouhei), Kris Northfield, Kristof Zelechovski, Krzysztof Maczyński, 黒澤剛志 (Kurosawa Takeshi), Kyle Barnhart, Kyle Hofmann, Kyle Huey, Léonard Bouchet, Léonie Watson, Lachlan Hunt, Larry Masinter, Larry Page, Lars Gunther, Lars Solberg, Laura Carlson, Laura Granka, Laura L. Carlson, Laura Wisewell, Laurens Holst, Lawrence Forooghian, Lee Kowalkowski, Leif Halvard Silli, Leif Kornstaedt, Lenny Domnitser, Leonard Rosenthol, Leons Petrazickis, Lobotom Dysmon, Logan, Loune, Lucas Gadani, Łukasz Pilorz, Luke Kenneth Casson Leighton, Maciej Stachowiak, Magne Andersson, Magnus Kristiansen, Maik Merten, Majid Valipour, Malcolm Rowe, Manish Goregaokar, Manish Tripathi, Manuel Martinez-Almeida, Marc Hoyois, Marc-André Choquette, Marc-André Lafortune, Marco Zehe, Marcus Bointon, Marijn Kruisselbrink, Mark Amery, Mark Birbeck, Mark Davis, Mark Green, Mark Miller, Mark Nottingham, Mark Pilgrim, Mark Rogers, Mark Rowe, Mark Schenk, Mark Vickers, Mark Wilton-Jones, Markus Stange, Martijn van der Ven, Martijn Wargers, Martin Atkins, Martin Chaov, Martin Dürst, Martin Honnen, Martin Janecke, Martin Kutschker, Martin Nilsson, Martin Thomson, Masataka Yakura, Masatoshi Kimura, Mason Freed, Mason Mize, Mathias Bynens, Mathieu Henri, Matias Larsson, Matt Brubeck, Matt Di Pasquale, Matt Falkenhagen, Matt Schmidt, Matt Wright, Matthew Gregan, Matthew Mastracci, Matthew Noorenberghe, Matthew Raymond, Matthew Thomas, Matthew Tylee Atkinson, Mattias Waldau, Max Romantschuk, Maxim Tsoy, Menachem Salomon, Menno van Slooten, Micah Dubinko, Michael 'Ratt' Iannarelli, Michael A. Nachbaur, Michael A. Puls II, Michael Carter, Michael Daskalov, Michael Day, Michael Dyck, Michael Enright, Michael Gratton, Michael Kohler, Michael McKelvey, Michael Nordman, Michael Powers, Michael Rakowski, Michael(tm) Smith, Michael Walmsley, Michal Zalewski, Michel Buffa, Michel Fortin, Michelangelo De Simone, Michiel van der Blonk, Miguel Casas-Sanchez, Mihai Şucan, Mihai Parparita, Mike Brown, Mike Dierken, Mike Dixon, Mike Hearn, Mike Pennisi, Mike Schinkel, Mike Shaver, Mikko Rantalainen, Mingye Wang, Mohamed Zergaoui, Mohammad Al Houssami, Mohammad Reza Zakerinasab, Momdo Nakamura, Morten Stenshorne, Mounir Lamouri, Ms2ger, mtrootyy, 邱慕安 (Mu-An Chiou), Mukilan Thiyagarajan, Mustaq Ahmed, Myles Borins, Nadia Heninger, NARUSE Yui, Navid Zolghadr, Neil Deakin, Neil Rashbrook, Neil Soiffer, Nicholas Shanks, Nicholas Stimpson, Nicholas Zakas, Nickolay Ponomarev, Nicolas Gallagher, Nicolas Pena Moreno, Nikki Bee, Noah Mendelsohn, Noah Slater, Noel Gordon, Nolan Waite, NoozNooz42, Norbert Lindenberg, Oisín Nolan, Ojan Vafai, Olaf Hoffmann, Olav Junker Kjær, Oldřich Vetešník, Oli Studholme, Oliver Hunt, Oliver Rigby, Olivia (Xiaoni) Lai, Olivier Gendrin, Olli Pettay, Ondřej Žára, Ori Avtalion, oSand, Pablo Flouret, Patrick Dark, Patrick Garies, Patrick H. Lauke, Patrik Persson, Paul Adenot, Paul Lewis, Paul Norman, Per-Erik Brodin, 一丝 (percyley), Perry Smith, Peter Beverloo, Peter Karlsson, Peter Kasting, Peter Moulder, Peter Occil, Peter Stark, Peter Van der Beken, Peter van der Zee, Peter-Paul Koch, Phil Pickering, Philip Ahlberg, Philip Taylor, Philip TAYLOR, Philippe De Ryck, Pierre-Arnaud Allumé, Pierre-Marie Dartus, ‏ Pooja Sanklecha, Prashant Hiremath, Prashanth Chandra, Prateek Rungta, Pravir Gupta, Prayag Verma, 李普君 (Pujun Li), Rachid Finge, Rafael Weinstein, Rafał Miłecki, Rahul Purohit, Raj Doshi, Rajas Moonka, Rakina Zata Amni, Ralf Stoltze, Ralph Giles, Raphael Champeimont, Rebecca Star, Remci Mizkur, Remco, Remy Sharp, Rene Saarsoo, Rene Stach, Ric Hardacre, Rich Clark, Rich Doughty, Richa Rupela, Richard Gibson, Richard Ishida, Ricky Mondello, Rigo Wenning, Rikkert Koppes, Rimantas Liubertas, Riona Macnamara, Rob Buis, Rob Ennals, Rob Jellinghaus, Rob S, Robert Blaut, Robert Collins, Robert Hogan, Robert Kieffer, Robert Linder, Robert Millan, Robert O'Callahan, Robert Sayre, Robin Berjon, Robin Schaufler, Rodger Combs, Roland Steiner, Roma Matusevich, Roman Ivanov, Roy Fielding, Rune Lillesveen, Russell Bicknell, Ruud Steltenpool, Ryan King, Ryan Landay, Ryan Sleevi, Ryo Kato, Ryosuke Niwa, S. Mike Dierken, Salvatore Loreto, Sam Dutton, Sam Kuper, Sam Ruby, Sam Sneddon, Sam Weinig, Samikshya Chand, Samuel Bronson, Samy Kamkar, Sander van Lambalgen, Sanjoy Pal, Sarah Gebauer, Sarven Capadisli, Schalk Neethling, Scott Beardsley, Scott González, Scott Hess, Scott Miles, Scott O'Hara, Sean B. Palmer, Sean Feng, Sean Fraser, Sean Hayes, Sean Hogan, Sean Knapp, Sebastian Markbåge, Sebastian Schnitzenbaumer, Sendil Kumar N, Seth Call, Seth Dillingham, Shannon Moeller, Shanti Rao, Shaun Inman, Shiino Yuki, 贺师俊 (HE Shi-Jun), Shiki Okasaka, Shivani Sharma, shreyateeza, Shubheksha Jalan, Sidak Singh Aulakh, Sierk Bornemann, Sigbjørn Finne, Sigbjørn Vik, Silver Ghost, Silvia Pfeiffer, Šime Vidas, Simon Fraser, Simon Montagu, Simon Sapin, Simon Spiegel, skeww, Smylers, Srirama Chandra Sekhar Mogali, Stanton McCandlish, stasoid, Stefan Håkansson, Stefan Haustein, Stefan Santesson, Stefan Schumacher, Ştefan Vargyas, Stefan Weiss, Steffen Meschkat, Stephen Ma, Stephen Stewart, Stephen White, Steve Comstock, Steve Faulkner, Steve Orvell, Steve Runyon, Steven Bennett, Steven Bingler, Steven Garrity, Steven Tate, Stewart Brodie, Stuart Ballard, Stuart Langridge, Stuart Parmenter, Subramanian Peruvemba, Sudhanshu Jaiswal, sudokus999, Sunava Dutta, Surma, Susan Borgrink, Susan Lesch, Sylvain Pasche, T. J. Crowder, Tab Atkins-Bittner, Taiju Tsuiki, Takashi Toyoshima, Takayoshi Kochi, Takeshi Yoshino, Tantek Çelik, 田村健人 (Kent TAMURA), Taylor Hunt, Ted Mielczarek, Terrence Wood, Tetsuharu OHZEKI, Theresa O'Connor, Thijs van der Vossen, Thomas Broyer, Thomas Koetter, Thomas O'Connor, Tim Altman, Tim Dresser, Tim Johansson, Tim Perry, Tim van der Lippe, TJ VanToll, Tobias Schneider, Tobie Langel, Toby Inkster, Todd Moody, Tom Baker, Tom Pike, Tom Schuster, Tom ten Thij, Tomasz Jakut, Tomek Wytrębowicz, Tommy Thorsen, Tony Ross, Tooru Fujisawa, Toru Kobayashi, Travis Leithead, Trevor Rowbotham, Trevor Saunders, Trey Eckels, triple-underscore, Tristan Fraipont, Tyler Close, Valentin Gosu, Vardhan Gupta, Veli Şenol, Victor Carbune, Victor Costan, Vipul Snehadeep Chawathe, Vitya Muhachev, Vlad Levin, Vladimir Katardjiev, Vladimir Vukićević, Vyacheslav Aristov, voracity, Walter Steiner, Wakaba, Wayne Carr, Wayne Pollock, Wellington Fernando de Macedo, Weston Ruter, Wilhelm Joys Andersen, Will Levine, Will Ray, William Chen, William Swanson, Willy Martin Aguirre Rodriguez, Wladimir Palant, Wojciech Mach, Wolfram Kriesing, Xan Gregg, xenotheme, XhmikosR, Xida Chen, Xidorn Quan, Xue Fuqiao, Yang Chen, Yao Xiao, Yash Handa, Yay295, Ye-Kui Wang, Yehuda Katz, Yi Xu, Yi-An Huang, Yngve Nysaeter Pettersen, Yoav Weiss, Yonathan Randolph, Yury Delendik, 平野裕 (Yutaka Hirano), Yuzo Fujishima, Zhenbin Xu, 张智强 (Zhiqiang Zhang), Zoltan Herczeg, and Øistein E. Andersen, for their useful comments, both large and small, that have led to changes to this specification over the years.

Thanks also to everyone who has ever posted about HTML to their blogs, public mailing lists, or forums, including all the contributors to the various W3C HTML WG lists and the various WHATWG lists.

Special thanks to Richard Williamson for creating the first implementation of canvas in Safari, from which the canvas feature was designed.

Special thanks also to the Microsoft employees who first implemented the event-based drag-and-drop mechanism, contenteditable, and other features first widely deployed by the Windows Internet Explorer browser.

Special thanks and $10,000 to David Hyatt who came up with a broken implementation of the adoption agency algorithm that the editor had to reverse engineer and fix before using it in the parsing section.

Thanks to the participants of the microdata usability study for allowing us to use their mistakes as a guide for designing the microdata feature.

Thanks to the many sources that provided inspiration for the examples used in the specification.

Thanks also to the Microsoft blogging community for some ideas, to the attendees of the W3C Workshop on Web Applications and Compound Documents for inspiration, to the #mrt crew, the #mrt.no crew, and the #whatwg crew, and to Pillar and Hedral for their ideas and support.

Thanks to Igor Zhbanov for generating PDF versions of the specification.

Special thanks to the RICG for developing the picture element and related features; in particular thanks to Adrian Bateman, Bruce Lawson, David Newton, Ilya Grigorik, John Schoenick, Leon de Rijke, Mat Marquis, Marcos Cáceres, Tab Atkins, Theresa O'Connor, and Yoav Weiss for their contributions.

Special thanks to the WPWG for incubating the custom elements feature. In particular, thanks to David Hyatt and Ian Hickson for their influence through the XBL specifications, Dimitri Glazkov for the first draft of the custom elements specification, and to Alex Komoroske, Alex Russell, Andres Rios, Boris Zbarsky, Brian Kardell, Daniel Buchner, Dominic Cooney, Erik Arvidsson, Elliott Sprehn, Hajime Morrita, Hayato Ito, Jan Miksovsky, Jonas Sicking, Olli Pettay, Rafael Weinstein, Roland Steiner, Ryosuke Niwa, Scott Miles, Steve Faulkner, Steve Orvell, Tab Atkins, Theresa O'Connor, Tim Perry, and William Chen for their contributions.

Special thanks to the CSSWG for developing the worklets. In particular, thanks to Ian Kilpatrik for his work as editor of the original worklets specification.

For about ten years starting in 2003, this standard was almost entirely written by Ian Hickson (Google, ian@hixie.ch). More recently, Simon Pieters (Bocoup, zcorpan@gmail.com), Anne van Kesteren (Mozilla, annevk@annevk.nl), Philip Jägenstedt (Google, philip@foolip.org), and Domenic Denicola (Google, d@domenic.me), all previously long-time contributors, have joined Ian in editing the text directly.

Intellectual property rights

The image in the introduction is based on a photo by Wonderlane. (CC BY 2.0)

The image of the wolf in the embedded content introduction is based on a photo by Barry O'Neill. (Public domain)

The image of the kettlebell swing in the embedded content introduction is based on a photo by kokkarina. (CC0 1.0)

The Blue Robot Player sprite used in the canvas demo is based on a work by JohnColburn. (CC BY-SA 3.0)

The photograph of robot 148 climbing the tower at the FIRST Robotics Competition 2013 Silicon Valley Regional is based on a work by Lenore Edman. (CC BY 2.0)

The diagram showing how async and defer impact script loading is based on a similar diagram from a blog post by Peter Beverloo. (CC0 1.0)

The image decoding demo used to demonstrate module-based workers draws on some example code from a tutorial by Ilmari Heikkinen. (CC BY 3.0)

The <flag-icon> example was inspired by a custom element by Steven Skelton. (MIT)

Part of the revision history of the picture element and related features can be found in the ResponsiveImagesCG/picture-element repository, which is available under the W3C Software and Document License.

Part of the revision history of the theme-color metadata name can be found in the whatwg/meta-theme-color repository, which is available under CC0.

Part of the revision history of the custom elements feature can be found in the w3c/webcomponents repository, which is available under the W3C Software and Document License.

Part of the revision history of the innerText getter and setter can be found in the rocallahan/innerText-spec repository, which is available under CC0.

Part of the revision history of the worklets feature can be found in the w3c/css-houdini-drafts repository, which is available under the W3C Software and Document License.

Copyright © WHATWG (Apple, Google, Mozilla, Microsoft). This work is licensed under a Creative Commons Attribution 4.0 International License.

This is the Living Standard. Those interested in the patent-review version should view the Living Standard Review Draft.