Class: Puppeteer::Browser

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

Defined Under Namespace

Classes: TargetAlreadyExistError, TargetNotExistError, Version

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(connection:, context_ids:, ignore_https_errors:, default_viewport:, process:, close_callback:) ⇒ Browser

Returns a new instance of Browser.

Parameters:



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/puppeteer/browser.rb', line 35

def initialize(connection:, context_ids:, ignore_https_errors:, default_viewport:, process:, close_callback:)
  @ignore_https_errors = ignore_https_errors
  @default_viewport = default_viewport
  @process = process
  @connection = connection
  @close_callback = close_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
  @targets = {}
  @connection.on_event(ConnectionEmittedEvents::Disconnected) do
    emit_event(BrowserEmittedEvents::Disconnected)
  end
  @connection.on_event('Target.targetCreated', &method(:handle_target_created))
  @connection.on_event('Target.targetDestroyed', &method(:handle_target_destroyed))
  @connection.on_event('Target.targetInfoChanged', &method(:handle_target_info_changed))
end

Class Method Details

.create(connection:, context_ids:, ignore_https_errors:, default_viewport:, process:, close_callback:) ⇒ Object

Parameters:



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/puppeteer/browser.rb', line 16

def self.create(connection:, context_ids:, ignore_https_errors:, default_viewport:, process:, close_callback:)
  browser = Puppeteer::Browser.new(
    connection: connection,
    context_ids: context_ids,
    ignore_https_errors: ignore_https_errors,
    default_viewport: default_viewport,
    process: process,
    close_callback: close_callback,
  )
  connection.send_message('Target.setDiscoverTargets', discover: true)
  browser
end

Instance Method Details

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

Parameters:



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

define_async_method :async_wait_for_target

#browser_contextsObject



86
87
88
# File 'lib/puppeteer/browser.rb', line 86

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

#closeObject



262
263
264
265
# File 'lib/puppeteer/browser.rb', line 262

def close
  @close_callback.call
  disconnect
end

#connected?Boolean

Returns:

  • (Boolean)


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

def connected?
  !@connection.closed?
end

#create_incognito_browser_contextPuppeteer::BrowserContext



80
81
82
83
84
# File 'lib/puppeteer/browser.rb', line 80

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) ⇒ !Promise<!Puppeteer.Page>

Parameters:

  • contextId (?string)

Returns:



179
180
181
182
183
184
185
186
187
188
189
# File 'lib/puppeteer/browser.rb', line 179

def create_page_in_context(context_id)
  create_target_params = { url: 'about:blank' }
  if context_id
    create_target_params[:browserContextId] = context_id
  end
  result = @connection.send_message('Target.createTarget', **create_target_params)
  target_id = result['targetId']
  target = @targets[target_id]
  await target.initialized_promise
  await target.page
end

#default_browser_contextPuppeteer::BrowserContext



91
92
93
# File 'lib/puppeteer/browser.rb', line 91

def default_browser_context
  @default_context
end

#disconnectObject



267
268
269
# File 'lib/puppeteer/browser.rb', line 267

def disconnect
  @connection.dispose
end

#dispose_context(context_id) ⇒ Object

Parameters:

  • context_id (String)


96
97
98
99
# File 'lib/puppeteer/browser.rb', line 96

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

#handle_target_created(event) ⇒ Object

Parameters:

  • event (!Protocol.Target.targetCreatedPayload)


108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# File 'lib/puppeteer/browser.rb', line 108

def handle_target_created(event)
  target_info = Puppeteer::Target::TargetInfo.new(event['targetInfo'])
  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

  if @targets[target_info.target_id]
    raise TargetAlreadyExistError.new
  end
  target = Puppeteer::Target.new(
    target_info: target_info,
    browser_context: context,
    session_factory: -> { @connection.create_session(target_info) },
    ignore_https_errors: @ignore_https_errors,
    default_viewport: @default_viewport,
  )
  #   assert(!this._targets.has(event.targetInfo.targetId), 'Target should not exist before targetCreated');
  @targets[target_info.target_id] = target
  if await target.initialized_promise
    emit_event(BrowserEmittedEvents::TargetCreated, target)
    context.emit_event(BrowserContextEmittedEvents::TargetCreated, target)
  end
