Class: Puppeteer::ElementHandle

Inherits:
JSHandle
  • Object
show all
Includes:
DebugPrint, IfPresent
Defined in:
lib/puppeteer/element_handle.rb,
lib/puppeteer/element_handle/point.rb,
lib/puppeteer/element_handle/offset.rb,
lib/puppeteer/element_handle/box_model.rb,
lib/puppeteer/element_handle/bounding_box.rb

Defined Under Namespace

Classes: BoundingBox, BoxModel, DragInterceptionNotEnabledError, ElementNotClickableError, ElementNotFoundError, ElementNotVisibleError, Offset, Point, ScrollIntoViewError

Instance Attribute Summary collapse

Attributes inherited from JSHandle

#context, #remote_object

Instance Method Summary collapse

Methods included from IfPresent

#if_present

Methods included from DebugPrint

#debug_print, #debug_puts

Methods inherited from JSHandle

#[], create, #dispose, #dispose_symbol, #disposed?, #evaluate, #evaluate_handle, #execution_context, #json_value, #move, #properties, #property, #to_s

Constructor Details

#initialize(context:, client:, remote_object:, frame:) ⇒ ElementHandle

Returns a new instance of ElementHandle.



17
18
19
20
21
22
23
# File 'lib/puppeteer/element_handle.rb', line 17

def initialize(context:, client:, remote_object:, frame:)
  super(context: context, client: client, remote_object: remote_object)
  @frame = frame
  @page = frame.page
  @frame_manager = frame.frame_manager
  @disposed = false
end

Instance Attribute Details

#frameObject (readonly)

Returns the value of attribute frame.



25
26
27
# File 'lib/puppeteer/element_handle.rb', line 25

def frame
  @frame
end

#frame_managerObject (readonly)

Returns the value of attribute frame_manager.



25
26
27
# File 'lib/puppeteer/element_handle.rb', line 25

def frame_manager
  @frame_manager
end

#pageObject (readonly)

Returns the value of attribute page.



25
26
27
# File 'lib/puppeteer/element_handle.rb', line 25

def page
  @page
end

Instance Method Details

#as_elementObject



151
152
153
# File 'lib/puppeteer/element_handle.rb', line 151

def as_element
  self
end

#as_locatorObject



156
157
158
# File 'lib/puppeteer/element_handle.rb', line 156

def as_locator
  Puppeteer::NodeLocator.create_from_handle(@frame, self)
end

#autofill(credit_card: nil, address: nil) ⇒ Object



546
547
548
549
550
551
552
553
554
555
# File 'lib/puppeteer/element_handle.rb', line 546

def autofill(credit_card: nil, address: nil)
  node_info = @remote_object.node_info(@client)
  field_id = node_info.dig('node', 'backendNodeId')
  @client.send_message('Autofill.trigger', {
    fieldId: field_id,
    frameId: @frame.id,
    card: credit_card,
    address: address,
  }.compact)
end

#bounding_boxObject



600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
# File 'lib/puppeteer/element_handle.rb', line 600

def bounding_box
  if_present(box_model) do |result_model|
    offset = oopif_offsets(@frame)
    quads = result_model.border

    x = quads.map(&:x).min
    y = quads.map(&:y).min
    BoundingBox.new(
      x: x + offset.x,
      y: y + offset.y,
      width: quads.map(&:x).max - x,
      height: quads.map(&:y).max - y,
    )
  end
end

#box_modelObject



617
618
619
620
621
# File 'lib/puppeteer/element_handle.rb', line 617

def box_model
  if_present(@remote_object.box_model(@client)) do |result|
    BoxModel.new(result['model'], offset: oopif_offsets(@frame))
  end
end

#click(delay: nil, button: nil, click_count: nil, count: nil, offset: nil) ⇒ Object



381
382
383
384
385
# File 'lib/puppeteer/element_handle.rb', line 381

