Reset variable on every new session using localstorage - javascript

I am trying to run something only once at the beginning of the user session spanning multiple pages.
I was trying to use sessionStorage to test if a variable exists which defaults to false initially, but it is not persisting in some browsers due to a JavaScript redirect in the script:
window.location.href
Is there a way to mimic this with localstorage which persists more reliably?
i.e. to do something only once at the beginning of each new user session. The session may have multiple pages so a single javascript variable won't work.
update: as requested in the comments, the basic logic is:
new session opened.
redirect once to last page viewed.
set redirected to true. to prevent this from happening again.
I realize there are other ways to do this besides localstorage. would be nice to use that though if possible.

you could check if the item already exists or if it is null with:
localStorage.getItem("itemname");
If it doesnt exists (== null) it is the first "run" so you could set it to prevent further loop execution. use:
localStorage.setItem("itemname", "notNull");

Related

How to recognize from what page the user has landed on another page?

Page A
Page B
Page C
If the user is coming from page A do something on page C (within the same website)
If the user is coming from page B do something else on page C (within the same website)
What would be the best approach to do that in JS? (dont use document.referrer)
In my opinion, there are two decent solutions:
When Page A loads Page C, include a variable in the URL that essentially says "loaded from page A". (Same applies to Page B.)
When Page A is loaded, set either a cookie, localStorage, or sessionStorage variable that says "loaded from page A". (Same applies for Page B.) Then when Page C is loaded, check the variable to see if either Page A or Page B was the most recently opened page. (You may also want to set a timeout/expiration-time on the cookie, localStorage, or sessionStorage.)
What you can do is have a global variable that will hold the location. When you load a page. assign that variable the location
window.location.href
or
document.URL;
Another option would be using cookies.
Your description doesnt make a lot of sense (to me), especially because you havent included any framework/stack you're using (which this responsibility would likely fall on).
That said, I would use a variable with session getters and setters. You can parse the query string or URL, set that equal to a session variable, then get that session variable when you're ready to use it.
Here's how to use session getters and setters in javascript
You can have page A and page B set a cookie that indicates which page they are. Then page C can check the cookie value.

How to ensure javascript single page application to be executed on single browser tab only

I am building SPA application is emberjs framework and I need to ensure that the application instance is running only once (on single tab) on same domain.
Analogy of mutex to prevent multiple instances known from desktop application development world.
There are some solution I am considering just now like using localStorage locks or window.postMessage or SharedWorker but non of them looks bulletproof to me.
Do you have some ideas?
Thanks is advance.
I've used localStorage to make sure when users log out in one tab it logs them out in other tabs and it's worked quite well.
Bind to the storage event on the window object and use the event.key/event.newValue keys to determine what action to take. You can also use the event.url key to make sure the storage event is firing from the correct page. In my code I set a logged-out flag if the url, key and newValue data validates.
Bind to the focus event on the window object and check the value of the logged-out flag and auto-logout the user if it's set to true.
For my purpose I had to initialize the localStorage data to "not logged out" on page load because the storage event will not fire if you don't actually change the value of the localStorage key you're watching. I.e. if the value is blah and you set it to blah, no event will fire.
This works back to IE 8 too.
For your purpose you could set a localStorage key/value when someone logs in and block the page from working if that key/value is already set. Maybe set a timestamp as the value so if someone doesn't properly logout they can get back in after so many seconds. Then set an interval to update the timestamp while the user is logged in.
This is untested, if you go down this road I'd be interested to see how it works for you and what you had to do to make it work.

Using Global Variables between multiple functions in JQuery?

