fingerprintjs

Форк
0
168 строк · 4.8 Кб
1
import * as FingerprintJS from '../src'
2
import { errorToObject } from '../src/utils/misc'
3

4
type Text = string | { html: string }
5

6
async function getVisitorData() {
7
  const fp = await FingerprintJS.load({ debug: true })
8
  return await fp.get()
9
}
10

11
async function startPlayground() {
12
  const output = document.querySelector('.output')
13
  if (!output) {
14
    throw new Error("The output element isn't found in the HTML code")
15
  }
16

17
  const startTime = Date.now()
18

19
  try {
20
    const { visitorId, confidence, components } = await getVisitorData()
21
    const totalTime = Date.now() - startTime
22
    output.innerHTML = ''
23
    addOutputSection({ output, header: 'Visitor identifier:', content: visitorId, size: 'giant' })
24
    addOutputSection({ output, header: 'Time took to get the identifier:', content: `${totalTime}ms`, size: 'big' })
25
    addOutputSection({
26
      output,
27
      header: 'Confidence score:',
28
      content: String(confidence.score),
29
      comment: confidence.comment && {
30
        html: confidence.comment.replace(
31
          /(upgrade\s+to\s+)?pro(\s+version)?(:\s+(https?:\/\/\S+))?/gi,
32
          '<a href="$4" target="_blank">$&</a>',
33
        ),
34
      },
35
      size: 'big',
36
    })
37
    addOutputSection({ output, header: 'User agent:', content: navigator.userAgent })
38
    addOutputSection({
39
      output,
40
      header: 'Entropy components:',
41
      content: FingerprintJS.componentsToDebugString(components),
42
    })
43

44
    initializeDebugButtons(`Visitor identifier: \`${visitorId}\`
45
Time took to get the identifier: ${totalTime}ms
46
Confidence: ${JSON.stringify(confidence)}
47
User agent: \`${navigator.userAgent}\`
48
Entropy components:
49
\`\`\`
50
${FingerprintJS.componentsToDebugString(components)}
51
\`\`\``)
52
  } catch (error) {
53
    const totalTime = Date.now() - startTime
54
    const errorData = error instanceof Error ? errorToObject(error) : error
55
    output.innerHTML = ''
56
    addOutputSection({ output, header: 'Unexpected error:', content: JSON.stringify(errorData, null, 2) })
57
    addOutputSection({ output, header: 'Time passed before the error:', content: `${totalTime}ms`, size: 'big' })
58
    addOutputSection({ output, header: 'User agent:', content: navigator.userAgent })
59

60
    initializeDebugButtons(`Unexpected error:\n
61
\`\`\`
62
${JSON.stringify(errorData, null, 2)}
63
\`\`\`
64
Time passed before the error: ${totalTime}ms
65
User agent: \`${navigator.userAgent}\``)
66
    throw error
67
  }
68
}
69

70
function addOutputSection({
71
  output,
72
  header,
73
  content,
74
  comment,
75
  size,
76
}: {
77
  output: Node
78
  header: Text
79
  content: Text
80
  comment?: Text
81
  size?: 'big' | 'giant'
82
}) {
83
  const headerElement = document.createElement('div')
84
  headerElement.appendChild(textToDOM(header))
85
  headerElement.classList.add('heading')
86
  output.appendChild(headerElement)
87

88
  const contentElement = document.createElement('pre')
89
  contentElement.appendChild(textToDOM(content))
90
  if (size) {
91
    contentElement.classList.add(size)
92
  }
93
  output.appendChild(contentElement)
94

95
  if (comment) {
96
    const commentElement = document.createElement('div')
97
    commentElement.appendChild(textToDOM(comment))
98
    commentElement.classList.add('comment')
99
    output.appendChild(commentElement)
100
  }
101
}
102

103
function initializeDebugButtons(debugText: string) {
104
  const copyButton = document.querySelector('#debugCopy')
105
  if (copyButton instanceof HTMLButtonElement) {
106
    copyButton.disabled = false
107
    copyButton.addEventListener('click', (event) => {
108
      event.preventDefault()
109
      copy(debugText)
110
    })
111
  }
112

113
  const shareButton = document.querySelector('#debugShare')
114
  if (shareButton instanceof HTMLButtonElement) {
115
    shareButton.disabled = false
116
    shareButton.addEventListener('click', (event) => {
117
      event.preventDefault()
118
      share(debugText)
119
    })
120
  }
121
}
122

123
function copy(text: string) {
124
  const textarea = document.createElement('textarea')
125
  textarea.value = text
126
  document.body.appendChild(textarea)
127
  textarea.focus()
128
  textarea.select()
129
  try {
130
    document.execCommand('copy')
131
  } catch {
132
    // Do nothing in case of a copying error
133
  }
134
  document.body.removeChild(textarea)
135
}
136

137
async function share(text: string) {
138
  if (!navigator.share) {
139
    alert(`Sharing is unavailable.
140

141
Sharing is available in mobile browsers and only on HTTPS websites. ${
142
      location.protocol === 'https:'
143
        ? 'Use a mobile device or the Copy button instead.'
144
        : `Open https://${location.host}${location.pathname}${location.search} instead.`
145
    }`)
146
    return
147
  }
148
  try {
149
    await navigator.share({ text })
150
  } catch {
151
    // Do nothing in case of a share abort
152
  }
153
}
154

155
function textToDOM(text: Text): Node {
156
  if (typeof text === 'string') {
157
    return document.createTextNode(text)
158
  }
159
  const container = document.createElement('div')
160
  container.innerHTML = text.html
161
  const fragment = document.createDocumentFragment()
162
  while (container.firstChild) {
163
    fragment.appendChild(container.firstChild)
164
  }
165
  return fragment
166
}
167

168
startPlayground()
169

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.