def click(delay: nil, button: nil, click_count: nil, count: nil, offset: nil)
  scroll_into_view_if_needed
  point = clickable_point(offset)
  @page.mouse.click(point.x, point.y, delay: delay, button: button, click_count: click_count, count: count)
end

#clickable_point(offset = nil) ⇒ Object



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/puppeteer/element_handle.rb', line 296

def clickable_point(offset = nil)
  offset_param = Offset.from(offset)

  result =
    begin
      @remote_object.content_quads(@client)
    rescue => err
      debug_puts(err)
      nil
    end

  if !result || result["quads"].empty?
    raise ElementNotVisibleError.new
  end

  # Filter out quads that have too small area to click into.
  layout_metrics = @page.client.send_message('Page.getLayoutMetrics')

  if result.empty? || result["quads"].empty?
    raise ElementNotClickableError.new
  end

  # Filter out quads that have too small area to click into.
  # Prefer cssLayoutViewport when available.
  layout_viewport = layout_metrics["cssLayoutViewport"] || layout_metrics["layoutViewport"]
  client_width = layout_viewport["clientWidth"]
  client_height = layout_viewport["clientHeight"]

  oopif_offset = oopif_offsets(@frame)
  quads = result["quads"].
            map { |quad| from_protocol_quad(quad) }.
            map { |quad| apply_offsets_to_quad(quad, oopif_offset) }.
            map { |quad| intersect_quad_with_viewport(quad, client_width, client_height) }.
            select { |quad| compute_quad_area(quad) > 1 }
  if quads.empty?
    raise ElementNotVisibleError.new
  end

  if offset_param
    # Return the point of the first quad identified by offset.
    quad = quads.first
    min_x = quad.map(&:x).min
    min_y = quad.map(&:y).min
    if min_x && min_y
      return Point.new(
        x: min_x + offset_param.x,
        y: min_y + offset_param.y,
      )
    end
  end

  # Return the middle point of the first quad.
  quads.first.reduce(:+) / 4
end

#content_frameObject



194
195
196
197
198
199
200
201
202
# File 'lib/puppeteer/element_handle.rb', line 194

def content_frame
  node_info = @remote_object.node_info(@client)
  frame_id = node_info['node']['frameId']
  if frame_id.is_a?(String)
    @frame_manager.frame(frame_id)
  else
    nil
  end
end

#drag(x:, y:) ⇒ Object



429
430
431
432
433
434
435
436
# File 'lib/puppeteer/element_handle.rb', line 429

def drag(x:, y:)
  unless @page.drag_interception_enabled?
    raise DragInterceptionNotEnabledError.new
  end
  scroll_into_view_if_needed
  start = clickable_point
  @page.mouse.drag(start, Point.new(x: x, y: y))
end

#drag_and_drop(target, delay: nil) ⇒ Object



465
466
467
468
469
470
# File 'lib/puppeteer/element_handle.rb', line 465

def drag_and_drop(target, delay: nil)
  scroll_into_view_if_needed
  start_point = clickable_point
  target_point = target.clickable_point
  @page.mouse.drag_and_drop(start_point, target_point, delay: delay)
end

#drag_enter(data) ⇒ Object



440
441
442
443
444
# File 'lib/puppeteer/element_handle.rb', line 440

def drag_enter(data)
  scroll_into_view_if_needed
  target = clickable_point
  @page.mouse.drag_enter(target, data)
end

#drag_over(data) ⇒ Object



448
449
450
451
452
# File 'lib/puppeteer/element_handle.rb', line 448

def drag_over(data)
  scroll_into_view_if_needed
  target = clickable_point
  @page.mouse.drag_over(target, data)
end

#drop(data) ⇒ Object



456
457
458
459
460
# File 'lib/puppeteer/element_handle.rb', line 456

def drop(data)
  scroll_into_view_if_needed
  target = clickable_point
  @page.mouse.drop(target, data)
end

