Class: Ferrum::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/ferrum/context.rb,
sig/ferrum/context.rbs

Overview

Represents a browser context, i.e. an isolated browsing profile (similar to an incognito window) with its own cookies, cache and storage. Keeps track of the Targets that belong to it and connects to them as Pages or Workers. Managed by Contexts, which owns the browser's collection of contexts and routes CDP target events to the right one.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client, contexts, id, implicit: false) ⇒ Context

Returns a new instance of Context.

Parameters:

  • (Client)
  • (Contexts)
  • (String)
  • implicit: (Boolean) (defaults to: false)


22
23
24
25
26
27
28
29
30
31
# File 'lib/ferrum/context.rb', line 22

def initialize(client, contexts, id, implicit: false)
  @id = id
  @implicit = implicit
  @client = client
  @contexts = contexts
  @targets = Concurrency::AwaitableMap.new
  @page_waiters = []
  @page_waiters_mutex = Mutex.new
  @downloads = Downloads.new(client, implicit ? nil : id)
end

Instance Attribute Details

#downloads ⇒ Downloads (readonly)

The downloads of every page in the context, and where they're saved.

Returns:



20
21
22
# File 'lib/ferrum/context.rb', line 20

def downloads
  @downloads
end

#id ⇒ String (readonly)

Returns the value of attribute id.

Returns:

  • (String)


15
16
17
# File 'lib/ferrum/context.rb', line 15

def id
  @id
end

Instance Method Details

#add_target(params:, session_id: nil, attached: false) ⇒ Target

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Registers a target discovered via a CDP Target.* event, or updates the session id on one already known. Called by Ferrum::Contexts as targets are created/attached.

Parameters:

  • params (Hash) —

    The target's targetInfo.

  • session_id (String, nil) (defaults to: nil)
  • attached (Boolean) (defaults to: false) —

    The session comes from Target.attachedToTarget, so it replaces the one a target got from its frame owner.

  • params: (Hash[String, untyped])
  • session_id: (String, nil) (defaults to: nil)
  • attached: (Boolean) (defaults to: false)

Returns:



224
225
226
227
228
229
230
231
232
233
# File 'lib/ferrum/context.rb', line 224

def add_target(params:, session_id: nil, attached: false)
  new_target = Target.new(@client, session_id, params, implicit: implicit?)
  target = @targets[new_target.id] || new_target
  # on first iteration session_id may be nil, then if session is present here we must set it to the target
  target.session_id = session_id if session_id && (attached || target.session_id.nil?)
  @default_target ||= target
  @targets[target.id] = target
  announce_page(target) if target.equal?(new_target)
  target
end

#attach_target(target_id) ⇒ Target

Manually attaches to a target, e.g. a service worker discovered via #service_workers. Once attached, target.worker/target.page returns a connected Worker/Page for it. A target that already has a session keeps it.

Note: attaching to a service worker's session prevents Chrome from ever terminating it while the connection is open.

Parameters:

  • target_id (String)

Returns:

Raises:



276
277
278
279
280
281
282
283
284
285
286
# File 'lib/ferrum/context.rb', line 276

def attach_target(target_id)
  target = @targets[target_id]
  raise NoSuchTargetError, "No target #{target_id} in context #{id}" unless target
  return target if target.session_id

  @contexts.manually_attached(target_id)
  session = @client.command("Target.attachToTarget", timeout: Client::PROTOCOL_TIMEOUT,
                                                     targetId: target_id, flatten: true)
  target.session_id = session["sessionId"]
  target
end

#await_page(opener: nil, timeout: nil) { ... } ⇒ Page?

Runs the block and returns the page it opens, in a tab or a window, e.g. through window.open or a link with target="_blank".

Only a page that another page opened is seen. Chrome reports no opener for a page the user opens from a link, i.e. a click with Ctrl, Cmd or Shift held, or a middle click, so such a page is not returned. Compare #targets before and after the click to find it.

Examples:

opened = browser.await_page { browser.at_css("a[target=_blank]").click }
opened.url # => "https://example.com/"

