Class: Puppeteer::FrameManager

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

Defined Under Namespace

Classes: NavigationError

Constant Summary collapse

UTILITY_WORLD_NAME =
'__puppeteer_utility_world__'

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from EventCallbackable

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

Methods included from IfPresent

#if_present

Methods included from DebugPrint

#debug_print, #debug_puts

Constructor Details

#initialize(client, page, ignore_https_errors, timeout_settings) ⇒ FrameManager

Returns a new instance of FrameManager.

Parameters:



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/puppeteer/frame_manager.rb', line 15

def initialize(client, page, ignore_https_errors, timeout_settings)
  @client = client
  @page = page
  @network_manager = Puppeteer::NetworkManager.new(client, ignore_https_errors, self)
  @timeout_settings = timeout_settings

  # @type {!Map<string, !Frame>}
  @frames = {}

  # @type {!Map<number, !ExecutionContext>}
  @context_id_to_context = {}

  # @type {!Set<string>}
  @isolated_worlds = Set.new

  setup_listeners(@client)
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



69
70
71
# File 'lib/puppeteer/frame_manager.rb', line 69

def client
  @client
end

#network_managerObject (readonly)

Returns the value of attribute network_manager.



95
96
97
# File 'lib/puppeteer/frame_manager.rb', line 95

def network_manager
  @network_manager
end

#timeout_settingsObject (readonly)

Returns the value of attribute timeout_settings.



69
70
71
# File 'lib/puppeteer/frame_manager.rb', line 69

def timeout_settings
  @timeout_settings
end

Instance Method Details

#execution_context_by_id(context_id, session) ⇒ Object



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

def execution_context_by_id(context_id, session)
  key = "#{session.id}:#{context_id}"
  @context_id_to_context[key] or raise "INTERNAL ERROR: missing context with id = #{context_id}"
end

#frame(frame_id) ⇒ ?Frame

Parameters:

  • frameId (!string)

Returns:



243
244
245
# File 'lib/puppeteer/frame_manager.rb', line 243

def frame(frame_id)
  @frames[frame_id]
end

#frames!Array<!Frame>

Returns:



237
238
239
# File 'lib/puppeteer/frame_manager.rb', line 237

def frames
  @frames.values
end

#handle_attached_to_target(event) ⇒ Object

Parameters:

  • event (Hash)


175
176
177
178
179
180
181
182
183
184
# File 'lib/puppeteer/frame_manager.rb', line 175

def handle_attached_to_target(event)
  return if event['targetInfo']['type'] != 'iframe'

  frame = @frames[event['targetInfo']['targetId']]
  session = Puppeteer::Connection.from_session(@client).session(event['sessionId'])

  frame.send(:update_client, session)
  setup_listeners(session)
  async_init(session)
end

#handle_detached_from_target(event) ⇒ Object

Parameters:

  • event (Hash)


187
188
189
190
191
192
193
194
# File 'lib/puppeteer/frame_manager.rb', line 187

def handle_detached_from_target(event)
  frame = @frames[event['targetId']]
  if frame && frame.oop_frame?
    # When an OOP iframe is removed from the page, it
    # will only get a Target.detachedFromTarget event.
    remove_frame_recursively(frame)
  end
end

#handle_execution_context_created(context_payload, session) ⇒ Object

Parameters:

  • context_payload (Hash)


361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/puppeteer/frame_manager.rb', line 361

def handle_execution_context_created(context_payload, session)
  frame = if_present(context_payload.dig('auxData', 'frameId')) { |frame_id| @frames[frame_id] }

  world = nil
  if frame
    # commented out the original implementation for allowing us to use Frame#evaluate on OOP iframe.
    #
    # # Only care about execution contexts created for the current session.
    # return if @client != session

    if context_payload.dig('auxData', 'isDefault')
      world = frame.main_world
    elsif context_payload['name'] == UTILITY_WORLD_NAME && !frame.secondary_world.has_context?
      # In case of multiple sessions to the same target, there's a race between
      # connections so we might end up creating multiple isolated worlds.
      # We can use either.
      world = frame.secondary_world
    end
  end

  if context_payload.dig('auxData', 'type') == 'isolated'
    @isolated_worlds << context_payload['name']
  end

  context = Puppeteer::ExecutionContext.new(frame&._client || @client, context_payload, world)
  if world
    world.context = context
  end
  key = "#{session.id}:#{context_payload['id']}"
  @context_id_to_context[key] = context