end

#handle_target_destroyed(event) ⇒ Object

Parameters:

  • event ({targetId: string})


137
138
139
140
141
142
143
144
145
146
147
# File 'lib/puppeteer/browser.rb', line 137

def handle_target_destroyed(event)
  target_id = event['targetId']
  target = @targets[target_id]
  target.ignore_initialize_callback_promise
  @targets.delete(target_id)
  target.closed_callback
  if await target.initialized_promise
    emit_event(BrowserEmittedEvents::TargetDestroyed, target)
    target.browser_context.emit_event(BrowserContextEmittedEvents::TargetDestroyed, target)
  end
end

#handle_target_info_changed(event) ⇒ Object

Parameters:

  • event (!Protocol.Target.targetInfoChangedPayload)


156
157
158
159
160
161
162
163
164
165
166
# File 'lib/puppeteer/browser.rb', line 156

def handle_target_info_changed(event)
  target_info = Puppeteer::Target::TargetInfo.new(event['targetInfo'])
  target = @targets[target_info.target_id] or raise TargetNotExistError.new
  previous_url = target.url
  was_initialized = target.initialized?
  target.handle_target_info_changed(target_info)
  if was_initialized && previous_url != target.url
    emit_event(BrowserEmittedEvents::TargetChanged, target)
    target.browser_context.emit_event(BrowserContextEmittedEvents::TargetChanged, target)
  end
end

#new_pageObject



173
174
175
# File 'lib/puppeteer/browser.rb', line 173

def new_page
  @default_context.new_page
end

#on(event_name, &block) ⇒ Object

Parameters:

  • event_name (Symbol)

    either of :disconnected, :targetcreated, :targetchanged, :targetdestroyed



57
58
59
60
61
62
63
# File 'lib/puppeteer/browser.rb', line 57

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) ⇒ Object

Parameters:

  • event_name (Symbol)


66
67
68
69
70
71
72
# File 'lib/puppeteer/browser.rb', line 66

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

#pages!Promise<!Array<!Puppeteer.Page>>

Returns:



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

def pages
  browser_contexts.flat_map(&:pages)
end

#processPuppeteer::BrowserRunner::BrowserProcess



75
76
77
# File 'lib/puppeteer/browser.rb', line 75

def process
  @process
end

#target!Target

Returns:



198
199
200
# File 'lib/puppeteer/browser.rb', line 198

def target
  targets.find { |target| target.type == 'browser' }
end

#targets!Array<!Target>

Returns:



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

def targets
  @targets.values.select { |target| target.initialized? }
end

#user_agentString

Returns:

  • (String)


258
259
260
# File 'lib/puppeteer/browser.rb', line 258

def user_agent
  get_version.user_agent
end

#versionString

Returns:

  • (String)


253
254
255
# File 'lib/puppeteer/browser.rb', line 253

def version
  get_version.product
end

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

Parameters:

Returns:



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

def wait_for_target(predicate:, timeout: nil)
  timeout_in_sec = (timeout || 30000).to_i / 1000.0
  existing_target = targets.find { |target| predicate.call(target) }
  return existing_target if existing_target

  event_listening_ids = []
  target_promise = resolvable_future
  event_listening_ids << add_event_listener(BrowserEmittedEvents::TargetCreated) do |target|
    if predicate.call(target)
      target_promise.fulfill(target)
    end
  end
  event_listening_ids << add_event_listener(BrowserEmittedEvents::TargetChanged) do |target|
    if predicate.call(target)
      target_promise.fulfill(target)
    end
  end

  begin
    if timeout_in_sec > 0
      Timeout.timeout(timeout_in_sec) do
        target_promise.value!
      end
    else
      target_promise.value!
    end
  rescue Timeout::Error
    raise Puppeteer::TimeoutError.new("waiting for target failed: timeout #{timeout}ms exceeded")
  ensure
    remove_event_listener(*event_listening_ids)
  end
end

#ws_endpointString

Returns:

  • (String)


169
170
171
# File 'lib/puppeteer/browser.rb', line 169

def ws_endpoint
  @connection.url
end