Class: Puppeteer::Browser

Inherits:
Object
  • Object
show all
Includes:
DebugPrint, EventCallbackable, IfPresent
Defined in:
lib/puppeteer/browser.rb,
sig/puppeteer/browser.rbs

Defined Under Namespace

Classes: CreatePageError, MissingBrowserContextError, MissingTargetError, Version

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, #off, #on_event, #remove_event_listener

Methods included from DebugPrint

#debug_print, #debug_puts

Constructor Details

#initialize(product:, connection:, context_ids:, ignore_https_errors:, default_viewport:, network_enabled: true, issues_enabled: true, block_list: nil, allow_list: nil, process:, close_callback:, target_filter_callback:, is_page_target_callback:) ⇒ Browser

Returns a new instance of Browser.

Parameters:

  • product: (String, nil)
  • connection: (Puppeteer::Connection)
  • context_ids: (Array[String])
  • ignore_https_errors: (Boolean)
  • default_viewport: (Puppeteer::Viewport, nil)
  • process: (Puppeteer::BrowserRunner::BrowserProcess, nil)
  • close_callback: (Proc)
  • target_filter_callback: (Proc, nil)
  • is_page_target_callback: (Proc, nil)
  • network_enabled: (Boolean) (defaults to: true)
  • issues_enabled: (Boolean) (defaults to: true)
  • block_list: (Array[String], nil) (defaults to: nil)
  • allow_list: (Array[String], nil) (defaults to: nil)


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
# File 'lib/puppeteer/browser.rb', line 72

def initialize(product:,
               connection:,
               context_ids:,
               ignore_https_errors:,
               default_viewport:,
               network_enabled: true,
               issues_enabled: true,
               block_list: nil,
               allow_list: nil,
               process:,
               close_callback:,
               target_filter_callback:,
               is_page_target_callback:)
  @product = product ? product.to_s : 'chrome'
  if @product != 'chrome'
    raise ArgumentError.new("Unsupported product: #{@product}. Only 'chrome' is supported.")
  end
  @ignore_https_errors = ignore_https_errors
  @default_viewport = default_viewport
  @network_enabled = network_enabled
  @issues_enabled = issues_enabled
  @block_list = block_list
  @allow_list = allow_list
  @process = process
  @connection = connection
  @close_callback = close_callback
  @target_filter_callback = target_filter_callback || method(:default_target_filter_callback)
  @is_page_target_callback = is_page_target_callback || method(:default_is_page_target_callback)
  @default_context = Puppeteer::BrowserContext.new(@connection, self, nil)
  @contexts = {}

  context_ids.each do |context_id|
    @contexts[context_id] = Puppeteer::BrowserContext.new(@connection, self, context_id)
  end

  @target_manager = Puppeteer::ChromeTargetManager.new(
    connection: connection,
    target_factory: method(:create_target),
    target_filter_callback: @target_filter_callback,
    block_list: block_list,
    allow_list: allow_list,
  )
  @connection.reject_emulate_network_conditions_calls =
    [block_list, allow_list].any? { |list| list && !list.empty? }
  @extensions = {}
  @version_promise = nil
end

Instance Attribute Details

#is_page_target_callbackObject (readonly)

Returns the value of attribute is_page_target_callback.

Returns:

  • (Object)


138
139
140
# File 'lib/puppeteer/browser.rb', line 138

def is_page_target_callback
  @is_page_target_callback
end

Class Method Details

.create(product:, connection:, context_ids:, ignore_https_errors:, default_viewport:, network_enabled: true, issues_enabled: true, block_list: nil, allow_list: nil, process:, close_callback:, target_filter_callback:, is_page_target_callback:) ⇒ Puppeteer::Browser

Parameters:

  • product: (String, nil)
  • connection: (Puppeteer::Connection)
  • context_ids: (Array[String])
  • ignore_https_errors: (Boolean)
  • default_viewport: (Puppeteer::Viewport, nil)
  • process: (Puppeteer::BrowserRunner::BrowserProcess, nil)
  • close_callback: (Proc)
  • target_filter_callback: (Proc, nil)
  • is_page_target_callback: (Proc, nil)
  • network_enabled: (Boolean) (defaults to: true)
  • issues_enabled: (Boolean) (defaults to: true)
  • block_list: (Array[String], nil) (defaults to: nil)
  • allow_list: (Array[String], nil) (defaults to: nil)