I want to dynamically load an image using jQuery like this:
main.js
var slidersrc=""; //try to define global variable - not sure if this is correct
jQuery(document).ready(function() {
jQuery("#sliderimg").attr('src', slidersrc);
});
jQuery("#selection1").click(function() {
slidersrc='wp-content/themes/*****/slide1.png';
});
So the first time user access my website, the slider is empty. After user clicks on one of the selection areas, I set the global variable value. Then if user continues to navigate at my website to different pages, the user should be shown a slider image as a result of his selection.
However, this doesn't appear to work.
Am I correctly using the global variable in jQuery? Or is there a better way to save the user selection value in client side?
thanks!
Global variables do NOT survive from one page to the next. Each page starts an entirely new javascript context (all new global variables, functions, etc...).
If you want to save state from one page to the next, your options are:
Put the data in a cookie which you can read from each successive page when that page loads.
Put the data in a browser local storage which you can read with javascript from each successive page when that page loads (recommended option).
Store the data on the server and embed it in each page as it is served from the server.
You can read about how to read and write from browser LocalStorage here and here.
If you're planning on changing the slider image each time the user clicks, then perhaps you want to save an index into an image array in local storage. When the page loads, you read the current index from localStorage (or supply a default value if no value exists in local storage), then write back the current value to localStorage for the next page. If the user takes some action that causes the index to update to a new value, then you update your page and then write that new index into localStorage so the next page can read it from there and so on.
LocalStorage is a similar concept to cookies, but it's a bit easier to manage and more efficient (the data is not sent to the server with every page request).

Use javascript to remember what choices the user made on previous pages?

I have some pages, on the last page I need to know what choices a user made on the two last pages.
Like this:
a.html
User has three choices here that takes him/her to different urls. I need to somehow save this choice and use it later.
Example:
<script>globalVariable1="firstchoice"</script>
b.html
This is one of three choices page and here the User have 3-4 new choices that takes him/her to different urls. I also need to save this choice somehow for later use.
Example:
<script>globalVariable2="thirdchoice"</script>
c.html
This is the page where I need to know what choices the user has made earlier. To be able to link back to those exact pages if the user wants to go back in my breadcrumb-solution.
Example:
<script>
if(globalVariable1 == "firstchoice"){
//do this
}
if(globalVariable2 == "thirdchoice"){
//do this
}
</script>
Can I do this with some global variables in javascript or how can I solve this?
Thanks
You can use localStorage. A browser API that persists key/value pairs even if you navigate between pages, reload the page or close and reopen the browser.
//setting a value
localStorage["foo"] = "bar";
//getting a value
var x = localStorage["foo"];
Using sessionStorage will also work.
//setting a value
sessionStorage["foo"] = "bar";
//getting a value
var x = sessionStorage["foo"];
Wikipedias Web Storage article describes the difference between localStorage and sessionStorage as:
Data placed in local storage is per domain (it's available to all scripts from the domain that originally stored the data) and persists after the browser is closed. Session storage is per-page-per-window and is limited to the lifetime of the window. Session storage is intended to allow separate instances of the same web application to run in different windows without interfering with each other, a use case that's not well supported by cookies.
You will have to store cookies to track the user's state. Try cookie.js. It has a really simple key-value interface that you can read about on its GitHub page.
Web pages are stateless, so you cannot share global JavaScript variables between pages.
However you can set global variables for your page and containing modules by using the value of the cookie.
Your cookies will be available on all pages of your domain for the current browser.
Example:
//Page 1: Set cookie depending on user choice
$.cookie("choice1", ValueOfChoice1);
//Page 2: Get previous user choice
globalVariable1 = $.choice1("example");
You can read Setting cookies with jQuery if you want more details about how to use cookies.
you can use localStorage or sessionStorage.
Another choice if you're using some server-side language like PHP or Asp.Net is to sore those values in the user's session on the server.

How to add javascript to page on login and logout in Drupal 6

I'm working on a module and am trying to add some javascript to the next page a user sees after logging in or out. Calling drupal_add_js() on hook_user (op == login) doesn't seem to work; I'm assuming this is because drupal_goto is called after the login is completed and a fresh page request is initiated.
I've considered using hook_user to set session variables which I can then respond to on the next page load but that seems somewhat fragile. Any suggestions?
If you want something to be carried over to a new page you only have a few options:
Alter the url.
Store in the database.
Store in session.
Altering the url, would probably be quite hard and messy. Storing in the session or database is basically the same thing. So you would probably want to use the Drupal session system instead of making your own.
You could add something in the session and then in hook_init check for it and if it's there add the js and delete it from the session.
I don't think you will find a much better solution, though it would be nice if there were.

Categories