#eval_on_selector(selector, page_function, *args) ⇒ Object Also known as: Seval

‘$eval()` in JavaScript.



785
786
787
788
789
790
791
792
793
794
# File 'lib/puppeteer/element_handle.rb', line 785

def eval_on_selector(selector, page_function, *args)
  element_handle = query_selector(selector)
  unless element_handle
    raise ElementNotFoundError.new(selector)
  end
  result = element_handle.evaluate(page_function, *args)
  element_handle.dispose

  result
end

#eval_on_selector_all(selector, page_function, *args) ⇒ Object Also known as: SSeval

‘$$eval()` in JavaScript.



804
805
806
807
808
809
810
# File 'lib/puppeteer/element_handle.rb', line 804

def eval_on_selector_all(selector, page_function, *args)
  handles = query_handler_manager.detect_query_handler(selector).query_all_array(self)
  result = handles.evaluate(page_function, *args)
  handles.dispose

  result
end

#focusObject



572
573
574
# File 'lib/puppeteer/element_handle.rb', line 572

def focus
  evaluate('element => element.focus()')
end

#hidden?Boolean

Returns:

  • (Boolean)


166
167
168
# File 'lib/puppeteer/element_handle.rb', line 166

def hidden?
  check_visibility(false)
end

#hoverObject



369
370
371
372
373
# File 'lib/puppeteer/element_handle.rb', line 369

def hover
  scroll_into_view_if_needed
  point = clickable_point
  @page.mouse.move(point.x, point.y)
end

#inspectObject



28
29
30
31
32
33
34
# File 'lib/puppeteer/element_handle.rb', line 28

def inspect
  values = %i[context remote_object page disposed].map do |sym|
    value = instance_variable_get(:"@#{sym}")
    "@#{sym}=#{value}"
  end
  "#<Puppeteer::ElementHandle #{values.join(' ')}>"
end

#intersecting_viewport?(threshold: nil) ⇒ Boolean

in JS, #isIntersectingViewport.

Returns:

  • (Boolean)


834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
# File 'lib/puppeteer/element_handle.rb', line 834

def intersecting_viewport?(threshold: nil)
  option_threshold = threshold || 0
  js = <<~JAVASCRIPT
  async (element, threshold) => {
    const visibleRatio = await new Promise(resolve => {
      const observer = new IntersectionObserver(entries => {
        resolve(entries[0].intersectionRatio);
        observer.disconnect();
      });
      observer.observe(element);
    });
    if (threshold === 1) return visibleRatio === 1;
    else return visibleRatio > threshold;
  }
  JAVASCRIPT

  evaluate(js, option_threshold)
end

#press(key, delay: nil, text: nil) ⇒ Object



592
593
594
595
# File 'lib/puppeteer/element_handle.rb', line 592

def press(key, delay: nil, text: nil)
  focus
  @page.keyboard.press(key, delay: delay)
end

#query_ax_tree(accessible_name: nil, role: nil) ⇒ Object

used in AriaQueryHandler



863
864
865
866
# File 'lib/puppeteer/element_handle.rb', line 863

def query_ax_tree(accessible_name: nil, role: nil)
  @remote_object.query_ax_tree(@client,
    accessible_name: accessible_name, role: role)
end

#query_selector(selector) ⇒ Object Also known as: S

‘$()` in JavaScript.



754
755
756
# File 'lib/puppeteer/element_handle.rb', line 754

def query_selector(selector)
  query_selector_in_isolated_world(selector)
end

#query_selector_all(selector, isolate: nil) ⇒ Object Also known as: SS

‘$$()` in JavaScript.



763
764
765
766
767
768
769
770
# File 'lib/puppeteer/element_handle.rb', line 763

def query_selector_all(selector, isolate: nil)
  if isolate == false
    results = query_handler_manager.detect_query_handler(selector).query_all(self)
    return results || []
  end

  query_selector_all_in_isolated_world(selector)
end

