fingerprintjs not loading in chrome extension

Viewed 536

I am trying to load fingerprintjs in my chrome extension and for some reason it is not loading. The documentation says to use this approach, which works fine in standalone web sites, just not in chrome extensions

<script>
    function initFingerprintJS() {
      FingerprintJS.load().then(fp => {
        // The FingerprintJS agent is ready.
        // Get a visitor identifier when you'd like to.
        fp.get().then(result => {
          // This is the visitor identifier:
          const visitorId = result.visitorId;
          console.log("visitorId", visitorId);
        });
      });
    }
  </script>
  <script async src="fp.min.js" onload="initFingerprintJS();"></script>

For chrome extension I added created a JS file initFingerprint.js that holds the init code like so:

var visitorId = null; //will hold the actual fingerprint
function initFingerprintJS() {
    console.log("inside initFingerprintJS");
    FingerprintJS.load().then(fp => {
        console.log("loaded initFingerprintJS");
        fp.get().then(result => {
            console.log("initFingerprintJS got result", result)
            visitorId = result.visitorId; // This is the visitor identifier
            console.log("visitorId", visitorId);
        });
    });
}
initFingerprintJS();

In background.html, I added this:

<script async src="fp.min.js"></script>
<script async src="initFingerprint.js"></script>

I have tried with async in there and not in there, but still no luck. This line will print, but none of the other lines below it.

inside initFingerprintJS

What am I doing wrong? I appreciate any help. thank you

1 Answers

Remove <script> tag for fp.min.js from the html and create the script element yourself in initFingerprint.js so you can use the onload event directly:

loadScript('fp.min.js').then(initFingerprintJS);

function loadScript(url) {
  return new Promise((resolve, reject) => {
    const el = document.createElement('script');
    el.onload = resolve;
    el.onerror = reject;
    el.src = url;
    document.documentElement.appendChild(el);
  });
}

async function initFingerprintJS() {
  visitorId = await (await FingerprintJS.load()).get();
  console.log('visitorId', visitorId);
}
Related