How to save data when user move away from the web page on mobile devices?

I am creating an HTML web app and getting all data from API calls. This mostly works on mobile devices(IOS/Android). There are some pages that users can navigate these pages(every page has a previous/next button). I wanted to save page data when the user tries to move away from the webpage(tab close/minimize the browser/ swipe between apps). This app focuses on mobile devices and needs to save data when users move away from the web page. I tried onunload, onbeforeunload method but these are not fired. I used ajax calls to save data with an API. What is the best way to fix this problem?