Returns:



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/puppeteer/browser.rb', line 25

def self.create(product:,
                connection:,
                context_ids:,
                ignore_https_errors:,
                default_viewport:,
                network_enabled: true,
                issues_enabled: true,
                block_list: nil,
                allow_list: nil,
                process:,
                close_callback:,
                target_filter_callback:,
                is_page_target_callback:)
  browser = Puppeteer::Browser.new(
    product: product,
    connection: connection,
    context_ids: context_ids,
    ignore_https_errors: ignore_https_errors,
    default_viewport: default_viewport,
    network_enabled: network_enabled,
    issues_enabled: issues_enabled,
    block_list: block_list,
    allow_list: allow_list,
    process: process,
    close_callback: close_callback,
    target_filter_callback: target_filter_callback,
    is_page_target_callback: is_page_target_callback,
  )
  browser.send(:validate_allow_list_version)
  browser.send(:attach)
  browser
end

Instance Method Details

#_create_devtools_page(page_target_id) ⇒ Puppeteer::Page

Parameters:

  • page_target_id (String)

Returns:



459
460
461
462
# File 'lib/puppeteer/browser.rb', line 459

def _create_devtools_page(page_target_id)
  result = @connection.send_message('Target.openDevTools', targetId: page_target_id)
  _get_devtools_target_page(result['targetId'])
end

#_get_devtools_target_page(devtools_target_id) ⇒ Puppeteer::Page

Parameters:

  • devtools_target_id (String)

Returns:



466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/puppeteer/browser.rb', line 466

def _get_devtools_target_page(devtools_target_id)
  target = wait_for_available_target(devtools_target_id)
  unless target
    raise MissingTargetError.new(
      "Missing target for DevTools page (id = #{devtools_target_id})",
    )
  end
  unless target.initialized_promise.wait
    raise CreatePageError.new(
      "Failed to create target for DevTools page (id = #{devtools_target_id})",
    )
  end
  page = target.as_page
  unless page
    raise CreatePageError.new(
      "Failed to create a DevTools Page for target (id = #{devtools_target_id})",
    )
  end
  page
end

#_has_devtools_target(page_target_id) ⇒ String?

Parameters:

  • page_target_id (String)

Returns:

  • (String, nil)


452
453
454
455
# File 'lib/puppeteer/browser.rb', line 452

def _has_devtools_target(page_target_id)
  result = @connection.send_message('Target.getDevToolsTarget', targetId: page_target_id)
  result['targetId']
end

#allow_listArray[String]?

Returns:

  • (Array[String], nil)


543
544
545
# File 'lib/puppeteer/browser.rb', line 543

def allow_list
  @allow_list
end

#async_wait_for_target(predicate:, timeout: nil) ⇒ Object



421
# File 'lib/puppeteer/browser.rb', line 421

define_async_method :async_wait_for_target

#block_listArray[String]?

Returns:

  • (Array[String], nil)


538
539
540
# File 'lib/puppeteer/browser.rb', line 538

def block_list
  @block_list
end

#browser_contextsArray[Puppeteer::BrowserContext]

Returns:



229
230
231
# File 'lib/puppeteer/browser.rb', line 229

def browser_contexts
  [@default_context].concat(@contexts.values)
end

#closevoid

This method returns an undefined value.



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

def close
  @close_callback.call
  disconnect
end

#connected?Boolean

Returns:

  • (Boolean)


566
567
568
# File 'lib/puppeteer/browser.rb', line 566

def connected?
  !@connection.closed?
end

#create_browser_context(proxy_server: nil, proxy_bypass_list: nil, download_behavior: nil) ⇒ Puppeteer::BrowserContext

Parameters:

  • proxy_server: (String, nil) (defaults to: nil)
  • proxy_bypass_list: (Array[String], nil) (defaults to: nil)
  • download_behavior: (Hash[Symbol | String, untyped], nil) (defaults to: nil)

Returns:



216
217
218
219
220
221
222
223
224
225
226
# File 'lib/puppeteer/browser.rb', line 216

