Class: Puppeteer::Page

Inherits:
Object
  • Object
show all
Includes:
DebugPrint, EventCallbackable, IfPresent
Defined in:
lib/puppeteer/page.rb,
lib/puppeteer/page/metrics.rb,
lib/puppeteer/page/pdf_options.rb,
lib/puppeteer/page/screenshot_options.rb,
lib/puppeteer/page/screenshot_task_queue.rb,
sig/puppeteer/page.rbs

Defined Under Namespace

Classes: JavaScriptExpression, JavaScriptFunction, Metrics, MetricsEvent, PDFOptions, PageError, PrintToPdfIsNotImplementedError, ScreenshotOptions, ScreenshotTaskQueue, TargetCrashedError

Constant Summary collapse

VISION_DEFICIENCY_TYPES =

Returns:

  • (Object)
%w[
  none
  achromatopsia
  blurredVision
  deuteranopia
  protanopia
  tritanopia
].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from IfPresent

#if_present

Methods included from EventCallbackable

#add_event_listener, #emit_event, #observe_first, #on_event, #remove_event_listener

Methods included from DebugPrint

#debug_print, #debug_puts

Constructor Details

#initialize(client, target, ignore_https_errors, network_enabled: true) ⇒ Page

Returns a new instance of Page.

Parameters:



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/puppeteer/page.rb', line 39

def initialize(client, target, ignore_https_errors, network_enabled: true)
  @closed = false
  @client = client
  @target = target
  @tab_session = client.parent_session || client
  @tab_target = @tab_session.target || target
  @tab_id = @tab_target.target_id
  @keyboard = Puppeteer::Keyboard.new(client)
  @mouse = Puppeteer::Mouse.new(client, @keyboard)
  @timeout_settings = Puppeteer::TimeoutSettings.new
  @touchscreen = Puppeteer::TouchScreen.new(client, @keyboard)
  @frame_manager = Puppeteer::FrameManager.new(client, self, ignore_https_errors, @timeout_settings, network_enabled: network_enabled)
  @emulation_manager = Puppeteer::EmulationManager.new(client)
  @tracing = Puppeteer::Tracing.new(client)
  @webmcp = Puppeteer::WebMCP.new(client, @frame_manager)
  @page_bindings = {}
  @page_binding_ids = {}
  @coverage = Puppeteer::Coverage.new(client)
  @javascript_enabled = true
  @screenshot_task_queue = ScreenshotTaskQueue.new
  @screencast_session_count = 0
  @screencast_start_promise = nil
  @screencast_mutex = Mutex.new
  @inflight_requests = Set.new
  @request_intercepted_listener_map = ObjectSpace::WeakMap.new
  @attached_sessions = Set.new
  @primary_session_listener_ids = []

  @workers = {}
  @user_drag_interception_enabled = false
  @service_worker_bypassed = false

  @swapped_session_listener_id = @tab_session.add_event_listener(CDPSessionEmittedEvents::Swapped) do |session|
    Async do
      handle_activation(session)
    rescue => err
      debug_puts(err)
    end
  end
  @secondary_session_listener_id = @tab_session.add_event_listener(CDPSessionEmittedEvents::Ready) do |session|
    handle_secondary_target(session)
  end
  @target_manager = @target.target_manager
  @target_gone_listener_id = @target_manager.add_event_listener(
    TargetManagerEmittedEvents::TargetGone,
    &method(:handle_detached_from_target)
  )

  @frame_manager.on_event(FrameManagerEmittedEvents::FrameAttached) do |event|
    emit_event(PageEmittedEvents::FrameAttached, event)
  end
  @frame_manager.on_event(FrameManagerEmittedEvents::FrameDetached) do |event|
    emit_event(PageEmittedEvents::FrameDetached, event)
  end
  @frame_manager.on_event(FrameManagerEmittedEvents::FrameNavigated) do |event|
    emit_event(PageEmittedEvents::FrameNavigated, event)
  end

  network_manager = @frame_manager.network_manager
  network_manager.on_event(NetworkManagerEmittedEvents::Request) do |event|
    @inflight_requests.add(event)
    emit_event(PageEmittedEvents::Request, event)
  end
  network_manager.on_event(NetworkManagerEmittedEvents::Response) do |event|
    emit_event(PageEmittedEvents::Response, event)
  end
  network_manager.on_event(NetworkManagerEmittedEvents::RequestServedFromCache) do |event|
    emit_event(PageEmittedEvents::RequestServedFromCache, event)
  end
  network_manager.on_event(NetworkManagerEmittedEvents::RequestFailed) do |event|
    @inflight_requests.delete(event)
    emit_event(PageEmittedEvents::RequestFailed, event)
  end
  network_manager.on_event(NetworkManagerEmittedEvents::RequestFinished) do |event|
    @inflight_requests.delete(event)
    emit_event(PageEmittedEvents::RequestFinished, event)
  end
  @file_chooser_interception_is_disabled = false
  @file_chooser_interceptors = Set.new

  setup_primary_target_listeners(@client)
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.

Returns:

  • (Object)


392
393
394
# File 'lib/puppeteer/page.rb', line 392

def client
  @client
end

#coverageObject (readonly)

Returns the value of attribute coverage.

Returns:

  • (Object)


488
489
490
# File 'lib/puppeteer/page.rb', line 488

def coverage
  @coverage
end

#javascript_enabledObject Also known as: javascript_enabled?

Returns the value of attribute javascript_enabled.

Returns:

  • (Object)


392
393
394
# File 'lib/puppeteer/page.rb', line 392

def javascript_enabled
  @javascript_enabled
end

#mouseObject (readonly)

Returns the value of attribute mouse.

Returns:

  • (Object)


1869
1870
1871
# File 'lib/puppeteer/page.rb', line 1869

def mouse
  @mouse
end

#service_worker_bypassedObject Also known as: service_worker_bypassed?

Returns the value of attribute service_worker_bypassed.

Returns:

  • (Object)


392
393
394
# File 'lib/puppeteer/page.rb', line 392

def service_worker_bypassed
  @service_worker_bypassed
end

#targetObject (readonly)

Returns the value of attribute target.

Returns:

  • (Object)


392
393
394
# File 'lib/puppeteer/page.rb', line 392

def target
  @target
end

#touchscreenObject (readonly) Also known as: touch_screen

Returns the value of attribute touchscreen.

Returns:

  • (Object)


488
489
490
# File 'lib/puppeteer/page.rb', line 488

def touchscreen
  @touchscreen
end

#tracingObject (readonly)

Returns the value of attribute tracing.

Returns:

  • (Object)


488
489
490
# File 'lib/puppeteer/page.rb', line 488

def tracing
  @tracing
end

#viewportObject

Returns the value of attribute viewport.

Returns:

  • (Object)


1458
1459
1460
# File 'lib/puppeteer/page.rb', line 1458

def viewport
  @viewport
end

#webmcpObject (readonly)

Returns the value of attribute webmcp.

Returns:

  • (Object)


488
489
490
# File 'lib/puppeteer/page.rb', line 488

def webmcp
  @webmcp
end

Class Method Details

.create(client, target, ignore_https_errors, default_viewport, network_enabled: true) ⇒ Puppeteer::Page

Parameters:

Returns:



25
26
27
28
29
30
31
32
# File 'lib/puppeteer/page.rb', line 25

def self.create(client, target, ignore_https_errors, default_viewport, network_enabled: true)
  page = Puppeteer::Page.new(client, target, ignore_https_errors, network_enabled: network_enabled)
  page.init
  if default_viewport
    page.viewport = default_viewport
  end
  page
end

Instance Method Details

#==(other) ⇒ Boolean

Parameters:

  • other (Object)

Returns:

  • (Boolean)


404
405
406
407
408
409
410
411
# File 'lib/puppeteer/page.rb', line 404

def ==(other)
  other = other.__getobj__ if other.is_a?(Puppeteer::ReactorRunner::Proxy)
  return true if equal?(other)
  return false unless other.is_a?(Puppeteer::Page)
  return false unless @target&.target_id && other.target&.target_id

  @target.target_id == other.target.target_id
end

#_start_screencastvoid

This method returns an undefined value.



1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
# File 'lib/puppeteer/page.rb', line 1516

def _start_screencast
  start_promise, first_session = @screencast_mutex.synchronize do
    @screencast_session_count += 1
    next [@screencast_start_promise, false] if @screencast_start_promise

    @screencast_start_promise = Async::Promise.new
    [@screencast_start_promise, true]
  end
  if first_session
    first_frame = Async::Promise.new
    client = main_frame.client
    listener_id = client.once('Page.screencastFrame') do
      first_frame.resolve(nil) unless first_frame.resolved?
    end
    begin
      client.send_message('Page.startScreencast', format: 'png')
      first_frame.wait
      start_promise.resolve(nil)
    rescue => error
      start_promise.reject(error) unless start_promise.resolved?
    ensure
      client.remove_event_listener(listener_id) if listener_id
    end
  end
  start_promise.wait
end

#_stop_screencastvoid

This method returns an undefined value.



1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
# File 'lib/puppeteer/page.rb', line 1544

def _stop_screencast
  should_stop = @screencast_mutex.synchronize do
    @screencast_session_count -= 1 if @screencast_session_count.positive?
    next false unless @screencast_start_promise

    @screencast_start_promise = nil
    @screencast_session_count.zero?
  end
  main_frame.client.send_message('Page.stopScreencast') if should_stop
end

#_tab_idString

Returns:

  • (String)


395
396
397
398
399
400
# File 'lib/puppeteer/page.rb', line 395

def _tab_id
  return @tab_id if @tab_id

  parent_session = @client.respond_to?(:parent_session) ? @client.parent_session : nil
  @tab_id = parent_session&.target&.target_id || @target.target_id
end

#accessibilityPuppeteer::Accessibility



492
493
494
# File 'lib/puppeteer/page.rb', line 492

def accessibility
  main_frame.accessibility
end

#add_script_tag(url: nil, path: nil, content: nil, type: nil, id: nil) ⇒ Puppeteer::ElementHandle

Parameters:

  • url: (String, nil) (defaults to: nil)
  • path: (String, nil) (defaults to: nil)
  • content: (String, nil) (defaults to: nil)
  • type: (String, nil) (defaults to: nil)
  • id: (String, nil) (defaults to: nil)

Returns:



726
727
728
# File 'lib/puppeteer/page.rb', line 726

def add_script_tag(url: nil, path: nil, content: nil, type: nil, id: nil)
  main_frame.add_script_tag(url: url, path: path, content: content, type: type, id: id)
end

#add_style_tag(url: nil, path: nil, content: nil) ⇒ Puppeteer::ElementHandle

Parameters:

  • url: (String, nil) (defaults to: nil)
  • path: (String, nil) (defaults to: nil)
  • content: (String, nil) (defaults to: nil)

Returns:



734
735
736
# File 'lib/puppeteer/page.rb', line 734

def add_style_tag(url: nil, path: nil, content: nil)
  main_frame.add_style_tag(url: url, path: path, content: content)
end

#async_wait_for_frame(url: nil, predicate: nil, timeout: nil) ⇒ Object



1304
# File 'lib/puppeteer/page.rb', line 1304

define_async_method :async_wait_for_frame

#async_wait_for_navigation(timeout: nil, wait_until: nil) ⇒ Object



1086
# File 'lib/puppeteer/page.rb', line 1086

define_async_method :async_wait_for_navigation

#async_wait_for_request(url: nil, predicate: nil, timeout: nil) ⇒ Object

Waits until request URL matches or request matches the given predicate.

Waits until request URL matches wait_for_request(url: 'https://example.com/awesome')

Waits until request matches the given predicate wait_for_request(predicate: -> (req){ req.url.start_with?('https://example.com/search') })



1186
# File 'lib/puppeteer/page.rb', line 1186

define_async_method :async_wait_for_request

#async_wait_for_response(url: nil, predicate: nil, timeout: nil) ⇒ Object



1214
# File 'lib/puppeteer/page.rb', line 1214

define_async_method :async_wait_for_response

#authenticate(username: nil, password: nil) ⇒ void

This method returns an undefined value.

Parameters:

  • username: (String, nil) (defaults to: nil)
  • password: (String, nil) (defaults to: nil)


812
813
814
# File 'lib/puppeteer/page.rb', line 812

def authenticate(username: nil, password: nil)
  @frame_manager.network_manager.authenticate(username: username, password: password)
end

#bring_to_frontvoid

This method returns an undefined value.

Brings page to front (activates tab).



1335
1336
1337
# File 'lib/puppeteer/page.rb', line 1335

def bring_to_front
  @client.send_message('Page.bringToFront')
end

#browserPuppeteer::Browser

Returns:



416
417
418
# File 'lib/puppeteer/page.rb', line 416

def browser
  @target.browser
end

#browser_contextPuppeteer::BrowserContext



421
422
423
# File 'lib/puppeteer/page.rb', line 421

def browser_context
  @target.browser_context
end

#bypass_csp=(enabled) ⇒ void

This method returns an undefined value.

Parameters:

  • enabled (Boolean)


1356
1357
1358
# File 'lib/puppeteer/page.rb', line 1356

def bypass_csp=(enabled)
  @client.send_message('Page.setBypassCSP', enabled: enabled)
end

#cache_enabled=(enabled) ⇒ Object

Parameters:

  • enabled (Boolean)

Returns:

  • (Object)


1667
1668
1669
# File 'lib/puppeteer/page.rb', line 1667

def cache_enabled=(enabled)
  @frame_manager.network_manager.cache_enabled = enabled
end

#capture_heap_snapshot(path:) ⇒ void

This method returns an undefined value.

Parameters:

  • path: (String)


838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
# File 'lib/puppeteer/page.rb', line 838

def capture_heap_snapshot(path:)
  @client.send_message('HeapProfiler.enable')
  @client.send_message('HeapProfiler.collectGarbage')

  begin
    File.open(path, 'w') do |file|
      listener_id = @client.add_event_listener('HeapProfiler.addHeapSnapshotChunk') do |event|
        file.write(event['chunk'])
      end

      begin
        @client.send_message('HeapProfiler.takeHeapSnapshot', reportProgress: false)
      ensure
        @client.remove_event_listener(listener_id)
      end
    end
  ensure
    @client.send_message('HeapProfiler.disable')
  end
end

#click(selector, delay: nil, button: nil, count: nil) ⇒ void