Parameters:

  • opener (Page, nil) (defaults to: nil) —

    Only return a page opened by this page. By default a page opened by any page of the context is returned.

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

    How long the block and the new page may take together. Defaults to the browser's timeout.

  • opener: (Page, nil) (defaults to: nil)
  • timeout: (::Numeric, Deadline, nil) (defaults to: nil)

Yields:

  • The code that opens the page.

Yield Returns:

  • (void)

Returns:

  • (Page, nil) —

    The first page opened since the call, nil if none opens in time.

Raises:

  • (ArgumentError) —

    If no block is given.



143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/ferrum/context.rb', line 143

def await_page(opener: nil, timeout: nil)
  raise ArgumentError, "await_page needs a block that opens the page" unless block_given?

  deadline = Deadline.wrap(timeout || @client.timeout)
  waiter = [opener&.target_id, Concurrency::Cell.new]
  @page_waiters_mutex.synchronize { @page_waiters << waiter }
  yield
  return unless waiter.last.wait(deadline)

  waiter.last.value.page
ensure
  @page_waiters_mutex.synchronize { @page_waiters.delete(waiter) }
end

#await_page!(**options) { ... } ⇒ Page

Same as #await_page, but raises if no page opens in time.

Parameters:

Yields:

  • The code that opens the page.

Yield Returns:

  • (void)

Returns:

Raises:



168
169
170
# File 'lib/ferrum/context.rb', line 168

def await_page!(**options, &)
  await_page(**options, &) || raise(TimeoutError)
end

#close_target(target_id) ⇒ nil

Closes a target in the browser, and its page or worker if one is connected, and removes it from the context right away, so targets and pages no longer list it once this returns. Chrome reports the target destroyed only later.

Parameters:

  • target_id (String)

Returns:

  • (nil)

Raises:



298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
# File 'lib/ferrum/context.rb', line 298

def close_target(target_id)
  target = @targets[target_id]
  raise NoSuchTargetError, "No target #{target_id} in context #{id}" unless target

  if !target.connected?
    @client.notify("Target.closeTarget", targetId: target_id)
  elsif target.page?
    target.page.close
  else
    target.worker.close
  end
  delete_target(target_id)

  nil
end

#cookies ⇒ Cookies

The cookies of the context, which every page in it shares.

Returns:



56
57
58
# File 'lib/ferrum/context.rb', line 56

def cookies
  @cookies ||= Cookies.new(@client, @id)
end

#create_page(new_window: false, **options) ⇒ Page

Creates a new target in this context and eagerly connects to it as a Page, forwarding options to Target#build_page.

Parameters:

  • new_window (Boolean) (defaults to: false) —

    Opens the page in a window of its own instead of a tab, see #create_target.

  • options (Hash)
  • new_window: (Boolean) (defaults to: false)

Returns:

Raises:



183
184
185
186
# File 'lib/ferrum/context.rb', line 183

def create_page(new_window: false, **options)
  target = create_target(new_window: new_window)
  target.build_page(**options)
end

#create_target(new_window: false) ⇒ Target

Creates a new target in this context via Target.createTarget and blocks until it's been registered (see #add_target).

Parameters:

  • new_window (Boolean) (defaults to: false) —

    Opens the target in a window of its own. Otherwise it's a tab in the window Chrome last opened for this context.

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

Returns:

Raises:



200
201
202
203
204
205
206
207
# File 'lib/ferrum/context.rb', line 200

def create_target(new_window: false)
  options = {}
  options[:browserContextId] = @id unless implicit?
  options[:newWindow] = true if new_window
  deadline = Deadline.wrap(@client.timeout)
  response = @client.command("Target.createTarget", timeout: deadline, url: "about:blank", **options)
  @targets.await(response["targetId"], deadline) || raise(NoSuchTargetError)
end

#default_target ⇒ Target

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The context's first known target, creating one via Target.createTarget if none has attached yet.

Returns:



49
50
51
# File 'lib/ferrum/context.rb', line 49

def default_target
  @default_target ||= create_target
end

#delete_target(target_id) ⇒ Target?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Removes a target, e.g. on Target.targetDestroyed/targetCrashed.

