Search code examples
javascriptfingerprintjs2

Save Fingerprint2 result in Variable


I am using Fingerprint2.js (Modern & flexible browser fingerprinting library, a successor to the original fingerprintjs http://valve.github.io/fingerprintjs2/)

I get hash fingerprint when i console.log inside the function. but when i store that result in some variable, it gives 'undifined'

Fingerprint2.get(options, function (components) {
  var values = components.map(function (component) { return component.value });
  console.log('insideFun -> ' + x64hash128(values.join(''), 31));
  return x64hash128(values.join(''), 31);
});

By this, i see a hash code in my console... but if i store the return value to some var it do not work.

if i use asyn/await it still do console value but not store in var

var guid = function guid() {
    var fpid;
    var options = {}
    let fp = (async function() {
        const components = await Fingerprint2.getPromise(options);

        var values = components.map(function (component) { return component.value });

        let fpid = x64hash128(values.join(''), 31);
        return fpid;
     })();
  return fpid;
};

guid();

it give fpid is undefined.

is there any way to handle this?


Solution

  • Fingerprint2.get is an asynchronous function (that's why you need to provide a callback to it); Doing return ... inside that callback won't have any effect.

    You could use getPromise instead, to return a Promise, and use async/await to make your code look like it's synchronous (even though it's not):

    // This function is asynchronous,
    // it does not return a fp, but a Promise that will
    // resolve to a fp
    var guid = function guid() {
        const options = {};
        return Fingerprint2.getPromise(options)
               .then(components => {
                 const values = components.map({ value } => value);
                 return x64hash128(values.join(''), 31);
               });
    };
    
    // And then, there are 2 ways to use it:
    
    // Method 1 - using `.then`
    guid()
      .then(fpid => { // When it's done
        console.log(fpid); // Now you can use it
        document.cookie = `fpid=${encodeURIComponent(fpid)}`;
      });
      
    
    // Method 2 - using `async/await`
    (async function() {
      const fpid = await guid();
      console.log(fpid); // Now you can use it
      document.cookie = `fpid=${encodeURIComponent(fpid)}`;
    })();
    
    // But this will never work:
    // const fpid = guid();
    // console.log(fpid); // Promise<pending>
    

    The problem when you do this:

    const fpid = guid();
    console.log(fpid);
    

    ... is that console.log is executed before the FingerPrint was retrieved. Because FP2 is asynchronous. So you need to wait for the result before being able to use it.