This method returns an undefined value.

Parameters:

  • selector (String)
  • delay: (Numeric, nil) (defaults to: nil)
  • button: (String, nil) (defaults to: nil)
  • count: (Integer, nil) (defaults to: nil)


1876
1877
1878
# File 'lib/puppeteer/page.rb', line 1876

def click(selector, delay: nil, button: nil, count: nil)
  main_frame.click(selector, delay: delay, button: button, count: count)
end

#close(run_before_unload: false) ⇒ void

This method returns an undefined value.

Parameters:

  • run_before_unload: (Boolean) (defaults to: false)


1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
# File 'lib/puppeteer/page.rb', line 1844

def close(run_before_unload: false)
  guard = browser_context.wait_for_screenshot_operations
  begin
    unless @client.connection
      raise 'Protocol error: Connection closed. Most likely the page has been closed.'
    end

    if run_before_unload
      @client.send_message('Page.close')
    else
      @client.connection.send_message('Target.closeTarget', targetId: @target.target_id)
      @tab_target.is_closed_promise.wait
    end
  rescue Puppeteer::Connection::ProtocolError => err
    raise unless err.message.match?(/Target closed/i)
  ensure
    guard&.release
  end
end

#closed?Boolean

Returns:

  • (Boolean)


1865
1866
1867
# File 'lib/puppeteer/page.rb', line 1865

def closed?
  @closed
end

#contentString

Returns:

  • (String)


1019
1020
1021
# File 'lib/puppeteer/page.rb', line 1019

def content
  main_frame.content
end

#content=(html) ⇒ void

This method returns an undefined value.

Parameters:

  • html (String)


1033
1034
1035
# File 'lib/puppeteer/page.rb', line 1033

def content=(html)
  main_frame.set_content(html)
end

#cookies(*urls) ⇒ Array[Hash[String, untyped]]

Parameters:

  • urls (Object)

Returns:

  • (Array[Hash[String, untyped]])


646
647
648
# File 'lib/puppeteer/page.rb', line 646

def cookies(*urls)
  @client.send_message('Network.getCookies', urls: (urls.empty? ? [url] : urls))['cookies']
end

#create_pdf_stream(options = {}) ⇒ Enumerable[String]

Parameters:

  • options (Hash[Symbol, untyped]) (defaults to: {})

Returns:

  • (Enumerable[String])


1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
# File 'lib/puppeteer/page.rb', line 1791

def create_pdf_stream(options = {})
  timeout_helper = Puppeteer::TimeoutHelper.new('Page.printToPDF',
                    timeout_ms: options[:timeout],
                    default_timeout_ms: 30000)
  pdf_options = PDFOptions.new(options)
  omit_background = options[:omit_background]
  set_transparent_background_color if omit_background
  result =
    begin
      timeout_helper.with_timeout do
        @client.send_message('Page.printToPDF', pdf_options.page_print_args)
      end
    ensure
      reset_default_background_color if omit_background
    end

  Puppeteer::ProtocolStreamReader.new(
    client: @client,
    handle: result['stream'],
  ).read_as_chunks
end

#default_navigation_timeout=(timeout) ⇒ void

This method returns an undefined value.

Parameters:

  • timeout (Numeric, nil)


548
549
550
# File 'lib/puppeteer/page.rb', line 548

def default_navigation_timeout=(timeout)
  @timeout_settings.default_navigation_timeout = timeout
end

#default_timeoutNumeric

Returns:

  • (Numeric)


559
560
561
# File 'lib/puppeteer/page.rb', line 559

def default_timeout
  @timeout_settings.timeout
end

#default_timeout=(timeout) ⇒ void

This method returns an undefined value.

Parameters:

  • timeout (Numeric, nil)


554
555
556
# File 'lib/puppeteer/page.rb', line 554

def default_timeout=(timeout)
  @timeout_settings.default_timeout = timeout
end

This method returns an undefined value.

Parameters:

  • cookies (Object)


670
671
672
673
674
675
676
677
678
679
# File 'lib/puppeteer/page.rb', line 670

def delete_cookie(*cookies)
  assert_cookie_params(cookies, requires: %i(name))

  page_url = url
  starts_with_http = page_url.start_with?("http")
  cookies.each do |cookie|
    item = (starts_with_http ? { url: page_url } : {}).merge(cookie)
    @client.send_message("Network.deleteCookies", item)
  end
end

#drag_interception_enabled=(enabled) ⇒ void

This method returns an undefined value.

Parameters:

  • enabled (Boolean)


522
523
524
525
# File 'lib/puppeteer/page.rb', line 522

def drag_interception_enabled=(enabled)
  @user_drag_interception_enabled = enabled
  @client.send_message('Input.setInterceptDrags', enabled: enabled)
end

#drag_interception_enabled?Boolean Also known as: drag_interception_enabled

Returns:

  • (Boolean)


271
272
273
# File 'lib/puppeteer/page.rb', line 271

def drag_interception_enabled?
  @user_drag_interception_enabled
end

#emulate(device) ⇒ void

This method returns an undefined value.

Parameters:



1341
1342
1343
1344
# File 'lib/puppeteer/page.rb', line 1341

def emulate(device)
  self.viewport = device.viewport
  self.user_agent = device.user_agent
end

#emulate_cpu_throttling(factor) ⇒ void

This method returns an undefined value.

Parameters:

  • factor (Numeric, nil)


1372
1373
1374
1375
1376
1377
1378
# File 'lib/puppeteer/page.rb', line 1372

def emulate_cpu_throttling(factor)
  if factor.nil? || factor >= 1
    @client.send_message('Emulation.setCPUThrottlingRate', rate: factor || 1)
  else
    raise ArgumentError.new('Throttling rate should be greater or equal to 1')
  end
end

#emulate_idle_state(is_user_active: nil, is_screen_unlocked: nil) ⇒ void

This method returns an undefined value.

Parameters:

  • is_user_active: (Boolean, nil) (defaults to: nil)
  • is_screen_unlocked: (Boolean, nil) (defaults to: nil)


1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
# File 'lib/puppeteer/page.rb', line 1437

def emulate_idle_state(is_user_active: nil, is_screen_unlocked: nil)
  overrides = {
    isUserActive: is_user_active,
    isScreenUnlocked: is_screen_unlocked,
  }.compact

  if overrides.empty?
    @client.send_message('Emulation.clearIdleOverride')
  else
    @client.send_message('Emulation.setIdleOverride', overrides)
  end
end

#emulate_locale(locale = nil) ⇒ void

This method returns an undefined value.

Parameters:

  • locale (String, nil) (defaults to: nil)


1410
1411
1412
1413
# File 'lib/puppeteer/page.rb', line 1410

def emulate_locale(locale = nil)
  @emulation_manager.emulate_locale(locale)
  @frame_manager.network_manager.set_accept_language(locale)
end

#emulate_media_features(features) ⇒ void

This method returns an undefined value.

Parameters:

  • features (Array[Hash[Symbol, untyped]], nil)


1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
# File 'lib/puppeteer/page.rb', line 1382

def emulate_media_features(features)
  if features.nil?
    @client.send_message('Emulation.setEmulatedMedia', features: nil)
  elsif features.is_a?(Array)
    features.each do |media_feature|
      name = media_feature[:name]
      unless /^(?:prefers-(?:color-scheme|reduced-motion)|color-gamut)$/.match?(name)
        raise ArgumentError.new("Unsupported media feature: #{name}")
      end
    end
    @client.send_message('Emulation.setEmulatedMedia', features: features)
  end
