Adding custom properties the Document Object in front-end javascript - javascript

Is it ok to add custom properties the Document Object in front-end javascript?
Suppose I want to store some parameters, but I can't do so in the URL. Can I create a new property on the Document Object to store the parameters? For example, if my parameter is 'someImportantInfo', can I set:
document.someImportantInfo = 'thisIsSecretInfo';
So that when a user goes new page, I can retrieve the contents of the 'someImportantInfo' property in my front-end Javascript, and do something with 'thisIsSecretInfo'?

The best way to do that is not in the document Object.
When you load a new page, the document Object will be replaced by another one.
To store information between different pages you can use the localStorage or sessionStorage:
When you need to save some value:
localStorage.setItem("someImportantInfo","thisIsSecretInfo");
And when you need to get this value in other page:
localStorage.getItem("someImportantInfo");
See some examples in: https://www.w3schools.com/html/html5_webstorage.asp
If you want to store information only during a session (cleared when the browser is closed), use sessionStorage instead.
Also, you can use cookies, but it's more tricky because you don't have a native function to save and retrieve cookies.

Related

Reopen Dexie Database with Tampermonkey

As per my previous post, I was referred to create a new post.
As seen in the comments, there is a trail of progression for the issue, I'll rephrase here in this post:
I'm using a TamperMonkey script in FireFox.
I'm trying to persist a Dexie object/database into TamperMonkey's local storage with GM.setValue('unique-dexie-db-name', dexieDBvariable);
However when I go to retrieve this value (ex. I store this on google.com, and retrieve this on yahoo.com) with var dexieDB = GM.getValue('unique-dexie-db-name'); My returned object value is not a Dexie database object, but rather something else I can't use as a database.
My question: I'm unsure, but I think when storing this Dexie Database into TamperMonkey, it gets stored as a string, and, I should try to somehow JSON.stringify() the object fully in order to be able to reproduce and re-create it when I need it in the GM.getValue() call. How do I store this Javascript object as a string in order to be able to retrieve the value again as a whole later?
This is my working example code;
https://gist.github.com/n-bell/b375c80b638d3a59a250e903afb4a36b.js
https://gist.github.com/n-bell/b375c80b638d3a59a250e903afb4a36b
(second link looks better formatted in browser)
And, as stated before, I've tried playing around with JSON.parse() / JSON.stringify() but I'm not sure this is the path to go down.

Passing dataset or datatable between two pages u

I've a popup to enter the data and once the data is added, I need to show data in parent page Gridview. But that data don't need to be stored until I click the save button below the Gridview in the parent page. It will still be displayed and maintained on the screen - (like it has active/inactive button).
When I click the save below the gridview, it will be stored in the database all at once. I need to do this using javascript. How can I do that?
I'm working on asp.net web project.
You can save your data temporarily using localStorage instead of your database for instance:
localStorage.setItem('myDataName', 'myDataValue') // Save data
And:
localStorage.getItem('myDataName') // Get data
This works for strings. If you want to save objects or arrays of objects, you must convert them to strings like this:
localStorage.setItem('myDataName', JSON.stringify(myObject)) // Save object
Take a look at LocalStorage
The localStorage property allows you to access a local Storage object.
localStorage is similar to sessionStorage. The only difference is
that, while data stored in localStorage has no expiration time, data
stored in sessionStorage gets cleared when the browsing session
ends—that is, when the browser is closed.
It should be noted that data stored in either localStorage or
sessionStorage is specific to the protocol of the page.
Store Data
localStorage.setItem('Key', 'YOUR_DATA');
Read Data
var YOUR_DATA = localStorage.getItem('Key');
You can also store objects by stringifying it.
localStorage.setItem('Key', JSON.stringify(YOUR_DATA_OBJ));
when reading parse to object
var YOUR_DATA_OBJ = JSON.parse(localStorage.getItem('Key'));

Keeping a global value in the next page [duplicate]

