forked from rubycdp/ferrum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
contexts.rb
81 lines (65 loc) · 2.03 KB
/
contexts.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# frozen_string_literal: true
require "ferrum/context"
module Ferrum
class Contexts
attr_reader :contexts
def initialize(browser)
@contexts = Concurrent::Hash.new
@browser = browser
subscribe
discover
end
def default_context
@default_context ||= create
end
def find_by(target_id:)
@contexts.find { |_, c| c.targets.keys.include?(target_id) }&.last
end
def create
response = @browser.command("Target.createBrowserContext")
context_id = response["browserContextId"]
context = Context.new(@browser, self, context_id)
@contexts[context_id] = context
context
end
def dispose(context_id)
context = @contexts[context_id]
@browser.command("Target.disposeBrowserContext",
browserContextId: context.id)
@contexts.delete(context_id)
true
end
def reset
@default_context = nil
@contexts.keys.each { |id| dispose(id) }
end
private
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
def discover
@browser.command("Target.setDiscoverTargets", discover: true)
end
end
end