how to backup html 5 local storage data - javascript

am developing an offline application using html 5 and java script libraries.
my system is for offline data collection. data is stored in the local machine in text format before being synced to the server later on.
before i had developed the same application but using silver light which was easy to back up data for security reasons using
any idea on how i can backup the text files and zip them to my hard disk will be highly appreciated.
i have not found a solid answer through my research so far
thanks in advance.

One "solution" I can think of is, before the user closes the app using the close button, you could detect the window.onbeforeunload event and send the data to your server to save. But this is not reliable because there might be cases when the browser may crash or the user might forcefully close the browser application. Or worst of all if you are constantly using localStorage and by chance the user clears the browsing data (which includes localStorage) it will be gone.
But assuming you have the data at hand, you can send it to the server using POST and make a script to save it in the disk. Obviously, you might want to impose limitation on file size and enforce other security restrictions.
WARNING: PHP
Lets say you have a folder created for each unique user and all files in each user's folder are guaranteed to be named uniquely. In PHP you can use functions like file_put_contents() to save a text file, you can also easily ZIP it using the ZipArchive class.
It's not recommended to store this kind of data directly to the drive. I would highly recommend you to put the localStorage data in some kind of database and do a database backup instead of backing up individual user's data.
As other users have pointed it out you could also look at the HTML5 File API. Examples here.

I found a solution on how to backup local storage files and zip them to my local drive without any server code. Below is a code snippet that works fine for me at least for now. Any modifications and enhancements will be highly appreciated.
if (localStorageKeys.length > 0) {
for (var i = 0; i < localStorageKeys.length; i++) {
var key = localStorageKeys[i];
if (key.search(_instrumentId) != -1) {
keysToBackup.push(key);
var data = localStorage.getItem(localStorageKeys[i]);
zip.file(localStorageKeys[i].slice(0, -19) + ".txt", data);
}
else {
keysNotToBackup.push(key);
}
var datafile = document.getElementById('backupData');
datafile.download = formName + "_Data.zip";
datafile.href = window.URL.createObjectURL(zip.generate({ type: "blob" }));
}
}

I found a solution for backup and restoring the local storage of websites.
You can use this repository:
https://github.com/todvora/localstorage-backup
This is the live app:
https://www.tomas-dvorak.cz/localstorage-backup/
Usage:
In the live app, Drag the buttons and drop them into your bookmarks. They are so-called bookmarklets.
Open the site you want to backup/restore and click on this bookmarked button.

Related

Can you prevent users editing the chrome.storage.local values in a Chrome extension? What is the best way to store persistent values for an extension?