end

#emulate_media_type(media_type) ⇒ void

This method returns an undefined value.

Parameters:

  • media_type (String, Symbol, nil)


1362
1363
1364
1365
1366
1367
1368
# File 'lib/puppeteer/page.rb', line 1362

def emulate_media_type(media_type)
  media_type_str = media_type.to_s
  unless ['screen', 'print', ''].include?(media_type_str)
    raise ArgumentError.new("Unsupported media type: #{media_type}")
  end
  @client.send_message('Emulation.setEmulatedMedia', media: media_type_str)
end

#emulate_network_conditions(network_condition) ⇒ void

This method returns an undefined value.

Parameters:



542
543
544
# File 'lib/puppeteer/page.rb', line 542

def emulate_network_conditions(network_condition)
  @frame_manager.network_manager.emulate_network_conditions(network_condition)
end

#emulate_timezone(timezone_id) ⇒ void

This method returns an undefined value.

Parameters:

  • timezone_id (String, nil)


1398
1399
1400
1401
1402
1403
1404
1405
1406
# File 'lib/puppeteer/page.rb', line 1398

def emulate_timezone(timezone_id)
  @client.send_message('Emulation.setTimezoneOverride', timezoneId: timezone_id || '')
rescue => err
  if err.message.include?('Invalid timezone')
    raise ArgumentError.new("Invalid timezone ID: #{timezone_id}")
  else
    raise err
  end
end

#emulate_vision_deficiency(vision_deficiency_type) ⇒ void

This method returns an undefined value.

Parameters:

  • vision_deficiency_type (String, nil)


1426
1427
1428
1429
1430
1431
1432
# File 'lib/puppeteer/page.rb', line 1426

def emulate_vision_deficiency(vision_deficiency_type)
  value = vision_deficiency_type || 'none'
  unless VISION_DEFICIENCY_TYPES.include?(value)
    raise ArgumentError.new("Unsupported vision deficiency: #{vision_deficiency_type}")
  end
  @client.send_message('Emulation.setEmulatedVisionDeficiency', type: value)
end

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

$eval() in JavaScript.

Parameters:

  • selector (String)
  • page_function (String)
  • args (Object)

Returns:

  • (Object)


616
617
618
# File 'lib/puppeteer/page.rb', line 616

def eval_on_selector(selector, page_function, *args)
  main_frame.eval_on_selector(selector, page_function, *args)
end

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

$$eval() in JavaScript.

Parameters:

  • selector (String)
  • page_function (String)
  • args (Object)

Returns:

  • (Object)


628
629
630
# File 'lib/puppeteer/page.rb', line 628

def eval_on_selector_all(selector, page_function, *args)
  main_frame.eval_on_selector_all(selector, page_function, *args)
end

#evaluate(page_function, *args) ⇒ Object

Parameters:

  • page_function (String)
  • args (Object)

Returns:

  • (Object)


1608
1609
1610
# File 'lib/puppeteer/page.rb', line 1608

def evaluate(page_function, *args)
  main_frame.evaluate(page_function, *args)
end

#evaluate_handle(page_function, *args) ⇒ Puppeteer::JSHandle

Parameters:

  • page_function (String)
  • args (Object)

Returns:



597
598
599
600
# File 'lib/puppeteer/page.rb', line 597

def evaluate_handle(page_function, *args)
  context = main_frame.execution_context
  context.evaluate_handle(page_function, *args)
end

#evaluate_on_new_document(page_function, *args) ⇒ Hash[String, untyped]

Parameters:

  • page_function (String)
  • args (Object)

Returns:

  • (Hash[String, untyped])


1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
# File 'lib/puppeteer/page.rb', line 1649

def evaluate_on_new_document(page_function, *args)
  source =
    if ['=>', 'async', 'function'].any? { |keyword| page_function.include?(keyword) }
      JavaScriptFunction.new(page_function, args).source
    else
      JavaScriptExpression.new(page_function).source
    end

  @client.send_message('Page.addScriptToEvaluateOnNewDocument', source: source)
end

#expose_function(name, puppeteer_function) ⇒ void

This method returns an undefined value.

Parameters:

  • name (String)
  • puppeteer_function (Proc)


741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
# File 'lib/puppeteer/page.rb', line 741

def expose_function(name, puppeteer_function)
  if @page_bindings[name]
    raise ArgumentError.new("Failed to add page binding with name `#{name}` already exists!")
  end
  @page_bindings[name] = puppeteer_function

  add_page_binding = <<~JAVASCRIPT
  function (type, bindingName) {
    /* Cast window to any here as we're about to add properties to it
    * via win[bindingName] which TypeScript doesn't like.
    */
    const win = window;
    const binding = win[bindingName];

    win[bindingName] = (...args) => {
      const me = window[bindingName];
      let callbacks = me.callbacks;
      if (!callbacks) {
        callbacks = new Map();
        me.callbacks = callbacks;
      }
      const seq = (me.lastSeq || 0) + 1;
      me.lastSeq = seq;
      const promise = new Promise((resolve, reject) =>
        callbacks.set(seq, { resolve, reject })
      );
      binding(JSON.stringify({ type, name: bindingName, seq, args }));
      return promise;
    };
  }
  JAVASCRIPT

  source = JavaScriptFunction.new(add_page_binding, ['exposedFun', name]).source
  @client.send_message('Runtime.addBinding', name: name)
  script = @client.send_message('Page.addScriptToEvaluateOnNewDocument', source: source)
  @page_binding_ids[name] = script['identifier']

  promises = @frame_manager.frames.map do |frame|
    frame.async_evaluate("() => #{source}")
  end
  Puppeteer::AsyncUtils.await_promise_all(*promises)

  nil
end

#extension_realmsArray[untyped]

Returns:

  • (Array[untyped])


450
451
452
# File 'lib/puppeteer/page.rb', line 450

def extension_realms
  main_frame.extension_realms
end

#extra_http_headers=(headers) ⇒ void

This method returns an undefined value.

Parameters:

  • headers (Hash[String, String])


818
819
820
# File 'lib/puppeteer/page.rb', line 818

def extra_http_headers=(headers)
  @frame_manager.network_manager.extra_http_headers = headers
end

#focus(selector) ⇒ void

This method returns an undefined value.

Parameters:

  • selector (String)


1884
1885
1886
# File 'lib/puppeteer/page.rb', line 1884

def focus(selector)
  main_frame.focus(selector)
end

#framesArray[Puppeteer::Frame]

Returns:



505
506
507
# File 'lib/puppeteer/page.rb', line 505

def frames
  @frame_manager.frames
end

#geolocation=(geolocation) ⇒ void

This method returns an undefined value.

Parameters:



388
389
390
# File 'lib/puppeteer/page.rb', line 388

def geolocation=(geolocation)
  @client.send_message('Emulation.setGeolocationOverride', geolocation.to_h)
end

#go_back(timeout: nil, wait_until: nil) ⇒ Puppeteer::HTTPResponse?

Parameters:

  • timeout: (Numeric, nil) (defaults to: nil)
  • wait_until: (String, Array[String], nil) (defaults to: nil)

