【问题标题】:How to get fingerprint2 result like function如何获得类似功能的指纹2结果
【发布时间】:2016-10-08 13:06:53
【问题描述】:

我想做一个函数来获取fingerprint2.js的结果

Fingerprint2 是一个现代且灵活的浏览器指纹库http://valve.github.io/fingerprintjs2/ 用法:

new Fingerprint2().get(function(result, components){
  console.log(result); //a hash, representing your device fingerprint
  console.log(components); // an array of FP components
});

无论我为在new Fingerprint2().get(function(result, components){ 之外获得 Fingerprint2 的结果所做的任何尝试都失败了。 像 Global vars 和 cookie 因为 Fingerprint2().get(...) 是异步的 它可以写成一个函数来获取指纹2结果吗? 例如:

var secure = getmefingerprint2();

【问题讨论】:

    标签: javascript fingerprintjs2


    【解决方案1】:

    利用 ES2017 功能 async/await,您可以像这样使用 Fingerprint2.getPromise()

    (async () => {
        const components = await Fingerprint2.getPromise();
        const values = components.map(component => component.value);
        const murmur = Fingerprint2.x64hash128(values.join(""), 31);
        console.log('fingerprint:', murmur);
    )()
    

    参见Fingerprint2 Doc中的get 和getPromise

    【讨论】:

    • 31 是什么?在 x64hash128 函数中?
    【解决方案2】:

    这应该是一条评论,但有点长。

    即使有可能,您也将绕过已发布的 api,这意味着您必须维护原始代码的一个分支。您还需要同步调用该功能 - 并且指纹js2 异步运行是出于充分而明显的原因。

    您似乎在询问XY problem

    你应该如何处理它取决于你打算在指纹被捕获后对它做什么。

    【讨论】:

      【解决方案3】:

      你不能让异步代码完全同步。但是,如果您的目标浏览器支持,您可以使用async/await,但不是普遍使用supported。此外,它只在async 函数内部看起来是同步的

      基本思想是返回一个promise,然后在async函数中返回一个await它:

      const getmefingerprint2 = async () => {
        const secure = await (new Promise(resolve => {
          new Fingerprint2().get((result, components) => resolve(result) )
        }))
        // do things with secure, whatever you return is thenable
        return secure
      }
      

      这个函数可以这样调用(因为 Promises):

      getmefingerprint2().then(result => {
        // do stuff with result
      })
      

      而且,在 async 函数中,您可以将 secure 视为同步处理。

      如果你真的想让你的异步代码表现得更加同步(如果你讨厌异步,可能对其他异步代码也有用),你可以将所有代码包装在一个 async 函数中,然后使用 await获取异步内容:

      const getFingerprint = () => new Promise(resolve => {
        new Fingerprint2().get((result, components) => resolve(result) )
      })
      
      const main = async () => {
        // do some of your app here
        const secure = await getFingerprint()
        // do more stuff here
      }
      
      main()
      

      或作为IIFE

      (async() => {
        // do some of your app here
        const secure = await getFingerprint()
        // do more stuff here
      })()
      

      这些只是一些 hacky 的变通方法,可以让您摆脱异步代码的负担,这可能值得了解一下,因为它会成为一个更好的应用程序。如果您将代码重构为仅在回调中包含依赖于secure 的内容,那么一旦您习惯了它,您将获得更好的性能、畅通的 UI 以及更容易推理的更动态的流程。

      【讨论】:

      • 另外,您可以使用 polyfills + babel 使其在旧浏览器中工作。 Here 是您尝试在 codepen 中完成的一个示例。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 2023-03-30
      • 2016-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多