#screenshot(type: nil, path: nil, full_page: nil, clip: nil, quality: nil, omit_background: nil, encoding: nil, capture_beyond_viewport: nil, from_surface: nil) ⇒ Object



633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
# File 'lib/puppeteer/element_handle.rb', line 633

def screenshot(type: nil,
               path: nil,
               full_page: nil,
               clip: nil,
               quality: nil,
               omit_background: nil,
               encoding: nil,
               capture_beyond_viewport: nil,
               from_surface: nil)
  needs_viewport_reset = false

  box = bounding_box
  unless box
    raise ElementNotVisibleError.new
  end

  viewport = @page.viewport
  if viewport && (box.width > viewport.width || box.height > viewport.height)
    new_viewport = viewport.merge(
      width: [viewport.width, box.width.to_i].min,
      height: [viewport.height, box.height.to_i].min,
    )
    @page.viewport = new_viewport

    needs_viewport_reset = true
  end
  scroll_into_view_if_needed

  box = bounding_box
  unless box
    raise ElementNotVisibleError.new
  end
  if box.width == 0
    raise 'Node has 0 width.'
  end
  if box.height == 0
    raise 'Node has 0 height.'
  end

  layout_metrics = @client.send_message('Page.getLayoutMetrics')
  page_x = layout_metrics["layoutViewport"]["pageX"]
  page_y = layout_metrics["layoutViewport"]["pageY"]

  if clip.nil?
    clip = {
      x: page_x + box.x,
      y: page_y + box.y,
      width: box.width,
      height: box.height,
    }
  end

  @page.screenshot(
    type: type,
    path: path,
    full_page:
    full_page,
    clip: clip,
    quality: quality,
    omit_background: omit_background,
    encoding: encoding,
    capture_beyond_viewport: capture_beyond_viewport,
    from_surface: from_surface)
ensure
  if needs_viewport_reset && viewport
    @page.viewport = viewport
  end
end

#scroll_into_view_if_neededObject



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/puppeteer/element_handle.rb', line 207

def scroll_into_view_if_needed
  js = <<~JAVASCRIPT
    async(element) => {
      if (!element.isConnected)
        return 'Node is detached from document';
      if (element.nodeType !== Node.ELEMENT_NODE)
        return 'Node is not of type HTMLElement';
      return false;
    }
  JAVASCRIPT
  error = evaluate(js) # returns String or false
  if error
    raise ScrollIntoViewError.new(error)
  end
  begin
    @remote_object.scroll_into_view_if_needed(@client)
  rescue
    # Fallback to Element.scrollIntoView if DOM.scrollIntoViewIfNeeded is not supported
    js = <<~JAVASCRIPT
      async (element, pageJavascriptEnabled) => {
        const visibleRatio = async () => {
          return await new Promise(resolve => {
            const observer = new IntersectionObserver(entries => {
              resolve(entries[0].intersectionRatio);
              observer.disconnect();
            });
            observer.observe(element);
          });
        };
        if (!pageJavascriptEnabled || (await visibleRatio()) !== 1.0) {
          element.scrollIntoView({
            block: 'center',
            inline: 'center',
            // @ts-expect-error Chrome still supports behavior: instant but
            // it's not in the spec so TS shouts We don't want to make this
            // breaking change in Puppeteer yet so we'll ignore the line.
            behavior: 'instant',
          });
        }
      }
    JAVASCRIPT
    evaluate(js, page.javascript_enabled?)
  end

  # clickpoint is often calculated before scrolling is completed.
  # So, just sleep about 10 frames
  sleep 0.16
end

#select(*values) ⇒ Object



474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/puppeteer/element_handle.rb', line 474