end

#handle_execution_context_destroyed(execution_context_id, session) ⇒ Object

Parameters:

  • execution_context_id (Integer)
  • session (Puppeteer::CDPSEssion)


395
396
397
398
399
400
401
402
403
# File 'lib/puppeteer/frame_manager.rb', line 395

def handle_execution_context_destroyed(execution_context_id, session)
  key = "#{session.id}:#{execution_context_id}"
  context = @context_id_to_context[key]
  return unless context
  @context_id_to_context.delete(key)
  if context.world
    context.world.delete_context(execution_context_id)
  end
end

#handle_execution_contexts_cleared(session) ⇒ Object

Parameters:



406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/puppeteer/frame_manager.rb', line 406

def handle_execution_contexts_cleared(session)
  @context_id_to_context.select! do |execution_context_id, context|
    # Make sure to only clear execution contexts that belong
    # to the current session.
    if context.client != session
      true # keep
    else
      if context.world
        context.world.delete_context(execution_context_id)
      end
      false # remove
    end
  end
end

#handle_frame_attached(session, frame_id, parent_frame_id) ⇒ Object

Parameters:



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/puppeteer/frame_manager.rb', line 250

def handle_frame_attached(session, frame_id, parent_frame_id)
  if @frames.has_key?(frame_id)
    frame = @frames[frame_id]
    if session && frame.oop_frame?
      # If an OOP iframes becomes a normal iframe again
      # it is first attached to the parent page before
      # the target is removed.
      frame.send(:update_client, session)
    end
    return
  end
  if !parent_frame_id
    raise ArgymentError.new('parent_frame_id must not be nil')
  end
  parent_frame = @frames[parent_frame_id]
  frame = Puppeteer::Frame.new(self, parent_frame, frame_id, session)
  @frames[frame_id] = frame

  emit_event(FrameManagerEmittedEvents::FrameAttached, frame)
end

#handle_frame_detached(frame_id, reason) ⇒ Object

Parameters:

  • frame_id (String)
  • reason (String)


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

def handle_frame_detached(frame_id, reason)
  frame = @frames[frame_id]
  if reason == 'remove'
    # Only remove the frame if the reason for the detached event is
    # an actual removement of the frame.
    # For frames that become OOP iframes, the reason would be 'swap'.
    if frame
      remove_frame_recursively(frame)
    end
  end
end

#handle_frame_navigated(frame_payload) ⇒ Object

Parameters:

  • frame_payload (Hash)


272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/puppeteer/frame_manager.rb', line 272

def handle_frame_navigated(frame_payload)
  is_main_frame = !frame_payload['parentId']
  frame =
    if is_main_frame
      @main_frame
    else
      @frames[frame_payload['id']]
    end

  if !is_main_frame && !frame
    raise ArgumentError.new('We either navigate top level or have old version of the navigated frame')
  end

  # Detach all child frames first.
  if frame
    frame.child_frames.each do |child|
      remove_frame_recursively(child)
    end
  end

  # Update or create main frame.
  if is_main_frame
    if frame
      # Update frame id to retain frame identity on cross-process navigation.
      @frames.delete(frame.id)
      frame.id = frame_payload['id']
    else
      # Initial main frame navigation.
      frame = Puppeteer::Frame.new(self, nil, frame_payload['id'], @client)
    end
    @frames[frame_payload['id']] = frame
    @main_frame = frame
  end

  # Update frame payload.
  frame.navigated(frame_payload)

  emit_event(FrameManagerEmittedEvents::FrameNavigated, frame)
end

#handle_frame_navigated_within_document(frame_id, url) ⇒ Object

Parameters:

  • frame_id (String)
  • url (String)


337
338
339
340
341
342
343
# File 'lib/puppeteer/frame_manager.rb', line 337

def handle_frame_navigated_within_document(frame_id, url)
  frame = @frames[frame_id]
  return unless frame
  frame.navigated_within_document(url)
  emit_event(FrameManagerEmittedEvents::FrameNavigatedWithinDocument, frame)
  emit_event(FrameManagerEmittedEvents::FrameNavigated, frame)
end

#handle_frame_stopped_loading(frame_id) ⇒ Object

Parameters:

  • frameId (string)


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

