I have read Javascript. Listen for iPhone shake event? and Detecting shaking in html5 mobile which gives a good solution to detect a mobile phone "shake" event:
<script src="shake.js"></script>
<script>
var myShakeEvent = new Shake({threshold: 15, timeout: 1000});
myShakeEvent.start();
window.addEventListener('shake', function() { alert('shake!'); }, false);
</script>
Unfortunately, this does not seem to work with recent iOS devices, and this issue shows that special permission should be granted for recent iOS versions. Note that the code from here is not easily usable in the library shake.js.
Question: which method is available, as of 2022, to detect a "shake" event with Javascript, working on the main browsers (Firefox, Chrome, Safari) and mobile devices (iOS, Android)?
It's ok if there is a popup asking for permission first (like popups asking for permission for geolocation requests).
There is no
shakeevent: the closest event that exists isdevicemotion.Based on the content of your question, I infer that you just want to subscribe to events which are fired when device acceleration exceeds a certain threshold, with a debounce delay between possible triggers (timeout).
Using the "shake.js" library you linked to as a reference, I wrote a TypeScript module which you can use to accomplish essentially the same thing. It includes getting user permission approval on start, but keep in mind that you'll have to call the
ShakeInstance.start()method in response to a user-initiated event (e.g. a button click).TS Playground
Use like this: