files/en-us/web/api/ndefreader/write/index.md
{{SecureContext_Header}}{{SeeCompatTable}}{{APIRef("Web NFC API")}}
The write() method of the {{DOMxRef("NDEFReader")}} interface attempts to write an NDEF message to a tag and returns a {{jsxref("Promise")}} that either resolves when a message has been written to the tag or rejects if a hardware or permission error is encountered. This method triggers a permission prompt if the "nfc" permission has not been previously granted.
write(message)
write(message, options)
message
data {{optional_inline}}
encoding {{optional_inline}}
id {{optional_inline}}
lang {{optional_inline}}
mediaType {{optional_inline}}
recordType
data. It must be one of the following values:
"absolute-url"
"empty"
"mime"
"smart-poster"
"text"
"unknown"
"URL"
options {{optional_inline}}
overwrite
signal {{optional_inline}}
A {{JSxRef("Promise")}} that either resolves when a message has been written to the tag or rejects if a hardware or permission error is encountered.
This method doesn't throw exceptions; instead, it rejects the returned promise,
passing a {{domxref("DOMException")}} whose name is one of the
following:
AbortError
options argument.NotAllowedError
overwrite is
false and there are already records on the tag.NotSupportedError
NotReadableError
NetworkError
The following example shows how to write a string to an NFC tag and process any errors that occur.
const ndef = new NDEFReader();
ndef
.write("Hello World")
.then(() => {
console.log("Message written.");
})
.catch((error) => {
console.log(`Write failed :-( try again: ${error}.`);
});
The following example shows how to write a record object (described above) to an NFC tag and process any errors that occur.
const ndef = new NDEFReader();
try {
await ndef.write({
records: [{ recordType: "url", data: "http://example.com/" }],
});
} catch {
console.log("Write failed :-( try again.");
}
It's sometimes useful to set a time limit on a write operation. For example, you ask the user to touch a tag, but no tag is found within a certain amount of time, then you time out.
const ndef = new NDEFReader();
ndef.onreading = (event) => console.log("We read a tag!");
function write(data, { timeout } = {}) {
return new Promise((resolve, reject) => {
const controller = new AbortController();
controller.signal.onabort = () =>
reject(new Error("Time is up, bailing out!"));
setTimeout(() => controller.abort(), timeout);
ndef.addEventListener(
"reading",
(event) => {
ndef.write(data, { signal: controller.signal }).then(resolve, reject);
},
{ once: true },
);
});
}
await ndef.scan();
try {
// Let's wait for 5 seconds only.
await write("Hello World", { timeout: 5_000 });
} catch (err) {
console.error("Something went wrong", err);
} finally {
console.log("We wrote to a tag!");
}
{{Specifications}}
{{Compat}}