I want to send some data from one HTML page to another. I am sending the data through the query parameters like http://localhost/project/index.html?status=exist. The problem with this method is that data remains in the URL. Is there any other method to send the data across HTML pages using JavaScript or jquery.
why don't you store your values in HTML5 storage objects such as sessionStorage or localStorage, visit HTML5 Storage Doc to get more details. Using this you can store intermediate values temporarily/permanently locally and then access your values later.
To store values for a session:
sessionStorage.setItem('label', 'value')
sessionStorage.getItem('label')
or more permanently:
localStorage.setItem('label', 'value')
localStorage.getItem('label')
So you can store (temporarily) form data between multiple pages using HTML5 storage objects which you can even retain after reload..
I know this is an old post, but figured I'd share my two cents. #Neji is correct in that you can use sessionStorage.getItem('label'), and sessionStorage.setItem('label', 'value') (although he had the setItem parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:
var val = sessionStorage.myValue
in place of getItem and
sessionStorage.myValue = 'value'
in place of setItem.
Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:
sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object
The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject all you get is [object Object], which doesn't help you too much.
possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags
like this
http://localhost/project/index.html#exist
so once when you are done retriving the data show the message and change the
window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server
Well, you can actually send data via JavaScript - but you should know that this is the #1 exploit source in web pages as it's XSS :)
I personally would suggest to use an HTML formular instead and modify the javascript data on the server side.
But if you want to share between two pages (I assume they are not both on localhost, because that won't make sense to share between two both-backend-driven pages) you will need to specify the CORS headers to allow the browser to send data to the whitelisted domains.
These two links might help you, it shows the example via Node backend, but you get the point how it works:
Link 1
And, of course, the CORS spec:
Link 2
~Cheers

Architecture for temporary storing of values within a javascript library

I am currently writing a javascript library that wraps a REST API provided by a third party (intended to be used on server side, but wouldn't like to limit it to). One of the actions defined by the api is 'login' which gives me a session key that I need to use on further requests. Currently, everytime I go to use this library I need to login again as there is no persistence of this session key. My question is, what is the best way to persist it throughout a session?
My first instinct was to give the library a callback that would store it and a callback that would retrieve it and the implementation can determine how that session key is persisted:
var thirdPartyApi = new ThirdPartyApi({
loginCredentials: {..},
setSessionKeyCallback: function() {},
getSessionKeyCallback: function() {}
});
thirdPartyApi.makeSomeRequest('foo');
Can you recommend the best architecture for this problem?
It seems like you want to use the REST Api in a browser. There are some factors you need to take into account, such as, navigating away from the page and coming back to it later.
You can use Web Storage to store the key. There are two types, localStorage and sessionStorage. The only difference between then is that sessionStorage is deleted when the browser window is closed, while localStorage isn't. Web Storage is supported by all modern browsers and IE8+ http://www.w3schools.com/html/html5_webstorage.asp
The localStorage object can be used as such:
localStorage.setItem("bar", foo);
var foo = localStorage.getItem("bar");
localStorage.removeItem("bar");
sessionStorage object can be used the same way.
both localStorage and sessionStorage are global objects that can be accessed from anywhere, so there is no need for any special architecture on your ThirdPartyApi object.

Backbone without a datastore

I am working on an offline javascript application. It needs to support IE7 so localStorage is not an option. That said, the app does NOT need to persist any information (if you refresh everything gets wiped and that's OK).
So my question is, how do I set Backbone to just use a standard javascript variable (JSON) as my data store?
If I omit the model.url() method I get an error. I imagine this is simple, but I'm not sure what to do.
Thanks!
If you look at what the localStorage adapter is doing, you will find that it is overriding Backbone.sync. This is the module in Backbone which is responsible for storing/newing/retrieving/updating your data when you call new, save, fetch, etc.
By default, it uses a RESTful endpoint defined in the url of your model. If you use the LocalStorage override, it puts it in a local store.
If, instead, you just want to put it into an in-memory array, you would just override Backbone.sync the same way by defining what "read", "update", "create" and "delete" do. I would base it off of the backbone-localstorage.js adapter since it does most of what you want, but I would then store/retrieve from hash of id/object key/value pairs.
Simply do not use the save or create Collection methods.
Instead use store and add. These do not attempt to persist the data to storage.

Categories

Resources