So I'm working on a Chrome extension for someone else. I don't want to give away specific details about the project, so for I'll use an equivalent example: let's assume it's an extension to run on an image/forum board. Imagine I have variables such as userPoints, isBanned etc. The later being fairly self-explanatory, while the former corresponding to points the user acquires as they perform certain actions, hence unlocking additional features etc
Let's imagine I have code like:
if(accountType !== "banned"){
if(userPoints > 10000) accountType = "gold";
else if(userPoints > 5000) accountType = "silver";
else if(userPoints > 2500) accountType = "bronze";
else if(userPoints <= 0) accountType = "banned";
else accountType = "standard";
}else{
alert("Sorry, you're banned");
stopExtension();
}
Obviously though, it becomes trivial for someone with the knowledge to just browse to the extensions background page and paste chrome.storage.local.set({'userPoints': 99999999}) in the console, hence giving them full access to all the site. And, with the Internet, someone can of course share this 'hack' on Twitter/YouTube/forums or whatever, then suddenly, since all they'd need to do is copy and paste a simple one-liner, you can have 1000s of people, even with no programming experience, all using a compromised version of your extension.
And I realise I could use a database on an external site, but realistically, it would be possible that I would be wanting to get/update these variables such as userPoints 200+ times per hour, if the user was browsing the extentions target site the entire time. So the main issues I have with using an external db are:
efficiency: realistically, I don't want every user to be querying the
db 200+ times per hour
ease-of-getting-started: I want the user to just download the
extension and go. I certainly don't want them to have to sign up. I
realise I could create a non-expiring cookie with for the user's ID
which would be used to access their data in the db, but I don't want
to do that, since users can e.g. clear all cookies etc
by default, I want all features to be disabled (i.e. effectively
being considered like a 'banned' user) - if, for some reason, the
connection with the db on my site fails, then the user wouldn't be
able to use the extension, which I wouldn't want (and just speaking
from experience of my parents being with Internet providers whose
connection could drop 10 times per hour, for some people, failed
connections could be a real issue) - in contrast, accessing data from
the local storage will have like a 99.999% success rate I'd assume,
so, for non-critical extensions like what I'm creating, that's more
than good enough
Still, at least from what I've found searching, I've not found any Chrome storage method that doesn't also allow the user to edit the values too. I would have thought there would be a storage method (or at least option with chrome.storage.local.set(...) to specify that the value could only be accessed from within the extension's context pages, but I've not found that option, at least.
Currently I'm thinking of encrypting the value to increment by, then obfuscating the code using a tool like obfuscator.io. With that, I can make a simple, like 30 character js file such as this
userPoints = userPoints + 1000;
become about 80,000...still, among all the junk, if you have the patience to scroll through the nonsense, it's still possible to find what you're looking for:
...[loads of code](_0x241f5c);}}}});_0x5eacdc(),***u=u+parseInt(decrypt('\u2300\u6340'))***;function _0x34ff36(_0x17398d)[loads more code]...
[note that, since it's an extension and the js files will be stored on the user's pc, things like file size/loading times of getting the js files from a server are irrelevant]
Hence meaning a user wouldn't be able to do something like chrome.storage.local.set({'userPoints': 99999999}), they'd instead have to set it to the encrypted version of a number - say, something like chrome.storage.local.set({'userPoints': "✀ເ찀삌ሀ"}) - this is better, but obviously, by no means secure.
So anyway, back to the original question: is there a way to store persistent values for a Chrome extension without the user being able to edit them?
Thanks

Button Counter and store on intranet

I've got a short question. I want to develop a little script on our intranet.
The requirements are:
a button, which count +1 if you click on it
just logged in users can count
all other users should see the counter
I'm a beginner in JS and i only know the localStorage function, but i want to save the counter on the server, so that everybody see's the same status.
Thats what I got, but its just the localStorage, so every computer has their own status of the counter.
if (localStorage.getItem("counter")!=null) {
counter = Number(localStorage.getItem("counter"));
document.getElementById("counterValue").innerHTML = counter;
}
Do you know what I mean? Thanks for the help and sorry for my bad english :)
You need to keep the 'counter' on the server. You should keep it in some kind of persistent storage (not memory, since the memory can be re-set):
simplest is file system (file)
DB (e.g., MySql)
cloud (e.g., AWS S3)
then to get it from storage and present to all users. If you need the value to be presented for all Live, then you'll have to use some solution for that like SignalR.

Unique flash ID per computer

I have created an online multiplayer card game using Adobe flash Professional. In this game multiple clients/account is not allowed, hence I need to detect whether the users are joining game from different devices or not. I can't simply do a server sided check for the IP-address because I still want e.g. people in the same office to be able to play together.
I have found some solution like reading the MAC address (Here) but the problem is that NetworkInfo.networkInfo.findInterfaces() works only on Adobe air, which is not my case.
Another solution could be using browser cookies, but the problem of this solution is that, the users can use e.g. Chrome and Firefox on the same computer.
As this a web game, using js could be also a solution, so I tag this question as js as well.
UPDATE
Using SharedObject does not work in this case, since google chrome uses its own storage.
Any suggestion will be appreciated.
Instead browser cookies you can use "flash cookies" - SharedObject. It is really simple and have mechanic similar to browser cookies, but stored in flash local storage.
UPDATE
Example:
var mySo:SharedObject = SharedObject.getLocal("host"); // get saved SO with name "host" if exists or create new if doesn't exist
mySo.data = {someProperty: "someData"}; // writing some data
var flushResult:Object = mySo.flush(); // saving data in local storage
...
var savedSO:SharedObject = SharedObject.getLocal("host");
trace(savedSO.data.someProperty); // output: someData

