I noticed recently an error popup in Chrome telling that navigator.vibrate can only be called once the user interacted with the page:
I could change my page to ask for user interaction (with a button for example) but I'd rather keep my page as is. But then I would need know if I can call navigator.vibrate.
My first approach was set a boolean to true after the first touchstart event:
let canVibrate = false;
document.addEventListener("touchstart", () => {
if (canVibrate) {
navigator.vibrate(200);
} else {
canVibrate = true;
}
});
This first approach works when the user touches with one finger, so probably most of the cases.
However this doesn't work if before pulling of its finger, the user puts down another. In that scenario, the error pops up for every touch done before removing all fingers. And then, it still needs one more touch, as if all these didn't count as an interaction.
Is there any javascript function that lets me know if navigator.vibrate can be called? And if not what are some ways to test it?
As per an example on the MDN page for touch events
This calls event.preventDefault() to keep the browser from continuing to process the touch event (this also prevents a mouse event from also being delivered). Then we get the context and pull the list of changed touch points out of the event's TouchEvent.changedTouches property.
To put this in an example you can do something like:
let canVibrate = false;
document.addEventListener("touchstart", (event) => {
if (!canVibrate) {
canVibrate = true
}
navigator.vibrate(200);
});