大网数据广告活动
Web 标准与前端开发

NDEFRecord: toRecords() method

· 52CE 我爱测

The **`toRecords()`** method of the NDEFRecord interface converts NDEFRecord.data to a sequence of records based on NDEFRecord.recordType, and returns the result. This allows parsing the payloads of record types which may contain nested records, such as smart poster and external

Web NFC API

The toRecords() method of the NDEFRecord interface converts NDEFRecord.data to a sequence of records based on NDEFRecord.recordType, and returns the result. This allows parsing the payloads of record types which may contain nested records, such as smart poster and external type records.

Syntax

toRecords()

Parameters

None.

Return value

A list of NDEFRecords.

Exceptions

  • NotSupportedError DOMException
    • : Indicates that the User Agent does not know how to parse this combination of NDEFRecord.data and NDEFRecord.recordType.

Examples

Read an external record with an NDEF message as payload

The example uses external type records to create application-defined records. These records may contain an NDEFMessage as payload, with its own NDEFRecord objects, including local types that are used in the context of the application. Notice that the smart poster record type also contains an NDEF message as payload.

Because NDEF gives no guarantee on the ordering of records, using an external type record with an NDEF message as payload can be useful for encapsulating related data.

This example shows how to read an external record for social posts, which contains an NDEFMessage, containing a text record and a record with the local type "act" (action), with a definition borrowed from smart poster, but used in local application context.

const ndefReader = new NDEFReader();
await ndefReader.scan();
ndefReader.onreading = (event) => {
  const externalRecord = event.message.records.find(
    (record) => record.type === "example.com:smart-poster",
  );

  let action, text;

  for (const record of externalRecord.toRecords()) {
    if (record.recordType === "text") {
      const decoder = new TextDecoder(record.encoding);
      text = decoder.decode(record.data);
    } else if (record.recordType === ":act") {
      action = record.data.getUint8(0);
    }
  }

  switch (action) {
    case 0: // do the action
      console.log(`Post "${text}" to timeline`);
      break;
    case 1: // save for later
      console.log(`Save "${text}" as a draft`);
      break;
    case 2: // open for editing
      console.log(`Show editable post with "${text}"`);
      break;
  }
};

Specifications

Browser compatibility

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。