Class: Ferrum::Context
- Inherits:
-
Object
- Object
- Ferrum::Context
- 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
-
#downloads ⇒ Downloads
readonly
The downloads of every page in the context, and where they're saved.
-
#id ⇒ String
readonly
Returns the value of attribute id.
Instance Method Summary collapse
-
#add_target(params:, session_id: nil, attached: false) ⇒ Target
private
Registers a target discovered via a CDP
Target.*event, or updates the session id on one already known. -
#attach_target(target_id) ⇒ Target
Manually attaches to a target, e.g.
-
#await_page(opener: nil, timeout: nil) { ... } ⇒ Page?
Runs the block and returns the page it opens, in a tab or a window, e.g.
-
#await_page!(**options) { ... } ⇒ Page
Same as #await_page, but raises if no page opens in time.
-
#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
targetsandpagesno longer list it once this returns. -
#cookies ⇒ Cookies
The cookies of the context, which every page in it shares.
-
#create_page(new_window: false, **options) ⇒ Page
Creates a new target in this context and eagerly connects to it as a Page, forwarding
optionsto Target#build_page. -
#create_target(new_window: false) ⇒ Target
Creates a new target in this context via
Target.createTargetand blocks until it's been registered (see #add_target). -
#default_target ⇒ Target
private
The context's first known target, creating one via
Target.createTargetif none has attached yet. -
#delete_target(target_id) ⇒ Target?
private
Removes a target, e.g.
-
#dispose ⇒ nil
Disposes this browser context and all of its targets.
-
#find_target {|arg0| ... } ⇒ Target?
private
Returns the first target for which the block returns truthy.
-
#implicit? ⇒ Boolean
Whether this is the browser's implicit context, the one it puts its startup window in.
-
#initialize(client, contexts, id, implicit: false) ⇒ Context
constructor
A new instance of Context.
-
#inspect ⇒ String
Debug representation of the context, including its known targets.
-
#page ⇒ Page
Connects to and returns the #default_target's page.
-
#pages {|target| ... } ⇒ Array<Page>
All page targets in this context, connected to as Pages.
-
#service_workers ⇒ Array<Target>
Service worker targets registered in this context.
-
#target(target_id) ⇒ Target?
The target with the given id.
-
#target?(target_id) ⇒ Boolean
private
Whether a target with the given id is known in this context.
-
#targets ⇒ Hash{String => Target}
The targets in this context by id, as they are at the time of the call.
-
#update_target(target_id, params) ⇒ void
private
Updates a known target's params, e.g.
-
#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.
Constructor Details
#initialize(client, contexts, id, implicit: false) ⇒ Context
Returns a new instance of Context.
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.
20 21 22 |
# File 'lib/ferrum/context.rb', line 20 def downloads @downloads end |
#id ⇒ String (readonly)
Returns the value of attribute id.
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.
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.
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.
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.
168 169 170 |
# File 'lib/ferrum/context.rb', line 168 def await_page!(**, &) await_page(**, &) || 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.
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.
56 57 58 |
# File 'lib/ferrum/context.rb', line 56 def @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.
183 184 185 186 |
# File 'lib/ferrum/context.rb', line 183 def create_page(new_window: false, **) target = create_target(new_window: new_window) target.build_page(**) 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).
200 201 202 203 204 205 206 207 |
# File 'lib/ferrum/context.rb', line 200 def create_target(new_window: false) = {} [:browserContextId] = @id unless implicit? [:newWindow] = true if new_window deadline = Deadline.wrap(@client.timeout) response = @client.command("Target.createTarget", timeout: deadline, url: "about:blank", **) @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.
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.
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?.
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.
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.
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.
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.
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.
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>
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.
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.
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.
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.
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.
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 |