I'm trying to create a simple web page that can read and write NFC tags. I also would like to have the functionality to cancel the write operation if need be. so I was following the examples here and here. however, I ran into a problem where the abort signal is being ignored. this simple code can demonstrate the problem:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script>
let data;
let reset_controller = new AbortController();
let ndef;
try {
ndef = new window.NDEFReader();
ndef.addEventListener("readingerror", async () => {
log_error('Cannot read data from the NFC tag.');
});
ndef.addEventListener("reading", async ({message, serialNumber}) => {
data = new TextDecoder('utf-8').decode(message.records[0].data.buffer);
draw_info();
});
} catch (error) {
console.error(error);
}
function draw_info() {
document.getElementById('data').innerHTML = `data is: ${data}`;
}
function reset() {
console.log('Aborted!')
reset_controller.abort();
document.getElementById('data').innerHTML = '';
}
async function read_data() {
data = await ndef.scan();
draw_info();
}
async function write_data() {
console.log('stating write')
try {
await ndef.write("some data", {
AbortSignal: reset_controller.signal
});
} catch (e) {
console.error(e);
}
}
</script>
</head>
<body>
<button onclick="read_data()">Read</button>
<button onclick="write_data()">Write</button>
<button onclick="reset()">Rest</button>
<p id="data">data is: </p>
</body>
</html>
to repeat the problem:
1- click on the write button.
2- click on reset to cancel the write.
- approach a tag.
the tag now contains the string 'some data' where it shouldn't
ok, I have found the problem.
when we pass the options object to the write function, the abort signal should be placed at 'signal' attribute not 'AbortSignal'