files/en-us/web/api/ndefreader/index.md
{{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The NDEFReader interface of the Web NFC API is used to read from and write data to compatible NFC devices, e.g., NFC tags supporting NDEF, when these devices are within the reader's magnetic induction field.
{{InheritanceDiagram}}
NDEFReader object.The NDEFReader interface inherits the methods of {{domxref("EventTarget")}}, its parent interface.
Inherits events from its parent, {{DOMxRef("EventTarget")}}.
The example below shows how to coordinate between a common reading handler and one used specifically for a single write. In order to write, a tag needs to be found and read. This gives you the ability to check whether it is actually a tag that you want to write to. That's why it's recommended that you call write() from a reading event.
const ndef = new NDEFReader();
let ignoreRead = false;
ndef.onreading = (event) => {
if (ignoreRead) {
return; // write pending, ignore read.
}
console.log("We read a tag, but not during pending write!");
};
function write(data) {
ignoreRead = true;
return new Promise((resolve, reject) => {
ndef.addEventListener(
"reading",
(event) => {
// Check if we want to write to this tag, or reject.
ndef
.write(data)
.then(resolve, reject)
.finally(() => (ignoreRead = false));
},
{ once: true },
);
});
}
await ndef.scan();
try {
await write("Hello World");
console.log("We wrote to a tag!");
} catch (err) {
console.error("Something went wrong", err);
}
{{Specifications}}
{{Compat}}