Returns:



1309
1310
1311
# File 'lib/puppeteer/page.rb', line 1309

def go_back(timeout: nil, wait_until: nil)
  go(-1, timeout: timeout, wait_until: wait_until)
end

#go_forward(timeout: nil, wait_until: nil) ⇒ Puppeteer::HTTPResponse?

Parameters:

  • timeout: (Numeric, nil) (defaults to: nil)
  • wait_until: (String, Array[String], nil) (defaults to: nil)

Returns:



1316
1317
1318
# File 'lib/puppeteer/page.rb', line 1316

def go_forward(timeout: nil, wait_until: nil)
  go(+1, timeout: timeout, wait_until: wait_until)
end

#goto(url, referer: nil, referrer_policy: nil, timeout: nil, wait_until: nil) ⇒ Puppeteer::HTTPResponse?

Parameters:

  • url (String)
  • referer: (String, nil) (defaults to: nil)
  • referrer_policy: (String, nil) (defaults to: nil)
  • timeout: (Numeric, nil) (defaults to: nil)
  • wait_until: (String, Array[String], nil) (defaults to: nil)

Returns:



1044
1045
1046
1047
1048
1049
1050
1051
1052
# File 'lib/puppeteer/page.rb', line 1044

def goto(url, referer: nil, referrer_policy: nil, timeout: nil, wait_until: nil)
  main_frame.goto(
    url,
    referer: referer,
    referrer_policy: referrer_policy,
    timeout: timeout,
    wait_until: wait_until,
  )
end

#handle_binding_called(event) ⇒ void

This method returns an undefined value.

Parameters:

  • event (Hash[String, untyped])


905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
# File 'lib/puppeteer/page.rb', line 905

def handle_binding_called(event)
  execution_context_id = event['executionContextId']
  payload =
    begin
      JSON.parse(event['payload'])
    rescue
      # The binding was either called by something in the page or it was
      # called before our wrapper was initialized.
      return
    end
  name = payload['name']
  seq = payload['seq']
  args = payload['args']

  if payload['type'] != 'exposedFun' || !@page_bindings[name]
    return
  end

  expression =
    begin
      result = @page_bindings[name].call(*args)

      deliver_result = <<~JAVASCRIPT
      function (name, seq, result) {
        window[name].callbacks.get(seq).resolve(result);
        window[name].callbacks.delete(seq);
      }
      JAVASCRIPT

      JavaScriptFunction.new(deliver_result, [name, seq, result]).source
    rescue => err
      deliver_error = <<~JAVASCRIPT
      function (name, seq, message) {
        const error = new Error(message);
        window[name].callbacks.get(seq).reject(error);
        window[name].callbacks.delete(seq);
      }
      JAVASCRIPT
      JavaScriptFunction.new(deliver_error, [name, seq, err.message]).source
    end

  Async do
    @client.async_send_message('Runtime.evaluate', expression: expression, contextId: execution_context_id).wait
  rescue => error
    debug_puts(error)
  end
end

#handle_file_chooser(event) ⇒ void

This method returns an undefined value.

Parameters:

  • event (Hash[String, untyped])


347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/puppeteer/page.rb', line 347

def handle_file_chooser(event)
  return if @file_chooser_interceptors.empty?

  frame = @frame_manager.frame(event['frameId'])
  element = frame.main_world.adopt_backend_node(event['backendNodeId'])
  interceptors = @file_chooser_interceptors.to_a
  @file_chooser_interceptors.clear
  file_chooser = Puppeteer::FileChooser.new(element, event)
  interceptors.each do |promise|
    promise.resolve(file_chooser)
  end
end

#has_dev_toolsBoolean

Returns:

  • (Boolean)


426
427
428
# File 'lib/puppeteer/page.rb', line 426

def has_dev_tools
  !!browser._has_devtools_target(@target.target_id)
end

#hover(selector) ⇒ void

This method returns an undefined value.

Parameters:

  • selector (String)


1892
1893
1894
# File 'lib/puppeteer/page.rb', line 1892

def hover(selector)
  main_frame.hover(selector)
end

#initArray[untyped]

Returns:

  • (Array[untyped])


261
262
263
264
265
266
267
268
# File 'lib/puppeteer/page.rb', line 261

def init
  Puppeteer::AsyncUtils.await_promise_all(
    @frame_manager.async_init(@target.target_id),
    @client.async_send_message('Performance.enable'),
    @client.async_send_message('Log.enable'),
    @webmcp.async_initialize_domain,
  )
end

#keyboard(&block) ⇒ void

This method returns an undefined value.



498
499
500
501
502
# File 'lib/puppeteer/page.rb', line 498

def keyboard(&block)
  @keyboard.instance_eval(&block) unless block.nil?

  @keyboard
end

#locator(selector_or_function) ⇒ Puppeteer::Locator

Parameters:

  • selector_or_function (String)

Returns:



565
566
567
568
569
570
571
# File 'lib/puppeteer/page.rb', line 565

def locator(selector_or_function)
  if Puppeteer::Locator.function_string?(selector_or_function)
    Puppeteer::FunctionLocator.create(self, selector_or_function)
  else
    Puppeteer::NodeLocator.create(self, selector_or_function)
  end
end

#main_framePuppeteer::Frame

Returns:



484
485
486
# File 'lib/puppeteer/page.rb', line 484

def main_frame
  @frame_manager.main_frame
end

#metricsPuppeteer::Page::Metrics



831
832
833
834
# File 'lib/puppeteer/page.rb', line 831

def metrics
  response = @client.send_message('Performance.getMetrics')
  Metrics.new(response['metrics'])
end

#off(event_name_or_id, listener = nil, &block) ⇒ void

This method returns an undefined value.

Parameters:

  • event_name_or_id (String, Symbol)
  • listener (Proc, nil) (defaults to: nil)


321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/puppeteer/page.rb', line 321

def off(event_name_or_id, listener = nil, &block)
  listener ||= block
  if listener && PageEmittedEvents.values.include?(event_name_or_id.to_s)
    event_name = event_name_or_id.to_s
    if event_name == 'request'
      listeners = @request_intercepted_listener_map[listener]
      wrapped = listeners&.shift
      return unless wrapped
      if listeners.empty?
        if @request_intercepted_listener_map.respond_to?(:delete)
          @request_intercepted_listener_map.delete(listener)
        else
          @request_intercepted_listener_map[listener] = nil
        end
      end
      super(event_name, wrapped)
    else
      super(event_name, listener)
    end
  else
    super(event_name_or_id)
  end
end

#offline_mode=(enabled) ⇒ void

This method returns an undefined value.

Parameters:

  • enabled (Boolean)


536
537
538
# File 'lib/puppeteer/page.rb', line 536

def offline_mode=(enabled)
  @frame_manager.network_manager.offline_mode = enabled
end

#on(event_name, &block) ⇒ void

This method returns an undefined value.

Parameters:

  • event_name (String, Symbol)


279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/puppeteer/page.rb', line 279

