Module: Isomorfeus::Puppetmaster::Driver::PuppeteerDocument

Included in:
Puppeteer
Defined in:
lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb

Instance Method Summary collapse

Instance Method Details

#document_accept_alert(document, **options, &block) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 5

def document_accept_alert(document, **options, &block)
  # TODO maybe wrap in mutex
  text =  options.key?(:text) ? "`#{options[:text]}`" : 'null'
  @context.exec <<~JAVASCRIPT
    ModalText = #{text};
    AllPageHandles[#{document.handle}].on('dialog', DialogAcceptHandler);
  JAVASCRIPT
  block.call
  sleep @reaction_timeout
  @context.eval 'ModalText'
ensure
  matched = await <<~JAVASCRIPT
    LastResult = ModalTextMatched;
    ModalTextMatched = false;
    ModalText = null;
    AllPageHandles[#{document.handle}].removeListener('dialog', DialogAcceptHandler);
  JAVASCRIPT
  raise Isomorfeus::Puppetmaster::NoModalError if options.key?(:text) && !matched
end

#document_accept_confirm(document, **options, &block) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 25

def document_accept_confirm(document, **options, &block)
  # TODO maybe wrap in mutex
  text =  options.key?(:text) ? "`#{options[:text]}`" : 'null'
  @context.exec <<~JAVASCRIPT
    ModalText = #{text};
    AllPageHandles[#{document.handle}].on('dialog', DialogAcceptHandler);
  JAVASCRIPT
  block.call
  sleep @reaction_timeout
  @context.eval 'ModalText'
ensure
  matched = await <<~JAVASCRIPT
    LastResult = ModalTextMatched;
    ModalTextMatched = false;
    ModalText = null;
    AllPageHandles[#{document.handle}].removeListener('dialog', DialogAcceptHandler);
  JAVASCRIPT
  raise Isomorfeus::Puppetmaster::NoModalError if options.key?(:text) && !matched
end

#document_accept_leave_page(document, **options, &block) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 45

def document_accept_leave_page(document, **options, &block)
  # TODO maybe wrap in mutex
  text =  options.key?(:text) ? "`#{options[:text]}`" : 'null'
  @context.exec <<~JAVASCRIPT
    ModalText = #{text};
    AllPageHandles[#{document.handle}].on('dialog', DialogAcceptHandler);
  JAVASCRIPT
  block.call
  sleep @reaction_timeout
  @context.eval 'ModalText'
ensure
  matched = await <<~JAVASCRIPT
    LastResult = ModalTextMatched;
    ModalTextMatched = false;
    ModalText = null;
    AllPageHandles[#{document.handle}].removeListener('dialog', DialogAcceptHandler);
  JAVASCRIPT
  raise Isomorfeus::Puppetmaster::NoModalError if options.key?(:text) && !matched
end

#document_accept_prompt(document, **options, &block) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 65

def document_accept_prompt(document, **options, &block)
  # TODO maybe wrap in mutex
  text =  options.key?(:text) ? "`#{options[:text]}`" : 'null'
  @context.exec <<~JAVASCRIPT
    ModalText = #{text};
    AllPageHandles[#{document.handle}].on('dialog', DialogAcceptHandler);
  JAVASCRIPT
  block.call
  sleep @reaction_timeout
  @context.eval 'ModalText'
ensure
  matched = await <<~JAVASCRIPT
    LastResult = ModalTextMatched;
    ModalTextMatched = false;
    ModalText = null;
    AllPageHandles[#{document.handle}].removeListener('dialog', DialogAcceptHandler);
  JAVASCRIPT
  raise Isomorfeus::Puppetmaster::NoModalError if options.key?(:text) && !matched
end

#document_all_text(document) ⇒ Object



85
86
87
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 85

def document_all_text(document)
  await("LastResult = AllPageHandles[#{document.handle}].evaluate(function(){ return document.documentElement.textContent; });")
end

#document_body(document) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 89

def document_body(document)
  node_data = await <<~JAVASCRIPT
    var element_handle = await AllPageHandles[#{document.handle}].$('body');
    if (element_handle) {
      var node_handle = RegisterElementHandle(element_handle);
      var tt = await AllElementHandles[node_handle].executionContext().evaluate((node) => {
        var name = node.nodeName;
        var tag = node.tagName.toLowerCase();
        return [name, tag, null, node.isContentEditable];
      }, AllElementHandles[node_handle]);
      LastResult = {handle: node_handle, name: tt[0], tag: tt[1], type: tt[2], content_editable: tt[3]};
    }
  JAVASCRIPT
  if node_data
    node_data[:css_selector] = 'body'
    Isomorfeus::Puppetmaster::Node.new_by_tag(self, document, node_data)
  end
end

#document_bring_to_front(document) ⇒ Object



108
109
110
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 108

def document_bring_to_front(document)
  await("await AllPageHandles[#{document.handle}].bringToFront();")
end

#document_clear_authentication_credentials(document) ⇒ Object



112
113
114
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 112

def document_clear_authentication_credentials(document)
  await("AllPageHandles[#{document.handle}].authenticate(null);")
end

#document_clear_cookies(document) ⇒ Object



116
117
118
119
120
121
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 116

def document_clear_cookies(document)
  await <<~JAVASCRIPT
    var cookies = await AllPageHandles[#{document.handle}].cookies();
    cookies.forEach(async(cookie) => {await AllPageHandles[#{document.handle}].deleteCookie(cookie);});
  JAVASCRIPT
end

#document_clear_extra_headers(document) ⇒ Object



123
124
125
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 123

def document_clear_extra_headers(document)
  await ("AllPageHandles[#{document.handle}].setExtraHTTPHeaders({});")
end

#document_clear_url_blacklist(document) ⇒ Object



127
128
129
130
131
132
133
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 127

def document_clear_url_blacklist(document)
  await <<~JAVASCRIPT
    var cdp_session = await AllPageHandles[#{document.handle}].target().createCDPSession();
    await cdp_session.send('Network.setBlockedURLs', {urls: []});
    await cdp_session.detach();
  JAVASCRIPT
end

#document_click(document, x: nil, y: nil, modifiers: nil) ⇒ Object



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
169
170
171
172
173
174
175
176
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 135

def document_click(document, x: nil, y: nil, modifiers: nil)
  # modifier_keys: :alt, :control, :meta, :shift
  # await "await  AllPageHandles[#{document.handle}].mouse.click(#{x},#{y},{button: 'left'});"
  # raise Isomorfeus::Pupppetmaster::InvalidActionError.new(:click) unless visible?
  modifiers = [modifiers] if modifiers.is_a?(Symbol)
  modifiers = [] unless modifiers
  modifiers = modifiers.map {|key| key.to_s.camelize(:lower) }
  await <<~JAVASCRIPT
    var response_event_occurred = false;
    var response_handler = function(event){ response_event_occurred = true; };
    var response_watcher = new Promise(function(resolve, reject){
      setTimeout(function(){
        if (!response_event_occurred) { resolve(true); } 
        else { setTimeout(function(){ resolve(true); }, #{@puppeteer_timeout}); }
        AllPageHandles[#{document.handle}].removeListener('response', response_handler);
      }, #{@puppeteer_reaction_timeout});
    });
    AllPageHandles[#{document.handle}].on('response', response_handler);
    var navigation_watcher = AllPageHandles[#{document.handle}].waitForNavigation();
    await AllPageHandles[#{document.handle}].evaluate(function(){ 
      var options = {button: 0, bubbles: true, cancelable: true};
      var node = window;
      var x = #{x ? x : 'null'};
      var y = #{y ? y : 'null'};
      var modifiers = #{modifiers};
      if (x && y) {
        options['clientX'] = x;
        options['clientY'] = y;
        var n = document.elementFromPoint(x, y);
        if (n) { node = n };
      }  
      if (modifiers.includes('meta')) { options['metaKey'] = true; }
      if (modifiers.includes('control')) { options['ctrlKey'] = true; }
      if (modifiers.includes('shift')) { options['shiftKey'] = true; }
      if (modifiers.includes('alt')) { options['altKey'] = true; }
      node.dispatchEvent(new MouseEvent('mousedown', options));
      node.dispatchEvent(new MouseEvent('mouseup', options));
      node.dispatchEvent(new MouseEvent('click', options));
    });
    await Promise.race([response_watcher, navigation_watcher]);
  JAVASCRIPT
end

#document_close(document) ⇒ Object



178
179
180
181
182
183
184
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 178

def document_close(document)
  await <<~JAVASCRIPT
    await AllPageHandles[#{document.handle}].close();
    delete AllPageHandles[#{document.handle}];
    delete ConsoleMessages[#{document.handle}];
  JAVASCRIPT
end

#document_console(document) ⇒ Object



186
187
188
189
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 186

def document_console(document)
  messages = @context.exec "return ConsoleMessages[#{document.handle}]"
  messages.map {|m| Isomorfeus::Puppetmaster::ConsoleMessage.new(m)}
end

#document_cookies(document) ⇒ Object



191
192
193
194
195
196
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 191

def document_cookies(document)
  result = await("LastResult = await AllPageHandles[#{document.handle}].cookies();")
  result_hash = {}
  result.each { |cookie| result_hash[cookie['name']] = Isomorfeus::Puppetmaster::Cookie.new(cookie) }
  result_hash
end

#document_dismiss_confirm(document, **options, &block) ⇒ Object



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 198

def document_dismiss_confirm(document, **options, &block)
  # TODO
  text =  options.key?(:text) ? "`#{options[:text]}`" : 'null'
  @context.exec <<~JAVASCRIPT
    ModalText = #{text};
    AllPageHandles[#{document.handle}].on('dialog', DialogDismissHandler);
  JAVASCRIPT
  block.call
  sleep @reaction_timeout
  @context.eval 'ModalText'
ensure
  matched = await <<~JAVASCRIPT
    LastResult = ModalTextMatched;
    ModalTextMatched = false;
    ModalText = null;
    AllPageHandles[#{document.handle}].removeListener('dialog', DialogDismissHandler);
  JAVASCRIPT
  raise Isomorfeus::Puppetmaster::ModalNotFound if options.key?(:text) && !matched
end

#document_dismiss_leave_page(document, **options, &block) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 218

def document_dismiss_leave_page(document, **options, &block)
  # TODO
  text =  options.key?(:text) ? "`#{options[:text]}`" : 'null'
  @context.exec <<~JAVASCRIPT
    ModalText = #{text};
    AllPageHandles[#{document.handle}].on('dialog', DialogDismissHandler);
  JAVASCRIPT
  block.call
  sleep @reaction_timeout
  @context.eval 'ModalText'
ensure
  matched = await <<~JAVASCRIPT
    LastResult = ModalTextMatched;
    ModalTextMatched = false;
    ModalText = null;
    AllPageHandles[#{document.handle}].removeListener('dialog', DialogDismissHandler);
  JAVASCRIPT
  raise Isomorfeus::Puppetmaster::ModalNotFound if options.key?(:text) && !matched
end

#document_dismiss_prompt(document, **options, &block) ⇒ Object



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 238

def document_dismiss_prompt(document, **options, &block)
  # TODO
  text =  options.key?(:text) ? "`#{options[:text]}`" : 'null'
  @context.exec <<~JAVASCRIPT
    ModalText = #{text};
    AllPageHandles[#{document.handle}].on('dialog', DialogDismissHandler);
  JAVASCRIPT
  block.call
  sleep @reaction_timeout
  @context.eval 'ModalText'
ensure
  matched = await <<~JAVASCRIPT
    LastResult = ModalTextMatched;
    ModalTextMatched = false;
    ModalText = null;
    AllPageHandles[#{document.handle}].removeListener('dialog', DialogDismissHandler);
  JAVASCRIPT
  raise Isomorfeus::Puppetmaster::ModalNotFound if options.key?(:text) && !matched
end

#document_dispatch_event(document, name, event_type = nil, **options) ⇒ Object

Raises:

  • (ArgumentError)


258
259
260
261
262
263
264
265
266
267
268
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 258

def document_dispatch_event(document, name, event_type = nil, **options)
  raise ArgumentError, 'Unknown event' unless EVENTS.key?(name.to_sym) || event_type
  event_type, opts = *EVENTS[name.to_s.downcase.tr('_', '').to_sym] if event_type.nil?
  opts.merge!(options)
  await <<~JAVASCRIPT
    handle = await AllPageHandles[#{document.handle}].evaluate(function(node){
      var event = new #{event_type}('#{name}'#{opts.empty? ? '' : opts});
      document.dispatchEvent(event);
    });
  JAVASCRIPT
end

#document_double_click(document, x: nil, y: nil, modifiers: nil) ⇒ Object



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 270

def document_double_click(document, x: nil, y: nil, modifiers: nil)
  # modifier_keys: :alt, :control, :meta, :shift
  modifiers = [modifiers] if modifiers.is_a?(Symbol)
  modifiers = [] unless modifiers
  modifiers = modifiers.map {|key| key.to_s.camelize(:lower) }
  await <<~JAVASCRIPT
    var response_event_occurred = false;
    var response_handler = function(event){ response_event_occurred = true; };
    var response_watcher = new Promise(function(resolve, reject){
      setTimeout(function(){
        if (!response_event_occurred) { resolve(true); } 
        else { setTimeout(function(){ resolve(true); }, #{@puppeteer_timeout}); }
        AllPageHandles[#{document.handle}].removeListener('response', response_handler);
      }, #{@puppeteer_reaction_timeout});
    });
    AllPageHandlers[#{document.handle}].on('response', response_handler);
    var navigation_watcher = AllPageHandles[#{document.handle}].waitForNavigation();
    await AllPageHandles[#{document.handle}].evaluate(function(){
      var options = {button: 0, bubbles: true, cancelable: true};
      var node = window;
      var x = #{x ? x : 'null'};
      var y = #{y ? y : 'null'};
      var modifiers = #{modifiers};
      if (x && y) {
        options['clientX'] = x;
        options['clientY'] = y;
        var n = document.elementFromPoint(x, y);
        if (n) { node = n };
      }
      if (modifiers.includes('meta')) { options['metaKey'] = true; }
      if (modifiers.includes('control')) { options['ctrlKey'] = true; }
      if (modifiers.includes('shift')) { options['shiftKey'] = true; }
      if (modifiers.includes('alt')) { options['altKey'] = true; }
      node.dispatchEvent(new MouseEvent('mousedown', options));
      node.dispatchEvent(new MouseEvent('mouseup', options));
      node.dispatchEvent(new MouseEvent('dblclick', options));
    });
    await Promise.race([response_watcher, navigation_watcher]);
  JAVASCRIPT
end

#document_evaluate_script(document, script, *args) ⇒ Object



311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 311

def document_evaluate_script(document, script, *args)
  await <<~JAVASCRIPT
    var result = await AllPageHandles[#{document.handle}].evaluate((arguments) => {
      try {
        var res = (function(arguments) {
          return #{script.strip};
        })(arguments);
        return [res, null];
      } catch (err) {
        return [null, {name: err.name, message: err.message, stack: err.stack}]; 
      }
    }, #{args});
    if (result) {
      LastResult = result[0];
      LastErr = result[1];
    }
  JAVASCRIPT
end

#document_execute_script(document, script, *args) ⇒ Object



330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 330

def document_execute_script(document, script, *args)
  await <<~JAVASCRIPT
    var result = await AllPageHandles[#{document.handle}].evaluate((arguments) => {
      try {
        var res = (function(arguments) {
          #{script.strip};
        })(arguments);
        return [res, null];
      } catch (err) {
        return [null, {name: err.name, message: err.message, stack: err.stack}]; 
      } 
    }, #{args});
    if (result) {
      LastResult = result[0];
      LastErr = result[1];
    }
  JAVASCRIPT
end

#document_find(document, selector) ⇒ Object



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 349

def document_find(document, selector)
  js_escaped_selector = selector.gsub('\\', '\\\\\\').gsub('"', '\"')
  node_data = await <<~JAVASCRIPT
    var element_handle = await AllPageHandles[#{document.handle}].$("#{js_escaped_selector}");
    if (element_handle) {
      var node_handle = RegisterElementHandle(element_handle);
      var tt = await AllPageHandles[#{document.handle}].evaluate((node) => {
        var tag = node.tagName ? node.tagName.toLowerCase() : '';
        var name = node.nodeName;
        var type = null;
        if (tag === 'input') { type = node.getAttribute('type'); }
        return [name, tag, type, node.isContentEditable];
      }, AllElementHandles[node_handle]);
      LastResult = {handle: node_handle, name: tt[0], tag: tt[1], type: tt[2], content_editable: tt[3]};
    }
  JAVASCRIPT
  if node_data
    node_data[:css_selector] = selector
    Isomorfeus::Puppetmaster::Node.new_by_tag(self, document, node_data)
  else
    raise Isomorfeus::Puppetmaster::ElementNotFound.new(selector)
  end
end

#document_find_all(document, selector) ⇒ Object



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 373

def document_find_all(document, selector)
  js_escaped_selector = selector.gsub('\\', '\\\\\\').gsub('"', '\"')
  node_data_array = await <<~JAVASCRIPT
    var node_data_array = [];
    var element_handle_array = await AllPageHandles[#{document.handle}].$$("#{js_escaped_selector}");
    if (element_handle_array) {
      for (var i=0; i<element_handle_array.length; i++) {
        var node_handle = RegisterElementHandle(element_handle_array[i]);
        var tt = await AllPageHandles[#{document.handle}].evaluate((node) => {
          var tag = node.tagName ? node.tagName.toLowerCase() : '';
          var name = node.nodeName;
          var type = null;
          if (tag === 'input') { type = node.getAttribute('type'); }
          return [name, tag, type, node.isContentEditable];
        }, AllElementHandles[node_handle]);
        node_data_array.push({handle: node_handle, name: tt[0], tag: tt[1], type: tt[2], content_editable: tt[3]});
      }  
    }
    LastResult = node_data_array;
  JAVASCRIPT
  node_data_array.map do |node_data|
    node_data[:css_selector] = selector
    Isomorfeus::Puppetmaster::Node.new_by_tag(self, document, node_data)
  end
end

#document_find_all_xpath(document, query) ⇒ Object



399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 399

def document_find_all_xpath(document, query)
  js_escaped_query = query.gsub('\\', '\\\\\\').gsub('"', '\"')
  node_data_array = await <<~JAVASCRIPT
    var node_data_array = [];
    var element_handle_array = await AllPageHandles[#{document.handle}].$x("#{js_escaped_query}");
    if (element_handle_array) {  
      for (var i=0; i<element_handle_array.length; i++) {
        var node_handle = RegisterElementHandle(element_handle_array[i]);
        var tt = await AllPageHandles[#{document.handle}].evaluate((node) => {
          var tag = node.tagName ? node.tagName.toLowerCase() : '';
          var name = node.nodeName;
          var type = null;
          if (tag === 'input') { type = node.getAttribute('type'); }
          return [name, tag, type, node.isContentEditable];
        }, AllElementHandles[node_handle]);
        node_data_array.push({handle: node_handle, name: tt[0], tag: tt[1], type: tt[2], content_editable: tt[3]});
      }
    }
    LastResult = node_data_array;
  JAVASCRIPT
  node_data_array.map do |node_data|
    node_data[:xpath_query] = query
    Isomorfeus::Puppetmaster::Node.new_by_tag(self, document, node_data)
  end
end

#document_find_xpath(document, query) ⇒ Object



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 425

def document_find_xpath(document, query)
  js_escaped_query = query.gsub('\\', '\\\\\\').gsub('"', '\"')
  node_data = await <<~JAVASCRIPT
    var element_handle_array = await AllPageHandles[#{document.handle}].$x("#{js_escaped_query}");
    var element_handle = (element_handle_array) ? element_handle_array[0] : null;
    if (element_handle) {
      var node_handle = RegisterElementHandle(element_handle);
      var tt = await AllPageHandles[#{document.handle}].evaluate((node) => {
        var tag = node.tagName ? node.tagName.toLowerCase() : '';
        var name = node.nodeName;
        var type = null;
        if (tag === 'input') { type = node.getAttribute('type'); }
        return [name, tag, type, node.isContentEditable];
      }, AllElementHandles[node_handle]);
      LastResult = {handle: node_handle, name: tt[0], tag: tt[1], type: tt[2], content_editable: tt[3]};
    }
  JAVASCRIPT
  if node_data
    node_data[:xpath_query] = query
    Isomorfeus::Puppetmaster::Node.new_by_tag(self, document, node_data)
  else
    raise Isomorfeus::Puppetmaster::ElementNotFound.new(query)
  end
end

#document_go_back(document) ⇒ Object



450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 450

def document_go_back(document)
  response_hash, messages = await <<~JAVASCRIPT
    ConsoleMessages[#{document.handle}] = [];
    var response = await AllPageHandles[#{document.handle}].goBack();
    if (response) {
      var request = response.request();
      var formatted_response = {
        headers: response.headers(),
        ok: response.ok(),
        remote_address: response.remoteAddress(),
        request: {
          failure: request.failure(),
          headers: request.headers(),
          method: request.method(),
          post_data: request.postData(),
          resource_type: request.resourceType(),
          url: request.url()
        },
        status: response.status(),
        status_text: response.statusText(),
        text: response.text(),
        url: response.url()
      };
      LastResult = [formatted_response, ConsoleMessages[#{document.handle}]];
    } else {
      LastResult = [null, ConsoleMessages[#{document.handle}]];
    }
  JAVASCRIPT
  con_messages = messages.map {|m| Isomorfeus::Puppetmaster::ConsoleMessage.new(m)}
  con_messages.each { |m| raise determine_error({ 'message' => m.text }) if m.level == 'error' && !m.text.start_with?('Failed to load resource:') }
  if response_hash
    response = Isomorfeus::Puppetmaster::Response.new(response_hash)
    document.instance_variable_set(:@response, response)
  end
  document.response
end

#document_go_forward(document) ⇒ Object



487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 487

def document_go_forward(document)
  response_hash, messages = await <<~JAVASCRIPT
    ConsoleMessages[#{document.handle}] = [];
    var response = await AllPageHandles[#{document.handle}].goForward();
    if (response) {
      var request = response.request();
      var formatted_response = {
        headers: response.headers(),
        ok: response.ok(),
        remote_address: response.remoteAddress(),
        request: {
          failure: request.failure(),
          headers: request.headers(),
          method: request.method(),
          post_data: request.postData(),
          resource_type: request.resourceType(),
          url: request.url()
        },
        status: response.status(),
        status_text: response.statusText(),
        text: response.text(),
        url: response.url()
      };
      LastResult = [formatted_response, ConsoleMessages[#{document.handle}]];
    } else {
      LastResult = [null, ConsoleMessages[#{document.handle}]];
    }
  JAVASCRIPT
  con_messages = messages.map {|m| Isomorfeus::Puppetmaster::ConsoleMessage.new(m)}
  con_messages.each { |m| raise determine_error({ 'message' => m.text }) if m.level == 'error' && !m.text.start_with?('Failed to load resource:') }
  if response_hash
    response = Isomorfeus::Puppetmaster::Response.new(response_hash)
    document.instance_variable_set(:@response, response)
  end
  document.response
end

#document_goto(document, uri) ⇒ Object



524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 524

def document_goto(document, uri)
  parsed_uri = URI.parse(uri)
  parsed_uri.host = @app.host unless parsed_uri.host
  parsed_uri.port = @app.port unless parsed_uri.port
  parsed_uri.scheme = @app.scheme unless parsed_uri.scheme
  response_hash, messages = await <<~JAVASCRIPT
    ConsoleMessages[#{document.handle}] = [];
    var response = await AllPageHandles[#{document.handle}].goto('#{parsed_uri.to_s}');
    if (response) {
      var request = response.request();
      var formatted_response = {
        headers: response.headers(),
        ok: response.ok(),
        remote_address: response.remoteAddress(),
        request: {
          failure: request.failure(),
          headers: request.headers(),
          method: request.method(),
          post_data: request.postData(),
          resource_type: request.resourceType(),
          url: request.url()
        },
        status: response.status(),
        status_text: response.statusText(),
        text: response.text(),
        url: response.url()
      };
      LastResult = [formatted_response, ConsoleMessages[#{document.handle}]];
    } else {
      LastResult = [null, ConsoleMessages[#{document.handle}]];
    }
  JAVASCRIPT
  con_messages = messages.map {|m| Isomorfeus::Puppetmaster::ConsoleMessage.new(m)}
  con_messages.each { |m| raise determine_error({ 'message' => m.text }) if m.level == 'error' && !m.text.start_with?('Failed to load resource:') }
  if response_hash
    response = Isomorfeus::Puppetmaster::Response.new(response_hash)
    document.instance_variable_set(:@response, response)
  end
  document.response
end

#document_head(document) ⇒ Object



565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 565

def document_head(document)
  node_data = await <<~JAVASCRIPT
    var element_handle = await AllPageHandles[#{document.handle}].$('head');
    if (element_handle) {
      var node_handle = RegisterElementHandle(element_handle);
      var tt = await AllElementHandles[node_handle].executionContext().evaluate((node) => {
        var name = node.nodeName;
        var tag = node.tagName.toLower();
        return [name, tag, null, node.isContentEditable];
      }, AllElementHandles[node_handle]);
      LastResult = {handle: node_handle, name: tt[0], tag: tt[1], type: tt[2], content_editable: tt[3]};
    }
  JAVASCRIPT
  if node_data
    node_data[:css_selector] = selector
    Isomorfeus::Puppetmaster::Node.new_by_tag(self, document, node_data)
  end
end

#document_html(document) ⇒ Object



584
585
586
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 584

def document_html(document)
  await "LastResult = await AllPageHandles[#{document.handle}].content();"
end

#document_open_new_document(_document, uri = nil) ⇒ Object



588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 588

def document_open_new_document(_document, uri = nil)
  if !uri || uri == 'about:blank'
    parsed_uri = 'about:blank'
  else
    parsed_uri = URI.parse(uri)
    parsed_uri.host = @app.host unless parsed_uri.host
    parsed_uri.port = @app.port unless parsed_uri.port
    parsed_uri.scheme = @app.scheme unless parsed_uri.scheme
  end
  handle, response_hash, messages = await <<~JAVASCRIPT
    var new_page = await CurrentBrowser.newPage();
    var url = '#{parsed_uri.to_s}';
    new_page.setDefaultTimeout(#{@puppeteer_timeout});
    await new_page.setViewport({width: #{@width}, height: #{@height}});
    var new_target = new_page.target();
    var cdp_session = await new_target.createCDPSession();
    await cdp_session.send('Page.setDownloadBehavior', {behavior: 'allow', downloadPath: '#{Isomorfeus::Puppetmaster.download_path}'});
    if (#{@url_blacklist}.length > 0) { await cdp_session.send('Network.setBlockedURLs', {urls: #{@url_blacklist}}); }
    await cdp_session.detach();
    var page_handle = RegisterPage(new_page); 
    var result_response = null;
    if (url && url !== '') { 
      var response = await new_page.goto(url);
      if (response) {
        var request = response.request();
        result_response = {
          headers: response.headers(),
          ok: response.ok(),
          remote_address: response.remoteAddress(),
          request: {
            failure: request.failure(),
            headers: request.headers(),
            method: request.method(),
            post_data: request.postData(),
            resource_type: request.resourceType(),
            url: request.url()
          },
          status: response.status(),
          status_text: response.statusText(),
          text: response.text(),
          url: response.url()
        } 
      }
    };
    LastResult = [page_handle, result_response, ConsoleMessages[page_handle]];
  JAVASCRIPT
  con_messages = messages.map {|m| Isomorfeus::Puppetmaster::ConsoleMessage.new(m)}
  con_messages.each { |m| raise determine_error({ 'message' => m.text }) if m.level == 'error' && !m.text.start_with?('Failed to load resource:') }
  Isomorfeus::Puppetmaster::Document.new(self, handle, Isomorfeus::Puppetmaster::Response.new(response_hash))
end

#document_reload(document) ⇒ Object



639
640
641
642
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 639

def document_reload(document)
  response_hash = await"LastResult = await AllPageHandles[#{document.handle}].reload();"
  Isomorfeus::Puppetmaster::Response.new(response_hash)
end


644
645
646
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 644

def document_remove_cookie(document, name)
  await "await AllPageHandles[#{document.handle}].deleteCookie({name: '#{name}'})"
end

#document_render_base64(document, **options) ⇒ Object



648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 648

def document_render_base64(document, **options)
  # todo
  # https://pptr.dev/#?product=Puppeteer&version=v1.12.2&show=api-pagescreenshotoptions
  final_options = ["encoding: 'base64'"]
  if options.key?(:format)
    options[:format] = 'jpeg' if options[:format].to_s.downcase == 'jpg'
    final_options << "type: '#{options.delete(:format).to_s.downcase}'"
  end
  final_options << "quality: #{options.delete(:quality)}" if options.key?(:quality)
  final_options << "fullPage: #{options.delete(:full)}" if options.key?(:full)
  options.each do |k,v|
    final_options << "#{k.to_s.camelize(:lower)}: #{v}"
  end
  await "LastResult = await AllPageHandles[#{document.handle}].screenshot({#{final_options.join(', ')}});"
end

#document_reset_user_agent(document) ⇒ Object



664
665
666
667
668
669
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 664

def document_reset_user_agent(document)
  await <<~JAVASCRIPT
    var original_user_agent = await CurrentBrowser.userAgent();
    await AllPageHandles[#{document.handle}].setUserAgent(original_user_agent);
  JAVASCRIPT
end

#document_right_click(document, x: nil, y: nil, modifiers: nil) ⇒ Object



671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 671

def document_right_click(document, x: nil, y: nil, modifiers: nil)
  # modifier_keys: :alt, :control, :meta, :shift
  # offset: { x: int, y: int }
  modifiers = [modifiers] if modifiers.is_a?(Symbol)
  modifiers = [] unless modifiers
  modifiers = modifiers.map {|key| key.to_s.camelize(:lower) }
  await <<~JAVASCRIPT
    var response_event_occurred = false;
    var response_handler = function(event){ response_event_occurred = true; };
    var response_watcher = new Promise(function(resolve, reject){
      setTimeout(function(){
        if (!response_event_occurred) { resolve(true); } 
        else { setTimeout(function(){ resolve(true); }, #{@puppeteer_timeout}); }
        AllPageHandles[#{document.handle}].removeListener('response', response_handler);
      }, #{@puppeteer_reaction_timeout});
    });
    AllPageHandles[#{document.handle}].on('response', response_handler);
    var navigation_watcher = AllPageHandles[#{document.handle}].waitForNavigation();
    await AllPageHandles[#{document.handle}].evaluate(function(){
      var options = {button: 2, bubbles: true, cancelable: true};
      var node = window;
      var x = #{x ? x : 'null'};
      var y = #{y ? y : 'null'};
      var modifiers = #{modifiers};
      if (x && y) {
        options['clientX'] = x;
        options['clientY'] = y;
        var n = document.elementFromPoint(x, y);
        if (n) { node = n };
      }
      if (modifiers.includes('meta')) { options['metaKey'] = true; }
      if (modifiers.includes('control')) { options['ctrlKey'] = true; }
      if (modifiers.includes('shift')) { options['shiftKey'] = true; }
      if (modifiers.includes('alt')) { options['altKey'] = true; }
      node.dispatchEvent(new MouseEvent('mousedown', options));
      node.dispatchEvent(new MouseEvent('mouseup', options));
      node.dispatchEvent(new MouseEvent('contextmenu', options));
    });
    await Promise.race([response_watcher, navigation_watcher]);
  JAVASCRIPT
end

#document_save_pdf(document, path, **options) ⇒ Object



713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 713

def document_save_pdf(document, path, **options)
  # todo
  # https://pptr.dev/#?product=Puppeteer&version=v1.12.2&show=api-pagepdfoptions
  absolute_path = File.absolute_path(path)
  final_options = ["path: '#{absolute_path}'"]
  final_options << "format: '#{options.delete(:format)}'" if options.key?(:format)
  final_options << "headerTemplate: `#{options.delete(:header_template)}`" if options.key?(:header_template)
  final_options << "footerTemplate: `#{options.delete(:footer_template)}`" if options.key?(:footer_template)
  final_options << "pageRanges: '#{options.delete(:page_ranges)}'" if options.key?(:page_ranges)
  final_options << "width: '#{options.delete(:width)}'" if options.key?(:width)
  final_options << "height: '#{options.delete(:height)}'" if options.key?(:height)
  options.each do |k,v|
    final_options << "#{k.to_s.camelize(:lower)}: #{v}"
  end
  await "await AllPageHandles[#{document.handle}].pdf({#{final_options.join(', ')}});"
end

#document_save_screenshot(document, path, **options) ⇒ Object



730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 730

def document_save_screenshot(document, path, **options)
  # todo
  # https://pptr.dev/#?product=Puppeteer&version=v1.12.2&show=api-pagescreenshotoptions
  absolute_path = File.absolute_path(path)
  final_options = ["path: '#{absolute_path}'"]
  if options.key?(:format)
    options[:format] = 'jpeg' if options[:format].to_s.downcase == 'jpg'
    final_options << "type: '#{options.delete(:format).to_s.downcase}'"
  end
  final_options << "quality: #{options.delete(:quality)}" if options.key?(:quality)
  final_options << "fullPage: #{options.delete(:full)}" if options.key?(:full)
  options.each do |k,v|
    final_options << "#{k.to_s.camelize(:lower)}: #{v}"
  end
  await "await AllPageHandles[#{document.handle}].screenshot({#{final_options.join(', ')}});"
end

#document_scroll_by(document, x, y) ⇒ Object



747
748
749
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 747

def document_scroll_by(document, x, y)
  await "await AllPageHandles[#{document.handle}].evaluate('window.scrollBy(#{x}, #{y})');"
end

#document_scroll_to(document, x, y) ⇒ Object



751
752
753
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 751

def document_scroll_to(document, x, y)
  await "await AllPageHandles[#{document.handle}].evaluate('window.scrollTo(#{x}, #{y})');"
end

#document_set_authentication_credentials(document, username, password) ⇒ Object



755
756
757
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 755

def document_set_authentication_credentials(document, username, password)
  await "await AllPageHandles[#{document.handle}].authenticate({username: '#{username}', password: '#{password}'});"
end


759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 759

def document_set_cookie(document, name, value, **options)
  options[:name]  ||= name
  options[:value] ||= value
  uri = document_url(document)
  if uri == 'about:blank'
    uri = if Isomorfeus::Puppetmaster.server_host
            u = URI.new
            u.scheme = Isomorfeus::Puppetmaster.server_scheme if Isomorfeus::Puppetmaster.server_scheme
            u.host = Isomorfeus::Puppetmaster.server_host
            u.to_s
          else
            'http://127.0.0.1'
          end
  end
  options[:domain] ||= URI.parse(uri).host
  final_options = []
  final_options << "expires: #{options.delete(:expires).to_i}" if options.key?(:expires)
  final_options << "httpOnly: #{options.delete(:http_only)}" if options.key?(:http_only)
  final_options << "secure: #{options.delete(:secure)}" if options.key?(:secure)
  final_options << "sameSite: '#{options.delete(:same_site)}'" if options.key?(:same_site)
  options.each do |k,v|
    final_options << "#{k}: '#{v}'"
  end
  await "await AllPageHandles[#{document.handle}].setCookie({#{final_options.join(', ')}});"
end

#document_set_extra_headers(document, headers_hash) ⇒ Object



785
786
787
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 785

def document_set_extra_headers(document, headers_hash)
  await "await AllPageHandles[#{document.handle}].setExtraHTTPHeaders(#{Oj.dump(headers_hash, mode: :strict)});"
end

#document_set_url_blacklist(document, url_array) ⇒ Object



789
790
791
792
793
794
795
796
797
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 789

def document_set_url_blacklist(document, url_array)
  # https://www.chromium.org/administrators/url-blacklist-filter-format
  @url_blacklist = url_array
  await <<~JAVASCRIPT
    var cdp_session = await AllPageHandles[#{document.handle}].target().createCDPSession();
    await cdp_session.send('Network.setBlockedURLs', {urls: #{url_array}});
    await cdp_session.detach();
  JAVASCRIPT
end

#document_set_user_agent(document, agent_string) ⇒ Object



799
800
801
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 799

def document_set_user_agent(document, agent_string)
  await "await AllPageHandles[#{document.handle}].setUserAgent('#{agent_string}');"
end

#document_title(document) ⇒ Object



803
804
805
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 803

def document_title(document)
  await "LastResult = await AllPageHandles[#{document.handle}].title();"
end

#document_type_keys(document, *keys) ⇒ Object



807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 807

def document_type_keys(document, *keys)
  cjs = "await AllPageHandles[#{document.handle}].bringToFront();"
  top_modifiers = []
  keys.each do |key|
    if key.is_a?(String)
      key.each_char do |c|
        need_shift = /[[:upper:]]/.match(c)
        cjs << "await AllPageHandles[#{document.handle}].keyboard.down('Shift');\n" if need_shift
        c = "Key#{c.upcase}" if /[[:alpha:]]/.match(c)
        cjs << "await AllPageHandles[#{document.handle}].keyboard.down('#{c}');\n"
        cjs << "await AllPageHandles[#{document.handle}].keyboard.up('#{c}');\n"
        cjs << "await AllPageHandles[#{document.handle}].keyboard.up('Shift');\n" if need_shift
      end
    elsif key.is_a?(Symbol)
      if %i[ctrl Ctrl].include?(key)
        key = :control
      elsif  %i[command Command Meta].include?(key)
        key = :meta
      elsif  %i[divide Divide].include?(key)
        key = :numpad_divide
      elsif  %i[decimal Decimal].include?(key)
        key = :numpad_decimal
      elsif %i[left right up down].include?(key)
        key = "arrow_#{key}".to_sym
      end
      if %i[alt alt_left alt_right control control_left control_rigth meta meta_left meta_right shift shift_left shift_right].include?(key)
        top_modifiers << key
        cjs << "await AllPageHandles[#{document.handle}].keyboard.down('#{key.to_s.camelize}');\n"
      else
        cjs << "await AllPageHandles[#{document.handle}].keyboard.press('#{key.to_s.camelize}');\n"
      end
    elsif key.is_a?(Array)
      modifiers = []
      key.each do |k|
        if k.is_a?(Symbol)
          if %i[ctrl Ctrl].include?(k)
            k = :control
          elsif  %i[command Command Meta].include?(k)
            k = :meta
          elsif  %i[divide Divide].include?(k)
            k = :numpad_divide
          elsif  %i[decimal Decimal].include?(k)
            k = :numpad_decimal
          elsif %i[left right up down].include?(key)
            k = "arrow_#{key}".to_sym
          end
          if %i[alt alt_left alt_right control control_left control_rigth meta meta_left meta_right shift shift_left shift_right].include?(k)
            modifiers << k
            cjs << "await AllPageHandles[#{document.handle}].keyboard.down('#{k.to_s.camelize}');\n"
          else
            cjs << "await AllPageHandles[#{document.handle}].keyboard.press('#{k.to_s.camelize}');\n"
          end
        elsif k.is_a?(String)
          k.each_char do |c|
            need_shift = /[[:upper:]]/.match(c)
            cjs << "await AllPageHandles[#{document.handle}].keyboard.down('Shift');\n" if need_shift
            c = "Key#{c.upcase}" if /[[:alpha:]]/.match(c)
            cjs << "await AllPageHandles[#{document.handle}].keyboard.press('#{c}');\n"
            cjs << "await AllPageHandles[#{document.handle}].keyboard.up('Shift');\n" if need_shift
          end
        end
      end
      modifiers.reverse.each do |k|
        cjs << "await AllPageHandles[#{document.handle}].keyboard.up('#{k.to_s.camelize}');\n"
      end
    end
  end
  top_modifiers.reverse.each do |key|
    cjs << "await AllPageHandles[#{document.handle}].keyboard.up('#{key.to_s.camelize}');\n"
  end
  await(cjs)
end

#document_url(document) ⇒ Object



880
881
882
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 880

def document_url(document)
  await "LastResult = await AllPageHandles[#{document.handle}].evaluate('window.location.href');"
end

#document_user_agent(document) ⇒ Object



884
885
886
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 884

def document_user_agent(document)
  await "LastResult = await AllPageHandles[#{document.handle}].evaluate('window.navigator.userAgent');"
end

#document_viewport_maximize(document) ⇒ Object



888
889
890
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 888

def document_viewport_maximize(document)
  document_viewport_resize(document, @max_width, @max_height)
end

#document_viewport_resize(document, width, height) ⇒ Object



892
893
894
895
896
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 892

def document_viewport_resize(document, width, height)
  width = @max_width if width > @max_width
  height = @max_height if width > @max_height
  await "await AllPageHandles[#{document.handle}].setViewport({width: #{width}, height: #{height}});"
end

#document_viewport_size(document) ⇒ Object



898
899
900
901
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 898

def document_viewport_size(document)
  viewport = @context.eval "AllPageHandles[#{document.handle}].viewport()"
  [viewport['width'], viewport['height']]
end

#document_wait_for(document, selector) ⇒ Object



903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 903

def document_wait_for(document, selector)
  js_escaped_selector = selector.gsub('\\', '\\\\\\').gsub('"', '\"')
  node_data = await <<~JAVASCRIPT
    var element_handle = await AllPageHandles[#{document.handle}].waitForSelector("#{js_escaped_selector}");
    if (element_handle) {
      var node_handle = RegisterElementHandle(element_handle);
      var tt = await AllElementHandles[node_handle].executionContext().evaluate((node) => {
        var name = node.nodeName;
        var tag = node.tagName.toLowerCase();
        var type = null;
        if (tag === 'input') { type = node.getAttribute('type'); }
        return [name, tag, type, node.isContentEditable];
      }, AllElementHandles[node_handle]);
      LastResult = {handle: node_handle, name: tt[0], tag: tt[1], type: tt[2], content_editable: tt[3]};
    }
  JAVASCRIPT
  if node_data
    node_data[:css_selector] = selector
    Isomorfeus::Puppetmaster::Node.new_by_tag(self, document, node_data)
  else
    raise Isomorfeus::Puppetmaster::ElementNotFound.new(selector)
  end
end

#document_wait_for_xpath(document, query) ⇒ Object



927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
# File 'lib/isomorfeus/puppetmaster/driver/puppeteer_document.rb', line 927

def document_wait_for_xpath(document, query)
  js_escaped_query = query.gsub('\\', '\\\\\\').gsub('"', '\"')
  node_data = await <<~JAVASCRIPT
    var element_handle = await AllPageHandles[#{document.handle}].waitForXPath("#{js_escaped_query}");
    if (element_handle) {
      var node_handle = RegisterElementHandle(element_handle);
      var tt = await AllElementHandles[node_handle].executionContext().evaluate((node) => {
        var name = node.nodeName;
        var tag = node.tagName.toLowerCase();
        var type = null;
        if (tag === 'input') { type = node.getAttribute('type'); }
        return [name, tag, type, node.isContentEditable];
      }, AllElementHandles[node_handle]);
      LastResult = {handle: node_handle, name: tt[0], tag: tt[1], type: tt[2], content_editable: tt[3]};
    }
  JAVASCRIPT
  if node_data
    node_data[:xpath_query] = query
    Isomorfeus::Puppetmaster::Node.new_by_tag(self, document, node_data)
  else
    raise Isomorfeus::Puppetmaster::ElementNotFound.new(selector)
  end
end