def select(*values)
  if nonstring = values.find { |value| !value.is_a?(String) }
    raise ArgumentError.new("Values must be strings. Found value \"#{nonstring}\" of type \"#{nonstring.class}\"")
  end

  fn = <<~JAVASCRIPT
  (element, vals) => {
    const values = new Set(vals);
    if (element.nodeName.toLowerCase() !== 'select') {
      throw new Error('Element is not a <select> element.');
    }

    const selectedValues = new Set();
    if (!element.multiple) {
      for (const option of element.options) {
        option.selected = false;
      }
      for (const option of element.options) {
        if (values.has(option.value)) {
          option.selected = true;
          selectedValues.add(option.value);
          break;
        }
      }
    } else {
      for (const option of element.options) {
        option.selected = values.has(option.value);
        if (option.selected) {
          selectedValues.add(option.value);
        }
      }
    }
    element.dispatchEvent(new Event('input', { bubbles: true }));
    element.dispatchEvent(new Event('change', { bubbles: true }));
    return [...selectedValues.values()];
  }
  JAVASCRIPT
  evaluate(fn, values)
end

#Sx(expression) ⇒ Object

‘$x()` in JavaScript. $ is not allowed to use as a method name in Ruby.



818
819
820
821
822
823
824
825
826
827
# File 'lib/puppeteer/element_handle.rb', line 818

def Sx(expression)
  param_xpath =
    if expression.start_with?('//')
      ".#{expression}"
    else
      expression
    end

  query_selector_all("xpath/#{param_xpath}")
end

#tap(&block) ⇒ Object



561
562
563
564
565
566
567
# File 'lib/puppeteer/element_handle.rb', line 561

def tap(&block)
  return super(&block) if block

  scroll_into_view_if_needed
  point = clickable_point
  @page.touchscreen.tap(point.x, point.y)
end

#to_element(tag_name) ⇒ Object



143
144
145
146
147
148
# File 'lib/puppeteer/element_handle.rb', line 143

def to_element(tag_name)
  unless evaluate('(node, tagName) => node.nodeName === tagName.toUpperCase()', tag_name)
    raise ArgumentError.new("Element is not a(n) `#{tag_name}` element")
  end
  self
end

#touch_endObject



413
414
415
416
# File 'lib/puppeteer/element_handle.rb', line 413

def touch_end
  scroll_into_view_if_needed
  @page.touchscreen.touch_end
end

#touch_move(touch = nil) ⇒ Object



400
401
402
403
404
405
406
407
408
# File 'lib/puppeteer/element_handle.rb', line 400

def touch_move(touch = nil)
  scroll_into_view_if_needed
  point = clickable_point
  if touch
    touch.move(point.x, point.y)
  else
    @page.touchscreen.touch_move(point.x, point.y)
  end
end

#touch_startObject



390
391
392
393
394
# File 'lib/puppeteer/element_handle.rb', line 390

def touch_start
  scroll_into_view_if_needed
  point = clickable_point
  @page.touchscreen.touch_start(point.x, point.y)
end

#type_text(text, delay: nil) ⇒ Object



581
582
583
584
# File 'lib/puppeteer/element_handle.rb', line 581

def type_text(text, delay: nil)
  focus
  @page.keyboard.type_text(text, delay: delay)
end

#upload_file(*file_paths) ⇒ Object



516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
# File 'lib/puppeteer/element_handle.rb', line 516

def upload_file(*file_paths)
  is_multiple = evaluate("el => el.multiple")
  if !is_multiple && file_paths.length >= 2
    raise ArgumentError.new('Multiple file uploads only work with <input type=file multiple>')
  end

  backend_node_id = @remote_object.node_info(@client)["node"]["backendNodeId"]

  # The zero-length array is a special case, it seems that DOM.setFileInputFiles does
  # not actually update the files in that case, so the solution is to eval the element
  # value to a new FileList directly.
  if file_paths.empty?
    fn = <<~JAVASCRIPT
    (element) => {
      element.files = new DataTransfer().files;

      // Dispatch events for this case because it should behave akin to a user action.
      element.dispatchEvent(new Event('input', { bubbles: true }));
      element.dispatchEvent(new Event('change', { bubbles: true }));
    }
    JAVASCRIPT
    evaluate(fn)
  else
    @remote_object.set_file_input_files(@client, file_paths.map { |path| File.expand_path(path) }, backend_node_id)
  end