def create_browser_context(proxy_server: nil, proxy_bypass_list: nil, download_behavior: nil)
  params = {
    proxyServer: proxy_server,
    proxyBypassList: proxy_bypass_list&.join(','),
  }.compact
  result = @connection.send_message('Target.createBrowserContext', params)
  browser_context_id = result['browserContextId']
  context = Puppeteer::BrowserContext.new(@connection, self, browser_context_id)
  context.set_download_behavior(download_behavior) if download_behavior
  @contexts[browser_context_id] = context
end

#create_incognito_browser_contextPuppeteer::BrowserContext



206
207
208
209
210
# File 'lib/puppeteer/browser.rb', line 206

def create_incognito_browser_context
  result = @connection.send_message('Target.createBrowserContext')
  browser_context_id = result['browserContextId']
  @contexts[browser_context_id] = Puppeteer::BrowserContext.new(@connection, self, browser_context_id)
end

#create_page_in_context(context_id) ⇒ Puppeteer::Page

Parameters:

  • context_id (String, nil)

Returns:



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/puppeteer/browser.rb', line 329

def create_page_in_context(context_id)
  create_target_params = {
    url: 'about:blank',
    browserContextId: context_id,
  }.compact
  result = @connection.send_message('Target.createTarget', **create_target_params)
  target_id = result['targetId']
  target = wait_for_available_target(target_id)
  unless target
    raise MissingTargetError.new("Missing target for page (id = #{target_id})")
  end
  unless target.initialized_promise.wait
    raise CreatePageError.new("Failed to create target for page (id = #{target_id})")
  end
  page = target.page
  unless page
    raise CreatePageError.new("Failed to create a page for context (id = #{context_id})")
  end
  page
end

#create_target(target_info, session) ⇒ Puppeteer::Target

Parameters:

Returns:



258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/puppeteer/browser.rb', line 258

def create_target(target_info, session)
  browser_context_id = target_info.browser_context_id
  context =
    if browser_context_id && @contexts.has_key?(browser_context_id)
      @contexts[browser_context_id]
    else
      @default_context
    end

  unless context
    raise MissingBrowserContextError.new('Missing browser context')
  end

  Puppeteer::Target.new(
    target_info: target_info,
    session: session,
    browser_context: context,
    target_manager: @target_manager,
    session_factory: -> (auto_attach_emulated) { @connection.create_session(target_info, auto_attach_emulated: auto_attach_emulated) },
    ignore_https_errors: @ignore_https_errors,
    default_viewport: @default_viewport,
    network_enabled: @network_enabled,
    is_page_target_callback: @is_page_target_callback,
  )
end

#default_browser_contextPuppeteer::BrowserContext



234
235
236
# File 'lib/puppeteer/browser.rb', line 234

def default_browser_context
  @default_context
end

#disconnectvoid

This method returns an undefined value.



560
561
562
563
# File 'lib/puppeteer/browser.rb', line 560

def disconnect
  @target_manager.dispose
  @connection.dispose
end

#dispose_context(context_id) ⇒ void

This method returns an undefined value.

Parameters:

  • context_id (String, nil)


247
248
249
250
251
# File 'lib/puppeteer/browser.rb', line 247

def dispose_context(context_id)
  return unless context_id
  @connection.send_message('Target.disposeBrowserContext', browserContextId: context_id)
  @contexts.delete(context_id)
end

#extensionsHash[String, Puppeteer::Extension]

Returns:



509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/puppeteer/browser.rb', line 509

def extensions
  response = @connection.send_message('Extensions.getExtensions')
  extension_map = {}
  response.fetch('extensions', []).each do |payload|
    extension_id = payload['id']
    existing_extension = @extensions[extension_id]
    extension_map[extension_id] =
      if existing_extension
        existing_extension
      else
        Puppeteer::Extension.new(
          id: extension_id,
          version: payload['version'],
          name: payload['name'],
          path: payload['path'],
          enabled: payload['enabled'],
          browser: self,
        )
      end
  end
  @extensions = extension_map
end

#install_extension(path, enabled_in_incognito: false) ⇒ String

Parameters:

  • path (String)
  • enabled_in_incognito: (Boolean) (defaults to: false)

Returns:

  • (String)


490
491
492
493
494
495
496
497
498
# File 'lib/puppeteer/browser.rb', line 490

def install_extension(path, enabled_in_incognito: false)
  result = @connection.send_message('Extensions.loadUnpacked', {
    path: path,
    enableInIncognito: enabled_in_incognito,
  })
  extension_id = result['id']
  @extensions.delete(extension_id)
  extension_id