Open, create files and save data in client side and reuse that data

I am creating a chrome app with plain javascript and bootstrap. Initially user have to give some data and app keeps that data and reuse that for next times. I think I have to store that
data in a file. Can I use the plain javascript file IO to do that or is there a special way to do it in chrome-style. (Because some features are disabled in packaged apps)
You're right that localstorage is not enabled for Chrome packaged apps. However, depending on what kind of data you're managing, there are two APIs that should work.
chrome.storage.local is a general key-value store that will save data on the local machine (chrome.storage.sync is an identical API that will also synchronize the data between a users' devices, but I wouldn't recommend it for large files)
The API is simple to use:
chrome.storage.local.set({myKey: "myValue"}, function() {
if (!chrome.runtime.lastError) {
console.log("The value has been stored!");
} else {
console.error("There was an error!");
}
});
chrome.storage.local.get("myKey", function(data) {
if (!chrome.runtime.lastError) {
console.log("The value is " + data.myKey);
} else {
console.error("There was an error!");
}
});
(If you're using chrome.storage.sync, then you probably also want to add a listener to the chrome.storage.onChanged event, to know when data was changed from another location)
The other way may be what you're thinking of as "plain javascript file IO" -- the W3C File System API is supported by packaged apps. You can request storage space from the user and store actual files that you can read and write in JavaScript. There's a good introduction to it here.

How to increase speed of application with lots of RSS

Good Morning all...
I have web application with lots of RSS feeds. The flow is below
Fetch the RSS from respective site(using PHP)
Store it in DB (MySQL)
Read it and display it to users browser.
Fetching is done at every one hour interval and store to DB.
Then whoever request, display these feeds to users browser. (Read from DB and display it.)
The reading process is not that fast. In other words if user have 20 feeds on same page then loading 5 articles for each feed. It is not that fast and currently not giving good User experience.
I am running on 8GB RAM VPS server, Technology - PHP, MYSQL, MOOTOOLS, javascripts
Then to make it fast i tried using Flat File - Read feeds from respective sites and write it to Feed File. (separate file for each feed.)
Then read the feed file and display it on user browsers. In this scenario it was slower than reading from DB.
So now i have no option.. and no clue what i can do to increase the speed of my website.
If any expert have any suggestion please let me know.
Regards,
Mona
I would not consider myself an expert, but I could at least give you somethings to try:
First it's a good thing you're showing the rss feeds from your own database, this should protect you if any of the rss-sources fails due to problems at the rss-provider.
Nonetheless, I suggest you to move the loading part of the rss feeds to a separate file, which runs server-sided (and make it into a 'cronjob'). This makes sure that a user can never be bothered with the rebuilding of your data-source. This cronjob can then be called each hour to refresh your database.
The next step would be to find out where the process slows down the most, are there slow queries? Or is there just some sluggish code in your script?
To narrow down the causes, I really suggest you to install the XDebug extension (there are ready dlls for Windows here: http://pecl.php.net/package/Xdebug) and add the following lines to your php.ini:
[XDebug]
zend_extension = "C:\xampp\php\ext\php_xdebug.dll"
xdebug.profiler_append = 0
xdebug.profiler_enable = 0
xdebug.profiler_enable_trigger = 1
xdebug.profiler_output_dir = "C:\xdebug"
xdebug.profiler_output_name = "cachegrind.out.%t-%s"
xdebug.remote_enable = 0
xdebug.remote_handler = "dbgp"
xdebug.remote_host = "127.0.0.1"
xdebug.trace_output_dir = "C:\xdebug"
After installing, adding ?XDEBUG_PROFILE to your url (see: http://www.xdebug.org/docs/profiler) will generate a file which you can examine with WinCacheGrind (http://sourceforge.net/projects/wincachegrind/). This program you can narrow down the execution time per function call.
I hope this helps you out :)
PS: Make sure to disable, or even better, not install XDebug on your production environment, since XDebug slows down your scripts...

Categories

Resources