vendor/github.com/go-rod/rod/lib/js/helper.js

572 lines · 14475 bytes

  1// The reason to use an extra js file to hold the functions is the lint and IDE support.
  2// To debug just add "debugger" keyword to the line you want to pause, then run something like:
  3//
  4//     go run ./lib/js/generate/main.go
  5//     go test -run ^TestClick$ -- -rod=show,devtools
  6
  7const functions = {
  8  element(selector) {
  9    const s = functions.selectable(this)
 10    return s.querySelector(selector)
 11  },
 12
 13  triggerFavicon() {
 14    return new Promise((resolve, reject) => {
 15      const faviconElement = document.querySelector('link[rel~=icon]')
 16      const href = (faviconElement && faviconElement.href) || '/favicon.ico'
 17      const faviconUrl = new URL(href, window.location).toString()
 18      const xhr = new XMLHttpRequest()
 19      xhr.open('GET', faviconUrl)
 20
 21      xhr.ontimeout = function () {
 22        reject({
 23          errorType: 'timeout_error',
 24          xhr: xhr
 25        })
 26      }
 27
 28      xhr.onreadystatechange = function () {
 29        if (xhr.readyState === 4) {
 30          if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
 31            resolve({
 32              status: xhr.status,
 33              statusText: xhr.statusText,
 34              responseText: xhr.responseText
 35            })
 36          } else {
 37            reject({
 38              errorType: 'status_error',
 39              xhr: xhr,
 40              status: xhr.status,
 41              statusText: xhr.statusText,
 42              responseText: xhr.responseText
 43            })
 44          }
 45        }
 46      }
 47
 48      xhr.onerror = function () {
 49        reject({
 50          errorType: 'onerror',
 51          xhr: xhr,
 52          status: xhr.status,
 53          statusText: xhr.statusText,
 54          responseText: xhr.responseText
 55        })
 56      }
 57      xhr.send()
 58    })
 59  },
 60
 61  elements(selector) {
 62    return functions.selectable(this).querySelectorAll(selector)
 63  },
 64
 65  elementX(xPath) {
 66    const s = functions.selectable(this)
 67    return document.evaluate(
 68      xPath,
 69      s,
 70      null,
 71      XPathResult.FIRST_ORDERED_NODE_TYPE
 72    ).singleNodeValue
 73  },
 74
 75  elementsX(xpath) {
 76    const s = functions.selectable(this)
 77    const iter = document.evaluate(
 78      xpath,
 79      s,
 80      null,
 81      XPathResult.ORDERED_NODE_ITERATOR_TYPE
 82    )
 83    const list = []
 84    let el
 85    while ((el = iter.iterateNext())) list.push(el)
 86    return list
 87  },
 88
 89  elementR(selector, regex) {
 90    var reg
 91    var m = regex.match(/(\/?)(.+)\1([a-z]*)/i)
 92    // cSpell:ignore gmix
 93    if (m[3] && !/^(?!.*?(.).*?\1)[gmixXsuUAJ]+$/.test(m[3]))
 94      reg = new RegExp(regex)
 95    else reg = new RegExp(m[2], m[3])
 96
 97    const s = functions.selectable(this)
 98    const el = Array.from(s.querySelectorAll(selector)).find((e) =>
 99      reg.test(functions.text.call(e))
100    )
101    return el ? el : null
102  },
103
104  parents(selector) {
105    let p = this.parentElement
106    const list = []
107    while (p) {
108      if (p.matches(selector)) {
109        list.push(p)
110      }
111      p = p.parentElement
112    }
113    return list
114  },
115
116  containsElement(target) {
117    var node = target
118    while (node != null) {
119      if (node === this) {
120        return true
121      }
122      node = node.parentElement
123    }
124    return false
125  },
126
127  async initMouseTracer(iconId, icon) {
128    await functions.waitLoad()
129
130    if (document.getElementById(iconId)) {
131      return
132    }
133
134    const tmp = document.createElement('div')
135    tmp.innerHTML = icon
136    const svg = tmp.lastChild
137    svg.id = iconId
138    svg.style =
139      'position: absolute; z-index: 2147483647; width: 17px; pointer-events: none;'
140    svg.removeAttribute('width')
141    svg.removeAttribute('height')
142    document.body.parentElement.appendChild(svg)
143  },
144
145  updateMouseTracer(iconId, x, y) {
146    const svg = document.getElementById(iconId)
147    if (!svg) {
148      return false
149    }
150    svg.style.left = x - 2 + 'px'
151    svg.style.top = y - 3 + 'px'
152    return true
153  },
154
155  rect() {
156    const b = functions.tag(this).getBoundingClientRect()
157    return { x: b.x, y: b.y, width: b.width, height: b.height }
158  },
159
160  async overlay(id, left, top, width, height, msg) {
161    await functions.waitLoad()
162
163    const div = document.createElement('div')
164    div.id = id
165    div.style = `position: fixed; z-index:2147483647; border: 2px dashed red;
166        border-radius: 3px; box-shadow: #5f3232 0 0 3px; pointer-events: none;
167        box-sizing: border-box;
168        left: ${left}px;
169        top: ${top}px;
170        height: ${height}px;
171        width: ${width}px;`
172
173    if (width * height === 0) {
174      div.style.border = 'none'
175    }
176
177    if (!msg) {
178      document.body.parentElement.appendChild(div)
179      return
180    }
181
182    const msgDiv = document.createElement('div')
183    msgDiv.style = `position: absolute; color: #cc26d6; font-size: 12px; background: #ffffffeb;
184        box-shadow: #333 0 0 3px; padding: 2px 5px; border-radius: 3px; white-space: nowrap;
185        top: ${height}px;`
186
187    msgDiv.innerHTML = msg
188    div.appendChild(msgDiv)
189    document.body.parentElement.appendChild(div)
190
191    if (window.innerHeight < msgDiv.offsetHeight + top + height) {
192      msgDiv.style.top = -msgDiv.offsetHeight - 2 + 'px'
193    }
194
195    if (window.innerWidth < msgDiv.offsetWidth + left) {
196      msgDiv.style.left = window.innerWidth - msgDiv.offsetWidth - left + 'px'
197    }
198  },
199
200  async elementOverlay(id, msg) {
201    const interval = 100
202    const el = functions.tag(this)
203
204    let pre = el.getBoundingClientRect()
205    await functions.overlay(id, pre.left, pre.top, pre.width, pre.height, msg)
206
207    const update = () => {
208      const overlay = document.getElementById(id)
209      if (overlay === null) return
210
211      const box = el.getBoundingClientRect()
212      if (
213        pre.left === box.left &&
214        pre.top === box.top &&
215        pre.width === box.width &&
216        pre.height === box.height
217      ) {
218        setTimeout(update, interval)
219        return
220      }
221
222      overlay.style.left = box.left + 'px'
223      overlay.style.top = box.top + 'px'
224      overlay.style.width = box.width + 'px'
225      overlay.style.height = box.height + 'px'
226      pre = box
227
228      setTimeout(update, interval)
229    }
230
231    setTimeout(update, interval)
232  },
233
234  removeOverlay(id) {
235    const el = document.getElementById(id)
236    // prevent override like prototype.js
237    el && Element.prototype.remove.call(el)
238  },
239
240  waitIdle(timeout) {
241    return new Promise((resolve) => {
242      window.requestIdleCallback(resolve, { timeout })
243    })
244  },
245
246  waitLoad() {
247    const isWin = this === window
248    return new Promise((resolve, reject) => {
249      if (isWin) {
250        if (document.readyState === 'complete') return resolve()
251        window.addEventListener('load', resolve)
252      } else {
253        if (this.complete === undefined || this.complete) {
254          resolve()
255        } else {
256          this.addEventListener('load', resolve)
257          this.addEventListener('error', reject)
258        }
259      }
260    })
261  },
262
263  inputEvent() {
264    this.dispatchEvent(new Event('input', { bubbles: true }))
265    this.dispatchEvent(new Event('change', { bubbles: true }))
266  },
267
268  inputTime(stamp) {
269    const time = new Date(stamp)
270
271    const pad = (n) => n.toString().padStart(2, '0')
272
273    const y = time.getFullYear()
274    const mon = pad(time.getMonth() + 1)
275    const d = pad(time.getDate())
276    const h = pad(time.getHours())
277    const min = pad(time.getMinutes())
278
279    switch (this.type) {
280      case 'date':
281        this.value = `${y}-${mon}-${d}`
282        break
283      case 'datetime-local':
284        this.value = `${y}-${mon}-${d}T${h}:${min}`
285        break
286      case 'month':
287        this.value = `${y}-${mon}`
288        break
289      case 'time':
290        this.value = `${h}:${min}`
291        break
292    }
293
294    functions.inputEvent.call(this)
295  },
296
297  inputColor(color) {
298    this.value = `${color}`
299
300    functions.inputEvent.call(this)
301  },
302  selectText(pattern) {
303    const m = this.value.match(new RegExp(pattern))
304    if (m) {
305      this.setSelectionRange(m.index, m.index + m[0].length)
306    }
307  },
308
309  selectAllText() {
310    this.select()
311  },
312
313  select(selectors, selected, type) {
314    let matchers
315    switch (type) {
316      case 'regex':
317        matchers = selectors.map((s) => {
318          const reg = new RegExp(s)
319          return (el) => reg.test(el.innerText)
320        })
321        break
322      case 'css-selector':
323        matchers = selectors.map((s) => (el) => el.matches(s))
324        break
325      default:
326        matchers = selectors.map((s) => (el) => el.innerText.includes(s))
327        break
328    }
329
330    const opts = Array.from(this.options)
331    let has = false
332    matchers.forEach((s) => {
333      const el = opts.find(s)
334      if (el) {
335        el.selected = selected
336        has = true
337        return
338      }
339    })
340
341    this.dispatchEvent(new Event('input', { bubbles: true }))
342    this.dispatchEvent(new Event('change', { bubbles: true }))
343
344    return has
345  },
346
347  visible() {
348    const el = functions.tag(this)
349    const box = el.getBoundingClientRect()
350    const style = window.getComputedStyle(el)
351    return (
352      style.display !== 'none' &&
353      style.visibility !== 'hidden' &&
354      !!(box.top || box.bottom || box.width || box.height)
355    )
356  },
357
358  invisible() {
359    return !functions.visible.apply(this)
360  },
361
362  text() {
363    switch (this.tagName) {
364      case 'INPUT':
365      case 'TEXTAREA':
366        return this.value || this.placeholder
367      case 'SELECT':
368        return Array.from(this.selectedOptions)
369          .map((el) => el.innerText)
370          .join()
371      case undefined:
372        return this.textContent
373      default:
374        return this.innerText
375    }
376  },
377
378  resource() {
379    return new Promise((resolve, reject) => {
380      if (this.complete) {
381        return resolve(this.currentSrc)
382      }
383      this.addEventListener('load', () => resolve(this.currentSrc))
384      this.addEventListener('error', (e) => reject(e))
385    })
386  },
387
388  addScriptTag(id, url, content) {
389    if (document.getElementById(id)) return
390
391    return new Promise((resolve, reject) => {
392      var s = document.createElement('script')
393
394      if (url) {
395        s.src = url
396        s.onload = resolve
397      } else {
398        s.type = 'text/javascript'
399        s.text = content
400        resolve()
401      }
402
403      s.id = id
404      s.onerror = reject
405      document.head.appendChild(s)
406    })
407  },
408
409  addStyleTag(id, url, content) {
410    if (document.getElementById(id)) return
411
412    return new Promise((resolve, reject) => {
413      var el
414
415      if (url) {
416        el = document.createElement('link')
417        el.rel = 'stylesheet'
418        el.href = url
419      } else {
420        el = document.createElement('style')
421        el.type = 'text/css'
422        el.appendChild(document.createTextNode(content))
423        resolve()
424      }
425
426      el.id = id
427      el.onload = resolve
428      el.onerror = reject
429      document.head.appendChild(el)
430    })
431  },
432
433  selectable(s) {
434    return s.querySelector ? s : document
435  },
436
437  tag(el) {
438    return el.tagName ? el : el.parentElement
439  },
440
441  exposeFunc(name, bind) {
442    let callbackCount = 0
443    window[name] = (req) =>
444      new Promise((resolve, reject) => {
445        const cb = bind + '_cb' + callbackCount++
446        window[cb] = (res, err) => {
447          delete window[cb]
448          err ? reject(err) : resolve(res)
449        }
450        window[bind](JSON.stringify({ req, cb }))
451      })
452  },
453
454  getXPath(optimized) {
455    class Step {
456      constructor(value, optimized) {
457        this.value = value
458        this.optimized = optimized || false
459      }
460      toString() {
461        return this.value
462      }
463    }
464    const xPathValue = function xPathValue(node, optimized) {
465      let ownValue
466      const ownIndex = xPathIndex(node)
467      if (ownIndex === -1) {
468        return null
469      }
470      switch (node.nodeType) {
471        case Node.ELEMENT_NODE:
472          if (optimized && node.id) {
473            return new Step(`//*[@id='${node.id}']`, true)
474          }
475          ownValue = node.localName
476          break
477        case Node.ATTRIBUTE_NODE:
478          ownValue = `@${node.nodeName}`
479          break
480        case Node.TEXT_NODE:
481        case Node.CDATA_SECTION_NODE:
482          ownValue = 'text()'
483          break
484        case Node.PROCESSING_INSTRUCTION_NODE:
485          ownValue = 'processing-instruction()'
486          break
487        case Node.COMMENT_NODE:
488          ownValue = 'comment()'
489          break
490        case Node.DOCUMENT_NODE:
491          ownValue = ''
492          break
493        default:
494          ownValue = ''
495          break
496      }
497      if (ownIndex > 0) {
498        ownValue += `[${ownIndex}]`
499      }
500      return new Step(ownValue, node.nodeType === Node.DOCUMENT_NODE)
501    }
502    const xPathIndex = function xPathIndex(node) {
503      function areNodesSimilar(left, right) {
504        if (left === right) {
505          return true
506        }
507        if (
508          left.nodeType === Node.ELEMENT_NODE &&
509          right.nodeType === Node.ELEMENT_NODE
510        ) {
511          return left.localName === right.localName
512        }
513        if (left.nodeType === right.nodeType) {
514          return true
515        }
516        const leftType =
517          left.nodeType === Node.CDATA_SECTION_NODE
518            ? Node.TEXT_NODE
519            : left.nodeType
520        const rightType =
521          right.nodeType === Node.CDATA_SECTION_NODE
522            ? Node.TEXT_NODE
523            : right.nodeType
524        return leftType === rightType
525      }
526      const parentNode = node.parentNode
527      const siblings = parentNode ? parentNode.children : null
528      if (!siblings) {
529        return 0
530      }
531      let hasSameNamedElements
532      for (let i = 0; i < siblings.length; ++i) {
533        if (areNodesSimilar(node, siblings[i]) && !(siblings[i] === node)) {
534          hasSameNamedElements = true
535          break
536        }
537      }
538      if (!hasSameNamedElements) {
539        return 0
540      }
541      let ownIndex = 1
542      for (let i = 0; i < siblings.length; ++i) {
543        if (areNodesSimilar(node, siblings[i])) {
544          if (siblings[i] === node) {
545            return ownIndex
546          }
547          ++ownIndex
548        }
549      }
550      return -1
551    }
552    const node = this
553    if (node.nodeType === Node.DOCUMENT_NODE) {
554      return '/'
555    }
556    const steps = []
557    let contextNode = node
558    while (contextNode) {
559      const step = xPathValue(contextNode, optimized)
560      if (!step) {
561        break
562      }
563      steps.push(step)
564      if (step.optimized) {
565        break
566      }
567      contextNode = contextNode.parentNode
568    }
569    steps.reverse()
570    return (steps.length && steps[0].optimized ? '' : '/') + steps.join('/')
571  }
572}