def handle_frame_stopped_loading(frame_id)
  frame = @frames[frame_id]
  return if !frame
  frame.handle_loading_stopped
  emit_event(FrameManagerEmittedEvents::LifecycleEvent, frame)
end

#handle_frame_tree(session, frame_tree) ⇒ Object

Parameters:



214
215
216
217
218
219
220
221
222
223
224
# File 'lib/puppeteer/frame_manager.rb', line 214

def handle_frame_tree(session, frame_tree)
  if frame_tree['frame']['parentId']
    handle_frame_attached(session, frame_tree['frame']['id'], frame_tree['frame']['parentId'])
  end
  handle_frame_navigated(frame_tree['frame'])
  return if !frame_tree['childFrames']

  frame_tree['childFrames'].each do |child|
    handle_frame_tree(session, child)
  end
end

#handle_lifecycle_event(event) ⇒ Object

Parameters:

  • event (Hash)


197
198
199
200
201
202
# File 'lib/puppeteer/frame_manager.rb', line 197

def handle_lifecycle_event(event)
  frame = @frames[event['frameId']]
  return if !frame
  frame.handle_lifecycle_event(event['loaderId'], event['name'])
  emit_event(FrameManagerEmittedEvents::LifecycleEvent, frame)
end

#main_frame!Frame

Returns:



232
233
234
# File 'lib/puppeteer/frame_manager.rb', line 232

def main_frame
  @main_frame
end

Parameters:

  • frame (Puppeteer::Frame)
  • url (String)
  • options (!{referer?: string, timeout?: number, waitUntil?: string|!Array<string>}=)

Returns:



103
104
105
106
107
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/puppeteer/frame_manager.rb', line 103

def navigate_frame(frame, url, referer: nil, timeout: nil, wait_until: nil)
  assert_no_legacy_navigation_options(wait_until: wait_until)

  navigate_params = {
    url: url,
    referer: referer || @network_manager.extra_http_headers['referer'],
    frameId: frame.id,
  }.compact
  option_wait_until = wait_until || ['load']
  option_timeout = timeout || @timeout_settings.navigation_timeout

  watcher = Puppeteer::LifecycleWatcher.new(self, frame, option_wait_until, option_timeout)
  ensure_new_document_navigation = false

  begin
    navigate = future do
      result = @client.send_message('Page.navigate', navigate_params)
      loader_id = result['loaderId']
      ensure_new_document_navigation = !!loader_id
      if result['errorText']
        raise NavigationError.new("#{result['errorText']} at #{url}")
      end
    end
    await_any(
      navigate,
      watcher.timeout_or_termination_promise,
    )

    document_navigation_promise =
      if ensure_new_document_navigation
        watcher.new_document_navigation_promise
      else
        watcher.same_document_navigation_promise
      end
    await_any(
      document_navigation_promise,
      watcher.timeout_or_termination_promise,
    )
  rescue Puppeteer::TimeoutError => err
    raise NavigationError.new(err)
  ensure
    watcher.dispose
  end

  watcher.navigation_response
end

#page!Puppeteer.Page

Returns:



227
228
229
# File 'lib/puppeteer/frame_manager.rb', line 227

def page
  @page
end

#wait_for_frame_navigation(frame, timeout: nil, wait_until: nil) ⇒ Puppeteer::HTTPResponse

Parameters:

  • timeout (number|nil) (defaults to: nil)
  • wait_until (string|nil) (defaults to: nil)

    ‘load’ | ‘domcontentloaded’ | ‘networkidle0’ | ‘networkidle2’

Returns:



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/puppeteer/frame_manager.rb', line 153

def wait_for_frame_navigation(frame, timeout: nil, wait_until: nil)
  assert_no_legacy_navigation_options(wait_until: wait_until)

  option_wait_until = wait_until || ['load']
  option_timeout = timeout || @timeout_settings.navigation_timeout
  watcher = Puppeteer::LifecycleWatcher.new(self, frame, option_wait_until, option_timeout)
  begin
    await_any(
      watcher.timeout_or_termination_promise,
      watcher.same_document_navigation_promise,
      watcher.new_document_navigation_promise,
    )
  rescue Puppeteer::TimeoutError => err
    raise NavigationError.new(err)
  ensure
    watcher.dispose
  end

  watcher.navigation_response
end