Method: Ferrum::Network#subscribe

Defined in:
lib/ferrum/network.rb

#subscribeObject



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/ferrum/network.rb', line 116

def subscribe
  @page.on("Network.requestWillBeSent") do |params|
    request = Network::Request.new(params)

    # We can build exchange in two places, here on the event or when request
    # is interrupted. So we have to be careful when to create new one. We
    # create new exchange only if there's no with such id or there's but
    # it's filled with request which means this one is new but has response
    # for a redirect. So we assign response from the params to previous
    # exchange and build new exchange to assign this request to it.
    exchange = select(request.id).last
    exchange = build_exchange(request.id) unless exchange&.blank?

    # On redirects Chrome doesn't change `requestId` and there's no
    # `Network.responseReceived` event for such request. If there's already
    # exchange object with this id then we got redirected and params has
    # `redirectResponse` key which contains the response.
    if params["redirectResponse"]
      previous_exchange = select(request.id)[-2]
      response = Network::Response.new(@page, params)
      previous_exchange.response = response
    end

    exchange.request = request

    if exchange.navigation_request?(@page.main_frame.id)
      @exchange = exchange
    end
  end

  @page.on("Network.responseReceived") do |params|
    if exchange = select(params["requestId"]).last
      response = Network::Response.new(@page, params)
      exchange.response = response
    end
  end

  @page.on("Network.loadingFinished") do |params|
    exchange = select(params["requestId"]).last
    if exchange && exchange.response
      exchange.response.body_size = params["encodedDataLength"]
    end
  end

  @page.on("Log.entryAdded") do |params|
    entry = params["entry"] || {}
    if entry["source"] == "network" && entry["level"] == "error"
      exchange = select(entry["networkRequestId"]).last
      error = Network::Error.new(entry)
      exchange.error = error
    end
  end
end