class Ferrum::Contexts

Attributes

contexts[R]

Public Class Methods

new(browser) click to toggle source
# File lib/ferrum/contexts.rb, line 9
def initialize(browser)
  @contexts = Concurrent::Map.new
  @browser = browser
  subscribe
  discover
end

Public Instance Methods

create() click to toggle source
# File lib/ferrum/contexts.rb, line 26
def create
  response = @browser.command("Target.createBrowserContext")
  context_id = response["browserContextId"]
  context = Context.new(@browser, self, context_id)
  @contexts[context_id] = context
  context
end
default_context() click to toggle source
# File lib/ferrum/contexts.rb, line 16
def default_context
  @default_context ||= create
end
dispose(context_id) click to toggle source
# File lib/ferrum/contexts.rb, line 34
def dispose(context_id)
  context = @contexts[context_id]
  @browser.command("Target.disposeBrowserContext",
                   browserContextId: context.id)
  @contexts.delete(context_id)
  true
end
find_by(target_id:) click to toggle source
# File lib/ferrum/contexts.rb, line 20
def find_by(target_id:)
  context = nil
  @contexts.each_value { |c| context = c if c.has_target?(target_id) }
  context
end
reset() click to toggle source
# File lib/ferrum/contexts.rb, line 42
def reset
  @default_context = nil
  @contexts.keys.each { |id| dispose(id) }
end

Private Instance Methods

discover() click to toggle source
# File lib/ferrum/contexts.rb, line 79
def discover
  @browser.command("Target.setDiscoverTargets", discover: true)
end
subscribe() click to toggle source
# File lib/ferrum/contexts.rb, line 49
def subscribe
  @browser.client.on("Target.targetCreated") do |params|
    info = params["targetInfo"]
    next unless info["type"] == "page"

    context_id = info["browserContextId"]
    @contexts[context_id]&.add_target(info)
  end

  @browser.client.on("Target.targetInfoChanged") do |params|
    info = params["targetInfo"]
    next unless info["type"] == "page"

    context_id, target_id = info.values_at("browserContextId", "targetId")
    @contexts[context_id]&.update_target(target_id, info)
  end

  @browser.client.on("Target.targetDestroyed") do |params|
    if context = find_by(target_id: params["targetId"])
      context.delete_target(params["targetId"])
    end
  end

  @browser.client.on("Target.targetCrashed") do |params|
    if context = find_by(target_id: params["targetId"])
      context.delete_target(params["targetId"])
    end
  end
end