-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
cdp_session.rb
94 lines (83 loc) · 2.65 KB
/
cdp_session.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
82
83
84
85
86
87
88
89
90
91
92
93
94
class Puppeteer::CDPSession
include Puppeteer::DebugPrint
include Puppeteer::EventCallbackable
using Puppeteer::DefineAsyncMethod
class Error < StandardError; end
# @param {!Connection} connection
# @param {string} targetType
# @param {string} sessionId
def initialize(connection, target_type, session_id)
@callbacks = {}
@connection = connection
@target_type = target_type
@session_id = session_id
end
attr_reader :connection
# @param method [String]
# @param params [Hash]
# @returns [Hash]
def send_message(method, params = {})
await async_send_message(method, params)
end
# @param method [String]
# @param params [Hash]
# @returns [Future<Hash>]
def async_send_message(method, params = {})
if !@connection
raise Error.new("Protocol error (#{method}): Session closed. Most likely the #{@target_type} has been closed.")
end
id = @connection.raw_send(message: { sessionId: @session_id, method: method, params: params })
promise = resolvable_future
callback = Puppeteer::Connection::MessageCallback.new(method: method, promise: promise)
@callbacks[id] = callback
promise
end
# @param {{id?: number, method: string, params: Object, error: {message: string, data: any}, result?: *}} object
def handle_message(message)
if message['id']
if callback = @callbacks.delete(message['id'])
callback_with_message(callback, message)
else
raise Error.new("unknown id: #{id}")
end
else
emit_event(message['method'], message['params'])
end
end
private def callback_with_message(callback, message)
if message['error']
callback.reject(
Puppeteer::Connection::ProtocolError.new(
method: callback.method,
error_message: message['error']['message'],
error_data: message['error']['data']))
else
callback.resolve(message['result'])
end
end
def detach
if !@connection
raise Error.new("Session already detarched. Most likely the #{@target_type} has been closed.")
end
@connection.send_message('Target.detachFromTarget', sessionId: @session_id)
end
def handle_closed
@callbacks.each_value do |callback|
callback.reject(
Puppeteer::Connection::ProtocolError.new(
method: callback.method,
error_message: 'Target Closed.'))
end
@callbacks.clear
@connection = nil
emit_event(CDPSessionEmittedEvents::Disconnected)
end
# @param event_name [String]
def on(event_name, &block)
add_event_listener(event_name, &block)
end
# @param event_name [String]
def once(event_name, &block)
observe_first(event_name, &block)
end
end