Search code examples
javascriptjquerysession-storage

How do I run a function once session storage is != undefined


I am in a situation wherein I have a an external JavaScript file that makes an ajax call and saves certain data to session storage. The JavaScript file loads from an external site and therefore, I cannot edit it.

I need to run a function to consume the saved data as soon as it loads into session storage. How can I trigger a function once this data loads?


Solution

  • Maybe this can help you:

    window.onstorage = function(e) {
      console.log('The ' + e.key + ' key has been changed from ' + e.oldValue + ' to ' + e.newValue + '.');
    };
    

    More info here and here

    So you could subscribe to your session key changes with (not tested):

    window.onstorage = function(e) {
        if ( 
            e.storageArea === sessionStorage && 
            e.key === "<your_key>" && 
            e.oldValue === undefined &&
            e.newValue !== undefined
        ) {
            console.log("my key is not undefined anymore")
        } 
    };
    

    UPDATE: So it seems that it is not working for you. Then you can try something like this (using interval to check if sessionStorage changes):

    var INTERVAL = 2000;
    // Then, in your code you can check every `INTERVAL` milleconds
    // if the sessionKey you need is not null
    console.log("Program starts");
    // You can limit your intents too
    var limit = 5;
    var intervalId = setInterval(function() {
      console.log("Checking sessionStorage");
      var test = sessionStorage.getItem("test");
      if (test !== null) {
        console.log("'test' is now defined: " + test);
        clearInterval(intervalId);
      }
    
      if (--limit <= 0) {
        console.log("'test' has not changed");
        clearInterval(intervalId);
      }
    }, INTERVAL);
    

    Test here: https://jsbin.com/tukubutoje/edit?js,console