end

#visible?Boolean

Returns:

  • (Boolean)


161
162
163
# File 'lib/puppeteer/element_handle.rb', line 161

def visible?
  check_visibility(true)
end

#wait_for_selector(selector, visible: nil, hidden: nil, timeout: nil) ⇒ Object

Wait for the ‘selector` to appear within the element. If at the moment of calling the method the `selector` already exists, the method will return immediately. If the `selector` doesn’t appear after the ‘timeout` milliseconds of waiting, the function will throw.

This method does not work across navigations or if the element is detached from DOM.

developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors | selector of an element to wait for is added to DOM. Resolves to ‘null` if waiting for hidden: `true` and selector is not found in DOM. The optional parameters in `options` are:

  • ‘visible`: wait for the selected element to be present in DOM and to be

visible, i.e. to not have ‘display: none` or `visibility: hidden` CSS properties. Defaults to `false`.

  • ‘hidden`: wait for the selected element to not be found in the DOM or to be hidden,

i.e. have ‘display: none` or `visibility: hidden` CSS properties. Defaults to `false`.

  • ‘timeout`: maximum time to wait in milliseconds. Defaults to `30000`

(30 seconds). Pass ‘0` to disable timeout. The default value can be changed by using the Page.setDefaultTimeout method.



67
68
69
70
71
72
73
74
# File 'lib/puppeteer/element_handle.rb', line 67

def wait_for_selector(selector, visible: nil, hidden: nil, timeout: nil)
  query_handler_manager.detect_query_handler(selector).wait_for(
    self,
    visible: visible,
    hidden: hidden,
    timeout: timeout,
  )
end

#wait_for_xpath(xpath, visible: nil, hidden: nil, timeout: nil) ⇒ Object

Wait for the ‘xpath` within the element. If at the moment of calling the method the `xpath` already exists, the method will return immediately. If the `xpath` doesn’t appear after the ‘timeout` milliseconds of waiting, the function will throw.

If ‘xpath` starts with `//` instead of `.//`, the dot will be appended automatically.

This method works across navigation “‘js const puppeteer = require(’puppeteer’); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); let currentURL; page .waitForXPath(‘//img’) .then(() => console.log(‘First URL with image: ’ + currentURL)); for (currentURL of [ ‘example.com’, ‘google.com’, ‘bbc.com’, ]) { await page.goto(currentURL); } await browser.close(); })(); “‘ developer.mozilla.org/en-US/docs/Web/XPath | xpath of an element to wait for added to DOM. Resolves to `null` if waiting for `hidden: true` and xpath is not found in DOM. The optional Argument `options` have properties:

  • ‘visible`: A boolean to wait for element to be present in DOM and to be

visible, i.e. to not have ‘display: none` or `visibility: hidden` CSS properties. Defaults to `false`.

  • ‘hidden`: A boolean wait for element to not be found in the DOM or to be

hidden, i.e. have ‘display: none` or `visibility: hidden` CSS properties. Defaults to `false`.

  • ‘timeout`: A number which is maximum time to wait for in milliseconds.

Defaults to ‘30000` (30 seconds). Pass `0` to disable timeout. The default value can be changed by using the Page.setDefaultTimeout method.



128
129
130
131
132
133
134
135
136
137
# File 'lib/puppeteer/element_handle.rb', line 128

def wait_for_xpath(xpath, visible: nil, hidden: nil, timeout: nil)
  param_xpath =
    if xpath.start_with?('//')
      ".#{xpath}"
    else
      xpath
    end

  wait_for_selector("xpath/#{param_xpath}", visible: visible, hidden: hidden, timeout: timeout)
end