end

#issues_enabled?Boolean

Returns:

  • (Boolean)


533
534
535
# File 'lib/puppeteer/browser.rb', line 533

def issues_enabled?
  @issues_enabled
end

#new_pagePuppeteer::Page

Returns:



320
321
322
# File 'lib/puppeteer/browser.rb', line 320

def new_page
  @default_context.new_page
end

#on(event_name, &block) ⇒ void

This method returns an undefined value.

Parameters:

  • event_name (String, Symbol)


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

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

  super(event_name.to_s, &block)
end

#once(event_name, &block) ⇒ void

This method returns an undefined value.

Parameters:

  • event_name (String, Symbol)


154
155
156
157
158
159
160
# File 'lib/puppeteer/browser.rb', line 154

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

  super(event_name.to_s, &block)
end

#pagesArray[Puppeteer::Page]

Returns:



424
425
426
# File 'lib/puppeteer/browser.rb', line 424

def pages
  browser_contexts.flat_map(&:pages)
end

#processPuppeteer::BrowserRunner::BrowserProcess?



193
194
195
# File 'lib/puppeteer/browser.rb', line 193

def process
  @process
end

#set_permission(origin, *permissions) ⇒ void

This method returns an undefined value.

Parameters:

  • origin (String)
  • permissions (Object)


241
242
243
# File 'lib/puppeteer/browser.rb', line 241

def set_permission(origin, *permissions)
  @default_context.set_permission(origin, *permissions)
end

#targetPuppeteer::Target

The target associated with the browser.

Returns:



380
381
382
# File 'lib/puppeteer/browser.rb', line 380

def target
  targets.find { |target| target.type == 'browser' } or raise 'Browser target is not found'
end

#targetsArray[Puppeteer::Target]

All active targets inside the Browser. In case of multiple browser contexts, returns an array with all the targets in all browser contexts.

Returns:



373
374
375
# File 'lib/puppeteer/browser.rb', line 373

def targets
  @target_manager.available_targets.values.select { |target| target.exposed? && target.initialized? }
end

#uninstall_extension(extension_id) ⇒ void

This method returns an undefined value.

Parameters:

  • extension_id (String)


502
503
504
505
506
# File 'lib/puppeteer/browser.rb', line 502

def uninstall_extension(extension_id)
  @connection.send_message('Extensions.uninstall', id: extension_id)
  @target_manager.remove_extension_service_workers(extension_id)
  @extensions.delete(extension_id)
end

#url_allowed?(url) ⇒ Boolean

Parameters:

  • url (String)

Returns:

  • (Boolean)


549
550
551
# File 'lib/puppeteer/browser.rb', line 549

def url_allowed?(url)
  @target_manager.url_allowed?(url)
end

#user_agentString

Returns:

  • (String)


434
435
436
# File 'lib/puppeteer/browser.rb', line 434

def user_agent
  version_info.user_agent
end

#versionString

Returns:

  • (String)


429
430
431
# File 'lib/puppeteer/browser.rb', line 429

def version
  version_info.product
end

#wait_for_target(predicate:, timeout: nil) ⇒ Puppeteer::Target

Parameters:

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

Returns:



392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/puppeteer/browser.rb', line 392

def wait_for_target(predicate:, timeout: nil)
  timeout_helper = Puppeteer::TimeoutHelper.new('target', timeout_ms: timeout, default_timeout_ms: 30000)
  existing_target = targets.find { |target| predicate.call(target) }
  return existing_target if existing_target

  event_listening_ids = []
  target_promise = Async::Promise.new
  event_listening_ids << add_event_listener(BrowserEmittedEvents::TargetCreated) do |target|
    if predicate.call(target)
      target_promise.resolve(target)
    end
  end
  event_listening_ids << add_event_listener(BrowserEmittedEvents::TargetChanged) do |target|
    if predicate.call(target)
      target_promise.resolve(target)
    end
  end

  begin
    timeout_helper.with_timeout do
      target_promise.wait
    end
  ensure
    remove_event_listener(*event_listening_ids)
  end
end

#ws_endpointString

Returns:

  • (String)


315
316
317
# File 'lib/puppeteer/browser.rb', line 315

def ws_endpoint
  @connection.url
end