Parameters:

  • target_id (String)

Returns:



255
256
257
258
259
# File 'lib/ferrum/context.rb', line 255

def delete_target(target_id)
  target = @targets.delete(target_id)
  target&.release_waiters
  target
end

#dispose ⇒ nil

Disposes this browser context and all of its targets. The browser's implicit context cannot be disposed, see #implicit?.

Returns:

  • (nil)

Raises:



332
333
334
# File 'lib/ferrum/context.rb', line 332

def dispose
  @contexts.dispose(@id)
end

#find_target {|arg0| ... } ⇒ Target?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the first target for which the block returns truthy.

Yields:

Yield Parameters:

Yield Returns:

  • (Boolean)

Returns:



319
320
321
322
323
324
# File 'lib/ferrum/context.rb', line 319

def find_target
  targets = @targets.values
  targets.each { |t| return t if yield(t) }

  nil
end

#implicit? ⇒ Boolean

Whether this is the browser's implicit context, the one it puts its startup window in. We didn't create it, so we can't dispose it, and Chrome doesn't let us address it by id either: targets are created in it by omitting browserContextId altogether.

Returns:

  • (Boolean)


39
40
41
# File 'lib/ferrum/context.rb', line 39

def implicit?
  @implicit
end

#inspect ⇒ String

Debug representation of the context, including its known targets.

Returns:

  • (String)


360
361
362
# File 'lib/ferrum/context.rb', line 360

def inspect
  %(#<#{self.class} @id=#{@id.inspect} @targets=#{@targets.inspect} @default_target=#{@default_target.inspect}>)
end

#page ⇒ Page

Connects to and returns the #default_target's page.

Returns:

Raises:



65
66
67
# File 'lib/ferrum/context.rb', line 65

def page
  default_target.page
end

#pages {|target| ... } ⇒ Array<Page>

All page targets in this context, connected to as Pages.

Examples:

The pages opened by another page

browser.pages(&:opener_id)

Yields:

  • (target) —

    Only the pages of the targets the block returns truthy for are connected to and returned.

Yield Parameters:

Returns:

Raises:



90
91
92
93
94
# File 'lib/ferrum/context.rb', line 90

def pages(&)
  targets = @targets.values.select(&:page?)
  targets = targets.select(&) if block_given?
  targets.map(&:page)
end

#service_workers ⇒ Array<Target>

Service worker targets registered in this context. Unlike #workers, these are plain Targets and are not connected to. Attaching to a service worker's session keeps it alive indefinitely, so we only do that on demand, via target.worker.

Returns:



112
113
114
# File 'lib/ferrum/context.rb', line 112

def service_workers
  @targets.values.select(&:service_worker?)
end

#target(target_id) ⇒ Target?

The target with the given id.

Parameters:

  • target_id (String)

Returns:

  • (Target, nil) —

    nil when the context has no such target.



342
343
344
# File 'lib/ferrum/context.rb', line 342

def target(target_id)
  @targets[target_id]
end

#target?(target_id) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Whether a target with the given id is known in this context.

Parameters:

  • target_id (String)

Returns:

  • (Boolean)


353
354
355
# File 'lib/ferrum/context.rb', line 353

def target?(target_id)
  !!target(target_id)
end

#targets ⇒ Hash{String => Target}

The targets in this context by id, as they are at the time of the call.

Returns:



72
73
74
# File 'lib/ferrum/context.rb', line 72

def targets
  @targets.to_h
end

#update_target(target_id, params) ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Updates a known target's params, e.g. on Target.targetInfoChanged.

Parameters:

  • target_id (String)
  • params (Hash)


244
245
246
# File 'lib/ferrum/context.rb', line 244

def update_target(target_id, params)
  @targets[target_id]&.update(params)
end

#workers ⇒ Array<Worker>

Dedicated and shared workers spawned by any page in this context, leaving out the ones we have no session with, e.g. detached ones.

Returns:

Raises:



102
103
104
# File 'lib/ferrum/context.rb', line 102

def workers
  @targets.values.select { |t| (t.worker? || t.shared_worker?) && t.session_id }.map(&:worker)
end