def on(event_name, &block)
  unless PageEmittedEvents.values.include?(event_name.to_s)
    raise ArgumentError.new("Unknown event name: #{event_name}. Known events are #{PageEmittedEvents.values.to_a.join(", ")}")
  end

  if event_name.to_s == 'request'
    wrapped = ->(req) { req.enqueue_intercept_action(-> { block.call(req) }) }
    if (listeners = @request_intercepted_listener_map[block])
      listeners << wrapped
    else
      @request_intercepted_listener_map[block] = [wrapped]
    end
    super('request', &wrapped)
  else
    super(event_name.to_s, &block)
  end
end

#once(event_name, &block) ⇒ void

This method returns an undefined value.

Parameters:

  • event_name (String, Symbol)


300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/puppeteer/page.rb', line 300

def once(event_name, &block)
  unless PageEmittedEvents.values.include?(event_name.to_s)
    raise ArgumentError.new("Unknown event name: #{event_name}. Known events are #{PageEmittedEvents.values.to_a.join(", ")}")
  end

  if event_name.to_s == 'request'
    wrapped = ->(req) { req.enqueue_intercept_action(-> { block.call(req) }) }
    if (listeners = @request_intercepted_listener_map[block])
      listeners << wrapped
    else
      @request_intercepted_listener_map[block] = [wrapped]
    end
    super('request', &wrapped)
  else
    super(event_name.to_s, &block)
  end
end

#open_dev_toolsPuppeteer::Page

Returns:



431
432
433
434
435
436
437
438
439
# File 'lib/puppeteer/page.rb', line 431

def open_dev_tools
  page_target_id = @target.target_id
  devtools_target_id = browser._has_devtools_target(page_target_id)
  if devtools_target_id
    return browser._get_devtools_target_page(devtools_target_id)
  end

  browser._create_devtools_page(page_target_id)
end

#pdf(options = {}) ⇒ String

Parameters:

  • options (Hash[Symbol, untyped]) (defaults to: {})

Returns:

  • (String)


1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
# File 'lib/puppeteer/page.rb', line 1815

def pdf(options = {})
  chunks = create_pdf_stream(options)

  StringIO.open do |stringio|
    if options[:path]
      File.open(options[:path], 'wb') do |f|
        chunks.each do |chunk|
          f.write(chunk)
          stringio.write(chunk)
        end
      end
    else
      chunks.each do |chunk|
        stringio.write(chunk)
      end
    end

    stringio.string
  end
rescue => err
  if err.message.include?('PrintToPDF is not implemented')
    raise PrintToPdfIsNotImplementedError.new
  else
    raise
  end
end

#query_objects(prototype_handle) ⇒ Puppeteer::JSHandle

Parameters:

Returns:



606
607
608
609
# File 'lib/puppeteer/page.rb', line 606

def query_objects(prototype_handle)
  context = main_frame.execution_context
  context.query_objects(prototype_handle)
end

#query_selector(selector) ⇒ Puppeteer::ElementHandle? Also known as: S

$() in JavaScript.

Parameters:

  • selector (String)

Returns:



576
577
578
# File 'lib/puppeteer/page.rb', line 576

def query_selector(selector)
  main_frame.query_selector(selector)
end

#query_selector_all(selector, isolate: nil) ⇒ Array[Puppeteer::ElementHandle] Also known as: SS

$$() in JavaScript.

Parameters:

  • selector (String)
  • isolate: (Boolean, nil) (defaults to: nil)

Returns:



587
588
589
# File 'lib/puppeteer/page.rb', line 587

def query_selector_all(selector, isolate: nil)
  main_frame.query_selector_all(selector, isolate: isolate)
end

#reload(timeout: nil, wait_until: nil, ignore_cache: nil) ⇒ Puppeteer::HTTPResponse?

Parameters:

  • timeout: (Numeric, nil) (defaults to: nil)
  • wait_until: (String, Array[String], nil) (defaults to: nil)
  • ignore_cache: (Boolean, nil) (defaults to: nil)

Returns:



1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
# File 'lib/puppeteer/page.rb', line 1058

def reload(timeout: nil, wait_until: nil, ignore_cache: nil)
  params = {}
  params[:ignoreCache] = ignore_cache unless ignore_cache.nil?

  wait_for_navigation(timeout: timeout, wait_until: wait_until, ignore_same_document_navigation: true) do
    if params.empty?
      @client.send_message('Page.reload')
    else
      @client.send_message('Page.reload', **params)
    end
  end
end

#remove_exposed_function(name) ⇒ void

This method returns an undefined value.

Parameters:

  • name (String)


788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
# File 'lib/puppeteer/page.rb', line 788

def remove_exposed_function(name)
  identifier = @page_binding_ids[name]
  unless identifier
    raise ArgumentError.new("Function with name \"#{name}\" does not exist")
  end

  @page_binding_ids.delete(name)
  @page_bindings.delete(name)

  @client.send_message('Runtime.removeBinding', name: name)
  @client.send_message('Page.removeScriptToEvaluateOnNewDocument', identifier: identifier)

  remove_script = '(name) => { delete window[name]; }'
  @frame_manager.frames.each do |frame|
    frame.evaluate(remove_script, name)
  rescue StandardError
    nil
  end
  nil
end

#remove_script_to_evaluate_on_new_document(identifier) ⇒ void

This method returns an undefined value.

Parameters:

  • identifier (String)


1662
1663
1664
# File 'lib/puppeteer/page.rb', line 1662

def remove_script_to_evaluate_on_new_document(identifier)
  @client.send_message('Page.removeScriptToEvaluateOnNewDocument', identifier: identifier)
end

#request_interception=(value) ⇒ void

This method returns an undefined value.

Parameters:

  • value (Boolean)


516
517
518
# File 'lib/puppeteer/page.rb', line 516

def request_interception=(value)
  @frame_manager.network_manager.request_interception = value
end

#screencast(path: nil, overwrite: true, format: nil, crop: nil, scale: nil, speed: nil, fps: nil, loop: nil, delay: nil, quality: nil, colors: nil, ffmpeg_path: nil) ⇒ Puppeteer::ScreenRecorder

Parameters:

  • path: (String, nil) (defaults to: nil)
  • overwrite: (Boolean) (defaults to: true)
  • format: (String, nil) (defaults to: nil)
  • crop: (Hash[Symbol, Numeric], nil) (defaults to: nil)
  • scale: (Numeric, nil) (defaults to: nil)
  • speed: (Numeric, nil) (defaults to: nil)
  • fps: (Numeric, nil) (defaults to: nil)
  • loop: (Numeric, nil) (defaults to: nil)
  • delay: (Numeric, nil) (defaults to: nil)
  • quality: (Numeric, nil) (defaults to: nil)
  • colors: (Numeric, nil) (defaults to: nil)
  • ffmpeg_path: (String, nil) (defaults to: nil)

Returns:



1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
# File 'lib/puppeteer/page.rb', line 1473

def screencast(
  path: nil,
  overwrite: true,
  format: nil,
  crop: nil,
  scale: nil,
  speed: nil,
  fps: nil,
  loop: nil,
  delay: nil,
  quality: nil,
  colors: nil,
  ffmpeg_path: nil
)
  raise ArgumentError.new('`speed` must be greater than 0.') if speed && speed <= 0
  raise ArgumentError.new('`scale` must be greater than 0.') if scale && scale <= 0
  width, height, device_pixel_ratio = native_pixel_dimensions
  normalized_crop = normalize_screencast_crop(crop, width, height, device_pixel_ratio)
  options = {
    path: path,
    overwrite: overwrite,
    format: format,
    crop: normalized_crop,
    scale: scale,
    speed: speed,
    fps: fps,
    loop: loop,
    delay: delay,
    quality: quality,
    colors: colors,
    ffmpeg_path: ffmpeg_path,
  }.compact
  recorder = Puppeteer::ScreenRecorder.new(self, width, height, options)
  begin
    _start_screencast
  rescue
    recorder.stop
    raise
  end
  recorder
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) ⇒ String

