lornz
lornz

Reputation: 306

Export javascript object to use it in another program

I'm trying to build an offline navigation.

I have two versions of my program: online and offline.

  1. I create an object based on a google maps request

  2. I want to "store" this object somehow

  3. I want to access this object in the offline version of the program.

If I do console.log(object) google chrome gives me the object, but I cant just copy it and paste in the offline version.

Any ideas how to "export" the object?

Upvotes: 1

Views: 47

Answers (2)

Carlos Guzman
Carlos Guzman

Reputation: 363

I guest you use HTML5 for you task? In the case answer is yes, is ease save local data for your use in offline mode. You can read this tutorial for localStorage object Local Storage in HTML5

Now, the next code help you to save online data in local storage, and access this in offline:

function init() {
   var googleMapObject = null;

   // This is first status verification
   if (navigator.onLine) {
      googleMapObject = anyMethodToGetData();

      // Save remote object in local storage
      localStorage['googleMapsObject'] = JSON.stringify(googleMapObject);
   } else {
      // In offline mode, return local storage data
      if (localStorage['googleMapsObject']) {
         googleMapObject = JSON.parse(localStorage['googleMapsObject']);
      }
   }

   return googleMapsObject;
}

The init method is call in load/ready event. If you need detect change in online/offline state, use online/offline events.

Regards!!

Upvotes: 0

Damien
Damien

Reputation: 4093

  1. Stringify your object -> JSON.stringify( yourObject );

  2. Save your file as JSON ( you can use library like : https://github.com/eligrey/FileSaver.js/ )

  3. Upload this JSON to your offline app

  4. Parse it -> JSON.parse( youJsonFile.json )

Upvotes: 2

Related Questions