Parameters:

  • type: (String, nil) (defaults to: nil)
  • path: (String, nil) (defaults to: nil)
  • full_page: (Boolean, nil) (defaults to: nil)
  • clip: (Hash[Symbol, Numeric], nil) (defaults to: nil)
  • quality: (Integer, nil) (defaults to: nil)
  • omit_background: (Boolean, nil) (defaults to: nil)
  • encoding: (String, nil) (defaults to: nil)
  • capture_beyond_viewport: (Boolean, nil) (defaults to: nil)
  • from_surface: (Boolean, nil) (defaults to: nil)

Returns:

  • (String)


1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
# File 'lib/puppeteer/page.rb', line 1686

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)
  options = {
    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,
  }.compact
  screenshot_options = ScreenshotOptions.new(options)

  guard = browser_context.start_screenshot
  @screenshot_task_queue.post_task do
    screenshot_task(screenshot_options.type, screenshot_options)
  end
ensure
  guard&.release
end

#select(selector, *values) ⇒ Array[String]

Parameters:

  • selector (String)
  • values (Object)

Returns:

  • (Array[String])


1899
1900
1901
# File 'lib/puppeteer/page.rb', line 1899

def select(selector, *values)
  main_frame.select(selector, *values)
end

#set_content(html, timeout: nil, wait_until: nil) ⇒ void

This method returns an undefined value.

Parameters:

  • html (String)
  • timeout: (Numeric, nil) (defaults to: nil)
  • wait_until: (String, Array[String], nil) (defaults to: nil)


1027
1028
1029
# File 'lib/puppeteer/page.rb', line 1027

def set_content(html, timeout: nil, wait_until: nil)
  main_frame.set_content(html, timeout: timeout, wait_until: wait_until)
end

This method returns an undefined value.

Parameters:

  • cookies (Object)


683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
# File 'lib/puppeteer/page.rb', line 683

def set_cookie(*cookies)
  assert_cookie_params(cookies, requires: %i(name value))

  page_url = url
  starts_with_http = page_url.start_with?("http")
  items = cookies.map do |cookie|
    (starts_with_http ? { url: page_url } : {}).merge(cookie).tap do |item|
      item_name = item[:name] || item['name']
      item_url = item[:url] || item['url']
      raise ArgumentError.new("Blank page can not have cookie \"#{item_name}\"") if item_url == "about:blank"
      raise ArgumentError.new("Data URL page can not have cookie \"#{item_name}\"") if item_url&.start_with?("data:")

      same_site =
        if item.key?(:sameSite)
          item[:sameSite]
        elsif item.key?('sameSite')
          item['sameSite']
        elsif item.key?(:same_site)
          item[:same_site]
        else
          item['same_site']
        end

      converted_same_site = convert_same_site_for_cdp(same_site)
      item.delete(:sameSite)
      item.delete('sameSite')
      item.delete(:same_site)
      item.delete('same_site')
      item[:sameSite] = converted_same_site if converted_same_site
    end
  end
  delete_cookie(*items)
  unless items.empty?
    @client.send_message("Network.setCookies", cookies: items)
  end
end

#set_user_agent(user_agent, user_agent_metadata = nil) ⇒ void Also known as: user_agent=

This method returns an undefined value.

Parameters:

  • user_agent (String)
  • user_agent_metadata (Hash[String, untyped], nil) (defaults to: nil)


825
826
827
# File 'lib/puppeteer/page.rb', line 825

def set_user_agent(user_agent,  = nil)
  @frame_manager.network_manager.set_user_agent(user_agent, )
end

#Sx(expression) ⇒ Array[Puppeteer::ElementHandle]

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

Parameters:

  • expression (String)

Returns:



638
639
640
# File 'lib/puppeteer/page.rb', line 638

def Sx(expression)
  main_frame.Sx(expression)
end

#tap(selector: nil, &block) ⇒ void

This method returns an undefined value.

Parameters:

  • selector: (String, nil) (defaults to: nil)


1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
# File 'lib/puppeteer/page.rb', line 1908

def tap(selector: nil, &block)
  # resolves double meaning of tap.
  if selector.nil? && block
    # Original usage of Object#tap.
    #
    # browser.new_page.tap do |page|
    #   ...
    # end
    block.call(self)
    return self
  end

  # Puppeteer's Page#tap.
  main_frame.tap(selector)
  nil
end

#titleString

Returns:

  • (String)


1672
1673
1674
# File 'lib/puppeteer/page.rb', line 1672

def title
  main_frame.title
end

#trigger_extension_action(extension) ⇒ void

This method returns an undefined value.

Parameters:



445
446
447
# File 'lib/puppeteer/page.rb', line 445

def trigger_extension_action(extension)
  extension.trigger_action(self)
end

#type_text(selector, text, delay: nil) ⇒ void

This method returns an undefined value.

Parameters:

  • selector (String)
  • text (String)
  • delay: (Numeric, nil) (defaults to: nil)


1931
1932
1933
# File 'lib/puppeteer/page.rb', line 1931

def type_text(selector, text, delay: nil)
  main_frame.type_text(selector, text, delay: delay)
end

#urlString?

Returns:

  • (String, nil)


1014
1015
1016
# File 'lib/puppeteer/page.rb', line 1014

def url
  main_frame.url
end

#wait_for_file_chooser(timeout: nil) ⇒ Puppeteer::FileChooser

Parameters:

  • timeout: (Numeric, nil) (defaults to: nil)

Returns:



362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/puppeteer/page.rb', line 362

def wait_for_file_chooser(timeout: nil)
  if @file_chooser_interceptors.empty?
    @client.send_message('Page.setInterceptFileChooserDialog', enabled: true)
  end

  option_timeout = timeout || @timeout_settings.timeout
  promise = Async::Promise.new
  @file_chooser_interceptors << promise

  begin
    if option_timeout == 0
      promise.wait
    else
      Puppeteer::AsyncUtils.async_timeout(option_timeout, promise).wait
    end
  rescue Async::TimeoutError
    raise Puppeteer::TimeoutError.new("Waiting for `FileChooser` failed: #{option_timeout}ms exceeded")
  ensure
    @file_chooser_interceptors.delete(promise)
  end
end

#wait_for_frame(url: nil, predicate: nil, timeout: nil) ⇒ Puppeteer::Frame

Parameters:

  • url: (String, nil) (defaults to: nil)
  • predicate: (Proc, nil) (defaults to: nil)
  • timeout: (Numeric, nil) (defaults to: nil)

Returns:



1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
# File 'lib/puppeteer/page.rb', line 1276

def wait_for_frame(url: nil, predicate: nil, timeout: nil)
  if !url && !predicate
    raise ArgumentError.new('url or predicate must be specified')
  end
  if predicate && !predicate.is_a?(Proc)
    raise ArgumentError.new('predicate must be a proc.')
  end
  frame_predicate =
    if url
      -> (frame) { frame.url == url }
    else
      predicate
    end

  frames.each do |frame|
    return frame if frame_predicate.call(frame)
  end

  wait_for_frame_manager_event(
    FrameManagerEmittedEvents::FrameAttached,
    FrameManagerEmittedEvents::FrameNavigated,
    predicate: frame_predicate,
    timeout: timeout,
  )
end

#wait_for_function(page_function, args: [], polling: nil, timeout: nil) ⇒ Puppeteer::JSHandle

Parameters:

  • page_function (String)
  • args: (Array[untyped]) (defaults to: [])
  • polling: (String, Numeric, nil) (defaults to: nil)
  • timeout: (Numeric, nil) (defaults to: nil)

Returns:



1970
1971
1972
# File 'lib/puppeteer/page.rb', line 1970

def wait_for_function(page_function, args: [], polling: nil, timeout: nil)
  main_frame.wait_for_function(page_function, args: args, polling: polling, timeout: timeout)
end

#wait_for_navigation(timeout: nil, wait_until: nil, ignore_same_document_navigation: false) ⇒ Puppeteer::HTTPResponse?

Parameters:

  • timeout: (Numeric, nil) (defaults to: nil)
  • wait_until: (String, Array[String], nil) (defaults to: nil)
  • ignore_same_document_navigation: (Boolean) (defaults to: false)

Returns:



1075
1076
1077
1078
1079
1080
1081
1082
# File 'lib/puppeteer/page.rb', line 1075

def wait_for_navigation(timeout: nil, wait_until: nil, ignore_same_document_navigation: false)
  main_frame.send(
    :wait_for_navigation,
    timeout: timeout,
    wait_until: wait_until,
    ignore_same_document_navigation: ignore_same_document_navigation,
  )
end

#wait_for_network_idle(idle_time: 500, timeout: nil, concurrency: 0) ⇒ void

This method returns an undefined value.

Parameters:

  • idle_time: (Numeric) (defaults to: 500)
  • timeout: (Numeric, nil) (defaults to: nil)
  • concurrency: (Integer) (defaults to: 0)


1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
# File 'lib/puppeteer/page.rb', line 1220

def wait_for_network_idle(idle_time: 500, timeout: nil, concurrency: 0)
  option_timeout = timeout || @timeout_settings.timeout

  promise = Async::Promise.new
  idle_timer = nil

  schedule_idle = lambda do
    return if @inflight_requests.size > concurrency

    idle_timer&.stop
    idle_timer = Async do
      Puppeteer::AsyncUtils.sleep_seconds(idle_time / 1000.0)
      unless promise.resolved? || @inflight_requests.size > concurrency
        promise.resolve(nil)
      end
    end
  end

  # Use raw listener to avoid request interception queue delaying idle tracking.
  request_listener = add_event_listener('request') do
    idle_timer&.stop
    idle_timer = nil
  end
  request_finished_listener = on('requestfinished') do
    schedule_idle.call
  end
  request_failed_listener = on('requestfailed') do
    schedule_idle.call
  end

  schedule_idle.call

  begin
    if option_timeout == 0
      Puppeteer::AsyncUtils.await_promise_race(promise, session_close_promise)
    else
      Puppeteer::AsyncUtils.async_timeout(option_timeout, -> {
        Puppeteer::AsyncUtils.await_promise_race(promise, session_close_promise)
      }).wait
    end
  rescue Async::TimeoutError
    raise Puppeteer::TimeoutError.new("waiting for network idle failed: timeout #{option_timeout}ms exceeded")
  ensure
    off(request_listener)
    off(request_finished_listener)
    off(request_failed_listener)
    idle_timer&.stop
  end
end

#wait_for_request(url: nil, predicate: nil, timeout: nil) ⇒ Puppeteer::HTTPRequest

Parameters:

  • url: (String, nil) (defaults to: nil)
  • predicate: (Proc, nil) (defaults to: nil)
  • timeout: (Numeric, nil) (defaults to: nil)

Returns:



1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
# File 'lib/puppeteer/page.rb', line 1156

def wait_for_request(url: nil, predicate: nil, timeout: nil)
  if !url && !predicate
    raise ArgumentError.new('url or predicate must be specified')
  end
  if predicate && !predicate.is_a?(Proc)
    raise ArgumentError.new('predicate must be a proc.')
  end
  request_predicate =
    if url
      -> (request) { request.url == url }
    else
      predicate
    end

  wait_for_network_manager_event(NetworkManagerEmittedEvents::Request,
    predicate: request_predicate,
    timeout: timeout,
  )
end

#wait_for_response(url: nil, predicate: nil, timeout: nil) ⇒ Puppeteer::HTTPResponse

Parameters:

  • url: (String, nil) (defaults to: nil)
  • predicate: (Proc, nil) (defaults to: nil)
  • timeout: (Numeric, nil) (defaults to: nil)

Returns:



1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
# File 'lib/puppeteer/page.rb', line 1192

def wait_for_response(url: nil, predicate: nil, timeout: nil)
  if !url && !predicate
    raise ArgumentError.new('url or predicate must be specified')
  end
  if predicate && !predicate.is_a?(Proc)
    raise ArgumentError.new('predicate must be a proc.')
  end
  response_predicate =
    if url
      -> (response) { response.url == url }
    else
      predicate
    end

  wait_for_network_manager_event(NetworkManagerEmittedEvents::Response,
    predicate: response_predicate,
    timeout: timeout,
  )
end

#wait_for_selector(selector, visible: nil, hidden: nil, timeout: nil) ⇒ Puppeteer::ElementHandle?

Parameters:

  • selector (String)
  • visible: (Boolean, nil) (defaults to: nil)
  • hidden: (Boolean, nil) (defaults to: nil)
  • timeout: (Numeric, nil) (defaults to: nil)

Returns:



1942
1943
1944
# File 'lib/puppeteer/page.rb', line 1942

def wait_for_selector(selector, visible: nil, hidden: nil, timeout: nil)
  main_frame.wait_for_selector(selector, visible: visible, hidden: hidden, timeout: timeout)
end

#wait_for_timeout(milliseconds) ⇒ void

This method returns an undefined value.

Parameters:

  • milliseconds (Numeric)


1950
1951
1952
# File 'lib/puppeteer/page.rb', line 1950

def wait_for_timeout(milliseconds)
  main_frame.wait_for_timeout(milliseconds)
end

#wait_for_xpath(xpath, visible: nil, hidden: nil, timeout: nil) ⇒ Puppeteer::ElementHandle?

Parameters:

  • xpath (String)
  • visible: (Boolean, nil) (defaults to: nil)
  • hidden: (Boolean, nil) (defaults to: nil)
  • timeout: (Numeric, nil) (defaults to: nil)

Returns:



1959
1960
1961
# File 'lib/puppeteer/page.rb', line 1959

def wait_for_xpath(xpath, visible: nil, hidden: nil, timeout: nil)
  main_frame.wait_for_xpath(xpath, visible: visible, hidden: hidden, timeout: timeout)
end

#workersArray[untyped]

Returns:

  • (Array[untyped])


510
511
512
# File 'lib/puppeteer/page.rb', line 510

def workers
  @workers.values
end