/
page.rb
1284 lines (1096 loc) · 39.6 KB
/
page.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
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
398
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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
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
486
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
523
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
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
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'base64'
require 'json'
require "stringio"
require_relative './page/metrics'
require_relative './page/pdf_options'
require_relative './page/screenshot_options'
require_relative './page/screenshot_task_queue'
class Puppeteer::Page
include Puppeteer::DebugPrint
include Puppeteer::EventCallbackable
include Puppeteer::IfPresent
using Puppeteer::DefineAsyncMethod
# @param {!Puppeteer.CDPSession} client
# @param {!Puppeteer.Target} target
# @param {boolean} ignoreHTTPSErrors
# @param {?Puppeteer.Viewport} defaultViewport
# @return {!Promise<!Page>}
def self.create(client, target, ignore_https_errors, default_viewport)
page = Puppeteer::Page.new(client, target, ignore_https_errors)
page.init
if default_viewport
page.viewport = default_viewport
end
page
end
# @param {!Puppeteer.CDPSession} client
# @param {!Puppeteer.Target} target
# @param {boolean} ignoreHTTPSErrors
def initialize(client, target, ignore_https_errors)
@closed = false
@client = client
@target = target
@keyboard = Puppeteer::Keyboard.new(client)
@mouse = Puppeteer::Mouse.new(client, @keyboard)
@timeout_settings = Puppeteer::TimeoutSettings.new
@touchscreen = Puppeteer::TouchScreen.new(client, @keyboard)
# @accessibility = Accessibility.new(client)
@frame_manager = Puppeteer::FrameManager.new(client, self, ignore_https_errors, @timeout_settings)
@emulation_manager = Puppeteer::EmulationManager.new(client)
@tracing = Puppeteer::Tracing.new(client)
@page_bindings = {}
@coverage = Puppeteer::Coverage.new(client)
@javascript_enabled = true
@screenshot_task_queue = ScreenshotTaskQueue.new
@workers = {}
@user_drag_interception_enabled = false
@client.add_event_listener('Target.attachedToTarget') do |event|
if event['targetInfo']['type'] != 'worker' && event['targetInfo']['type'] != 'iframe'
# If we don't detach from service workers, they will never die.
# We still want to attach to workers for emitting events.
# We still want to attach to iframes so sessions may interact with them.
# We detach from all other types out of an abundance of caution.
# See https://source.chromium.org/chromium/chromium/src/+/main:content/browser/devtools/devtools_agent_host_impl.cc?ss=chromium&q=f:devtools%20-f:out%20%22::kTypePage%5B%5D%22
# for the complete list of available types.
@client.async_send_message('Target.detachFromTarget', sessionId: event['sessionId'])
next
end
if event['targetInfo']['type'] == 'worker'
session = Puppeteer::Connection.from_session(@client).session(event['sessionId']) # rubocop:disable Lint/UselessAssignment
# const worker = new Worker(session, event.targetInfo.url, this._addConsoleMessage.bind(this), this._handleException.bind(this));
# this._workers.set(event.sessionId, worker);
# this.emit(PageEmittedEvents::WorkerCreated, worker);
end
end
@client.add_event_listener('Target.detachedFromTarget') do |event|
session_id = event['sessionId']
worker = @workers[session_id]
next unless worker
emit_event(PageEmittedEvents::WorkerDestroyed, worker)
@workers.delete(session_id)
end
@frame_manager.on_event(FrameManagerEmittedEvents::FrameAttached) do |event|
emit_event(PageEmittedEvents::FrameAttached, event)
end
@frame_manager.on_event(FrameManagerEmittedEvents::FrameDetached) do |event|
emit_event(PageEmittedEvents::FrameDetached, event)
end
@frame_manager.on_event(FrameManagerEmittedEvents::FrameNavigated) do |event|
emit_event(PageEmittedEvents::FrameNavigated, event)
end
network_manager = @frame_manager.network_manager
network_manager.on_event(NetworkManagerEmittedEvents::Request) do |event|
emit_event(PageEmittedEvents::Request, event)
end
network_manager.on_event(NetworkManagerEmittedEvents::Response) do |event|
emit_event(PageEmittedEvents::Response, event)
end
network_manager.on_event(NetworkManagerEmittedEvents::RequestFailed) do |event|
emit_event(PageEmittedEvents::RequestFailed, event)
end
network_manager.on_event(NetworkManagerEmittedEvents::RequestFinished) do |event|
emit_event(PageEmittedEvents::RequestFinished, event)
end
@file_chooser_interception_is_disabled = false
@file_chooser_interceptors = Set.new
@client.on_event('Page.domContentEventFired') do |event|
emit_event(PageEmittedEvents::DOMContentLoaded)
end
@client.on_event('Page.loadEventFired') do |event|
emit_event(PageEmittedEvents::Load)
end
@client.add_event_listener('Runtime.consoleAPICalled') do |event|
handle_console_api(event)
end
@client.add_event_listener('Runtime.bindingCalled') do |event|
handle_binding_called(event)
end
@client.on_event('Page.javascriptDialogOpening') do |event|
handle_dialog_opening(event)
end
@client.on_event('Runtime.exceptionThrown') do |exception|
handle_exception(exception['exceptionDetails'])
end
@client.on_event('Inspector.targetCrashed') do |event|
handle_target_crashed
end
@client.on_event('Performance.metrics') do |event|
emit_event(PageEmittedEvents::Metrics, MetricsEvent.new(event))
end
@client.on_event('Log.entryAdded') do |event|
handle_log_entry_added(event)
end
@client.on_event('Page.fileChooserOpened') do |event|
handle_file_chooser(event)
end
@target.is_closed_promise.then do
emit_event(PageEmittedEvents::Close)
@closed = true
end
end
def init
await_all(
@frame_manager.async_init,
@client.async_send_message('Target.setAutoAttach', autoAttach: true, waitForDebuggerOnStart: false, flatten: true),
@client.async_send_message('Performance.enable'),
@client.async_send_message('Log.enable'),
)
end
def drag_interception_enabled?
@user_drag_interception_enabled
end
alias_method :drag_interception_enabled, :drag_interception_enabled?
# @param event_name [Symbol]
def on(event_name, &block)
unless PageEmittedEvents.values.include?(event_name.to_s)
raise ArgumentError.new("Unknown event name: #{event_name}. Known events are #{PageEmittedEvents.values.to_a.join(", ")}")
end
if event_name.to_s == 'request'
super('request') do |req|
req.enqueue_intercept_action(-> { block.call(req) })
end
end
super(event_name.to_s, &block)
end
# @param event_name [Symbol]
def once(event_name, &block)
unless PageEmittedEvents.values.include?(event_name.to_s)
raise ArgumentError.new("Unknown event name: #{event_name}. Known events are #{PageEmittedEvents.values.to_a.join(", ")}")
end
super(event_name.to_s, &block)
end
def handle_file_chooser(event)
return if @file_chooser_interceptors.empty?
frame = @frame_manager.frame(event['frameId'])
context = frame.execution_context
element = context.adopt_backend_node_id(event['backendNodeId'])
interceptors = @file_chooser_interceptors.to_a
@file_chooser_interceptors.clear
file_chooser = Puppeteer::FileChooser.new(element, event)
interceptors.each do |promise|
promise.fulfill(file_chooser)
end
end
class FileChooserTimeoutError < StandardError
def initialize(timeout:)
super("waiting for filechooser failed: timeout #{timeout}ms exceeded")
end
end
# @param timeout [Integer]
# @return [Puppeteer::FileChooser]
def wait_for_file_chooser(timeout: nil)
if @file_chooser_interceptors.empty?
@client.send_message('Page.setInterceptFileChooserDialog', enabled: true)
end
option_timeout = timeout || @timeout_settings.timeout
promise = resolvable_future
@file_chooser_interceptors << promise
begin
Timeout.timeout(option_timeout / 1000.0) do
promise.value!
end
rescue Timeout::Error
raise FileChooserTimeoutError.new(timeout: option_timeout)
ensure
@file_chooser_interceptors.delete(promise)
end
end
define_async_method :async_wait_for_file_chooser
# @param [Puppeteer::Geolocation]
def geolocation=(geolocation)
@client.send_message('Emulation.setGeolocationOverride', geolocation.to_h)
end
attr_reader :javascript_enabled, :target, :client
alias_method :javascript_enabled?, :javascript_enabled
def browser
@target.browser
end
def browser_context
@target.browser_context
end
class TargetCrashedError < StandardError; end
private def handle_target_crashed
emit_event(PageEmittedEvents::Error, TargetCrashedError.new('Page crashed!'))
end
private def handle_log_entry_added(event)
entry = event['entry']
level = entry['level']
text = entry['text']
source = entry['source']
url = entry['url']
line_number = entry['lineNumber']
if_present(entry['args']) do |args|
args.map do |arg|
Puppeteer::RemoteObject.new(arg).async_release(@client)
end
end
if source != 'worker'
console_message_location = Puppeteer::ConsoleMessage::Location.new(
url: url,
line_number: line_number,
)
emit_event(PageEmittedEvents::Console,
Puppeteer::ConsoleMessage.new(level, text, [], console_message_location))
end
end
def main_frame
@frame_manager.main_frame
end
attr_reader :touch_screen, :coverage, :tracing, :accessibility
def keyboard(&block)
@keyboard.instance_eval(&block) unless block.nil?
@keyboard
end
def frames
@frame_manager.frames
end
def workers
@workers.values
end
# @param value [Bool]
def request_interception=(value)
@frame_manager.network_manager.request_interception = value
end
def drag_interception_enabled=(enabled)
@user_drag_interception_enabled = enabled
@client.send_message('Input.setInterceptDrags', enabled: enabled)
end
def offline_mode=(enabled)
@frame_manager.network_manager.offline_mode = enabled
end
# @param network_condition [Puppeteer::NetworkCondition|nil]
def emulate_network_conditions(network_condition)
@frame_manager.network_manager.emulate_network_conditions(network_condition)
end
# @param {number} timeout
def default_navigation_timeout=(timeout)
@timeout_settings.default_navigation_timeout = timeout
end
# @param {number} timeout
def default_timeout=(timeout)
@timeout_settings.default_timeout = timeout
end
# `$()` in JavaScript.
# @param {string} selector
# @return {!Promise<?Puppeteer.ElementHandle>}
def query_selector(selector)
main_frame.query_selector(selector)
end
alias_method :S, :query_selector
define_async_method :async_query_selector
# `$$()` in JavaScript.
# @param {string} selector
# @return {!Promise<!Array<!Puppeteer.ElementHandle>>}
def query_selector_all(selector)
main_frame.query_selector_all(selector)
end
alias_method :SS, :query_selector_all
define_async_method :async_query_selector_all
# @param {Function|string} pageFunction
# @param {!Array<*>} args
# @return {!Promise<!Puppeteer.JSHandle>}
def evaluate_handle(page_function, *args)
context = main_frame.execution_context
context.evaluate_handle(page_function, *args)
end
define_async_method :async_evaluate_handle
# @param {!Puppeteer.JSHandle} prototypeHandle
# @return {!Promise<!Puppeteer.JSHandle>}
def query_objects(prototype_handle)
context = main_frame.execution_context
context.query_objects(prototype_handle)
end
# `$eval()` in JavaScript.
# @param selector [String]
# @param page_function [String]
# @return [Object]
def eval_on_selector(selector, page_function, *args)
main_frame.eval_on_selector(selector, page_function, *args)
end
alias_method :Seval, :eval_on_selector
define_async_method :async_eval_on_selector
# `$$eval()` in JavaScript.
# @param selector [String]
# @param page_function [String]
# @return [Object]
def eval_on_selector_all(selector, page_function, *args)
main_frame.eval_on_selector_all(selector, page_function, *args)
end
alias_method :SSeval, :eval_on_selector_all
define_async_method :async_eval_on_selector_all
# `$x()` in JavaScript. $ is not allowed to use as a method name in Ruby.
# @param {string} expression
# @return {!Promise<!Array<!Puppeteer.ElementHandle>>}
def Sx(expression)
main_frame.Sx(expression)
end
define_async_method :async_Sx
# @return [Array<Hash>]
def cookies(*urls)
@client.send_message('Network.getCookies', urls: (urls.empty? ? [url] : urls))['cookies']
end
# check if each cookie element has required fields ('name' and 'value')
private def assert_cookie_params(cookies, requires:)
return if cookies.all? do |cookie|
requires.all? { |field_name| cookie[field_name] || cookie[field_name.to_s] }
end
raise ArgumentError.new("Each coookie must have #{requires.join(" and ")} attribute.")
end
def delete_cookie(*cookies)
assert_cookie_params(cookies, requires: %i(name))
page_url = url
starts_with_http = page_url.start_with?("http")
cookies.each do |cookie|
item = (starts_with_http ? { url: page_url } : {}).merge(cookie)
@client.send_message("Network.deleteCookies", item)
end
end
def set_cookie(*cookies)
assert_cookie_params(cookies, requires: %i(name value))
page_url = url
starts_with_http = page_url.start_with?("http")
items = cookies.map do |cookie|
(starts_with_http ? { url: page_url } : {}).merge(cookie).tap do |item|
raise ArgumentError.new("Blank page can not have cookie \"#{item[:name]}\"") if item[:url] == "about:blank"
raise ArgumentError.new("Data URL page can not have cookie \"#{item[:name]}\"") if item[:url]&.start_with?("data:")
end
end
delete_cookie(*items)
unless items.empty?
@client.send_message("Network.setCookies", cookies: items)
end
end
# @param url [String?]
# @param path [String?]
# @param content [String?]
# @param type [String?]
# @param id [String?]
def add_script_tag(url: nil, path: nil, content: nil, type: nil, id: nil)
main_frame.add_script_tag(url: url, path: path, content: content, type: type, id: id)
end
# @param url [String?]
# @param path [String?]
# @param content [String?]
def add_style_tag(url: nil, path: nil, content: nil)
main_frame.add_style_tag(url: url, path: path, content: content)
end
# @param name [String]
# @param puppeteer_function [Proc]
def expose_function(name, puppeteer_function)
if @page_bindings[name]
raise ArgumentError.new("Failed to add page binding with name `#{name}` already exists!")
end
@page_bindings[name] = puppeteer_function
add_page_binding = <<~JAVASCRIPT
function (type, bindingName) {
/* Cast window to any here as we're about to add properties to it
* via win[bindingName] which TypeScript doesn't like.
*/
const win = window;
const binding = win[bindingName];
win[bindingName] = (...args) => {
const me = window[bindingName];
let callbacks = me.callbacks;
if (!callbacks) {
callbacks = new Map();
me.callbacks = callbacks;
}
const seq = (me.lastSeq || 0) + 1;
me.lastSeq = seq;
const promise = new Promise((resolve, reject) =>
callbacks.set(seq, { resolve, reject })
);
binding(JSON.stringify({ type, name: bindingName, seq, args }));
return promise;
};
}
JAVASCRIPT
source = JavaScriptFunction.new(add_page_binding, ['exposedFun', name]).source
@client.send_message('Runtime.addBinding', name: name)
@client.send_message('Page.addScriptToEvaluateOnNewDocument', source: source)
promises = @frame_manager.frames.map do |frame|
frame.async_evaluate("() => #{source}")
end
await_all(*promises)
nil
end
# @param username [String?]
# @param password [String?]
def authenticate(username: nil, password: nil)
@frame_manager.network_manager.authenticate(username: username, password: password)
end
# @param headers [Hash]
def extra_http_headers=(headers)
@frame_manager.network_manager.extra_http_headers = headers
end
# @param user_agent [String]
# @param user_agent_metadata [Hash]
def set_user_agent(user_agent, user_agent_metadata = nil)
@frame_manager.network_manager.set_user_agent(user_agent, user_agent_metadata)
end
alias_method :user_agent=, :set_user_agent
def metrics
response = @client.send_message('Performance.getMetrics')
Metrics.new(response['metrics'])
end
class PageError < StandardError ; end
private def handle_exception(exception_details)
message = Puppeteer::ExceptionDetails.new(exception_details).message
err = PageError.new(message)
# err.stack = ''; // Don't report clientside error with a node stack attached
emit_event(PageEmittedEvents::PageError, err)
end
private def handle_console_api(event)
if event['executionContextId'] == 0
# DevTools protocol stores the last 1000 console messages. These
# messages are always reported even for removed execution contexts. In
# this case, they are marked with executionContextId = 0 and are
# reported upon enabling Runtime agent.
#
# Ignore these messages since:
# - there's no execution context we can use to operate with message
# arguments
# - these messages are reported before Puppeteer clients can subscribe
# to the 'console'
# page event.
#
# @see https://github.com/puppeteer/puppeteer/issues/3865
return
end
context = @frame_manager.execution_context_by_id(event['executionContextId'], @client)
values = event['args'].map do |arg|
remote_object = Puppeteer::RemoteObject.new(arg)
Puppeteer::JSHandle.create(context: context, remote_object: remote_object)
end
add_console_message(event['type'], values, event['stackTrace'])
end
def handle_binding_called(event)
execution_context_id = event['executionContextId']
payload =
begin
JSON.parse(event['payload'])
rescue
# The binding was either called by something in the page or it was
# called before our wrapper was initialized.
return
end
name = payload['name']
seq = payload['seq']
args = payload['args']
if payload['type'] != 'exposedFun' || !@page_bindings[name]
return
end
expression =
begin
result = @page_bindings[name].call(*args)
deliver_result = <<~JAVASCRIPT
function (name, seq, result) {
window[name].callbacks.get(seq).resolve(result);
window[name].callbacks.delete(seq);
}
JAVASCRIPT
JavaScriptFunction.new(deliver_result, [name, seq, result]).source
rescue => err
deliver_error = <<~JAVASCRIPT
function (name, seq, message) {
const error = new Error(message);
window[name].callbacks.get(seq).reject(error);
window[name].callbacks.delete(seq);
}
JAVASCRIPT
JavaScriptFunction.new(deliver_error, [name, seq, err.message]).source
end
@client.async_send_message('Runtime.evaluate', expression: expression, contextId: execution_context_id).rescue do |error|
debug_puts(error)
end
end
private def add_console_message(type, args, stack_trace)
text_tokens = args.map { |arg| arg.remote_object.value }
stack_trace_locations =
if stack_trace && stack_trace['callFrames']
stack_trace['callFrames'].map do |call_frame|
Puppeteer::ConsoleMessage::Location.new(
url: call_frame['url'],
line_number: call_frame['lineNumber'],
column_number: call_frame['columnNumber'],
)
end
else
[]
end
console_message = Puppeteer::ConsoleMessage.new(type, text_tokens.join(' '), args, stack_trace_locations)
emit_event(PageEmittedEvents::Console, console_message)
end
private def handle_dialog_opening(event)
dialog_type = event['type']
unless %w(alert confirm prompt beforeunload).include?(dialog_type)
raise ArgumentError.new("Unknown javascript dialog type: #{dialog_type}")
end
dialog = Puppeteer::Dialog.new(@client,
type: dialog_type,
message: event['message'],
default_value: event['defaultPrompt'])
emit_event(PageEmittedEvents::Dialog, dialog)
end
private def set_transparent_background_color(&block)
@client.send_message(
'Emulation.setDefaultBackgroundColorOverride',
color: { r: 0, g: 0, b: 0, a: 0 })
end
private def reset_default_background_color(&block)
@client.send_message('Emulation.setDefaultBackgroundColorOverride')
end
# @return [String]
def url
main_frame.url
end
# @return [String]
def content
main_frame.content
end
# @param html [String]
# @param timeout [Integer]
# @param wait_until [String|Array<String>]
def set_content(html, timeout: nil, wait_until: nil)
main_frame.set_content(html, timeout: timeout, wait_until: wait_until)
end
# @param html [String]
def content=(html)
main_frame.set_content(html)
end
# @param url [String]
# @param rederer [String]
# @param timeout [number|nil]
# @param wait_until [string|nil] 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2'
def goto(url, referer: nil, timeout: nil, wait_until: nil)
main_frame.goto(url, referer: referer, timeout: timeout, wait_until: wait_until)
end
# @param timeout [number|nil]
# @param wait_until [string|nil] 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2'
# @return [Puppeteer::HTTPResponse]
def reload(timeout: nil, wait_until: nil)
wait_for_navigation(timeout: timeout, wait_until: wait_until) do
@client.send_message('Page.reload')
end
end
def wait_for_navigation(timeout: nil, wait_until: nil)
main_frame.send(:wait_for_navigation, timeout: timeout, wait_until: wait_until)
end
# @!method async_wait_for_navigation(timeout: nil, wait_until: nil)
#
# @param timeout [number|nil]
# @param wait_until [string|nil] 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2'
define_async_method :async_wait_for_navigation
private def wait_for_network_manager_event(event_name, predicate:, timeout:)
option_timeout = timeout || @timeout_settings.timeout
promise = resolvable_future
listener_id = @frame_manager.network_manager.add_event_listener(event_name) do |event_target|
if predicate.call(event_target)
promise.fulfill(event_target)
end
end
begin
# Timeout.timeout(0) means "no limit" for timeout.
Timeout.timeout(option_timeout / 1000.0) do
await_any(promise, session_close_promise)
end
rescue Timeout::Error
raise Puppeteer::TimeoutError.new("waiting for #{event_name} failed: timeout #{option_timeout}ms exceeded")
ensure
@frame_manager.network_manager.remove_event_listener(listener_id)
end
end
private def wait_for_frame_manager_event(*event_names, predicate:, timeout:)
option_timeout = timeout || @timeout_settings.timeout
promise = resolvable_future
listener_ids = event_names.map do |event_name|
@frame_manager.add_event_listener(event_name) do |event_target|
if predicate.call(event_target)
promise.fulfill(event_target) unless promise.resolved?
end
end
end
begin
# Timeout.timeout(0) means "no limit" for timeout.
Timeout.timeout(option_timeout / 1000.0) do
await_any(promise, session_close_promise)
end
rescue Timeout::Error
raise Puppeteer::TimeoutError.new("waiting for #{event_names.join(" or ")} failed: timeout #{option_timeout}ms exceeded")
ensure
listener_ids.each do |listener_id|
@frame_manager.remove_event_listener(listener_id)
end
end
end
private def session_close_promise
@disconnect_promise ||= resolvable_future do |future|
@client.observe_first(CDPSessionEmittedEvents::Disconnected) do
future.reject(Puppeteer::CDPSession::Error.new('Target Closed'))
end
end
end
def wait_for_request(url: nil, predicate: nil, timeout: nil)
if !url && !predicate
raise ArgumentError.new('url or predicate must be specified')
end
if predicate && !predicate.is_a?(Proc)
raise ArgumentError.new('predicate must be a proc.')
end
request_predicate =
if url
-> (request) { request.url == url }
else
predicate
end
wait_for_network_manager_event(NetworkManagerEmittedEvents::Request,
predicate: request_predicate,
timeout: timeout,
)
end
# @!method async_wait_for_request(url: nil, predicate: nil, timeout: nil)
#
# Waits until request URL matches or request matches the given predicate.
#
# Waits until request URL matches
# wait_for_request(url: 'https://example.com/awesome')
#
# Waits until request matches the given predicate
# wait_for_request(predicate: -> (req){ req.url.start_with?('https://example.com/search') })
#
# @param url [String]
# @param predicate [Proc(Puppeteer::HTTPRequest -> Boolean)]
define_async_method :async_wait_for_request
def wait_for_response(url: nil, predicate: nil, timeout: nil)
if !url && !predicate
raise ArgumentError.new('url or predicate must be specified')
end
if predicate && !predicate.is_a?(Proc)
raise ArgumentError.new('predicate must be a proc.')
end
response_predicate =
if url
-> (response) { response.url == url }
else
predicate
end
wait_for_network_manager_event(NetworkManagerEmittedEvents::Response,
predicate: response_predicate,
timeout: timeout,
)
end
# @!method async_wait_for_response(url: nil, predicate: nil, timeout: nil)
#
# @param url [String]
# @param predicate [Proc(Puppeteer::HTTPRequest -> Boolean)]
define_async_method :async_wait_for_response
def wait_for_frame(url: nil, predicate: nil, timeout: nil)
if !url && !predicate
raise ArgumentError.new('url or predicate must be specified')
end
if predicate && !predicate.is_a?(Proc)
raise ArgumentError.new('predicate must be a proc.')
end
frame_predicate =
if url
-> (frame) { frame.url == url }
else
predicate
end
frames.each do |frame|
return frame if frame_predicate.call(frame)
end
wait_for_frame_manager_event(
FrameManagerEmittedEvents::FrameAttached,
FrameManagerEmittedEvents::FrameNavigated,
predicate: frame_predicate,
timeout: timeout,
)
end
# @!method async_wait_for_frame(url: nil, predicate: nil, timeout: nil)
#
# @param url [String]
# @param predicate [Proc(Puppeteer::Frame -> Boolean)]
define_async_method :async_wait_for_frame
# @param timeout [number|nil]
# @param wait_until [string|nil] 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2'
def go_back(timeout: nil, wait_until: nil)
go(-1, timeout: timeout, wait_until: wait_until)
end
# @param timeout [number|nil]
# @param wait_until [string|nil] 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2'
def go_forward(timeout: nil, wait_until: nil)
go(+1, timeout: timeout, wait_until: wait_until)
end
private def go(delta, timeout: nil, wait_until: nil)
history = @client.send_message('Page.getNavigationHistory')
entries = history['entries']
index = history['currentIndex'] + delta
if_present(entries[index]) do |entry|
wait_for_navigation(timeout: timeout, wait_until: wait_until) do
@client.send_message('Page.navigateToHistoryEntry', entryId: entry['id'])
end
end
end
# Brings page to front (activates tab).
def bring_to_front
@client.send_message('Page.bringToFront')
end
# @param device [Device]
def emulate(device)
self.viewport = device.viewport
self.user_agent = device.user_agent
end
# @param {boolean} enabled
def javascript_enabled=(enabled)
return if @javascript_enabled == enabled
@javascript_enabled = enabled
@client.send_message('Emulation.setScriptExecutionDisabled', value: !enabled)
end
# @param enabled [Boolean]
def bypass_csp=(enabled)
@client.send_message('Page.setBypassCSP', enabled: enabled)
end
# @param media_type [String|Symbol|nil] either of (media, print, nil)
def emulate_media_type(media_type)
media_type_str = media_type.to_s
unless ['screen', 'print', ''].include?(media_type_str)
raise ArgumentError.new("Unsupported media type: #{media_type}")
end
@client.send_message('Emulation.setEmulatedMedia', media: media_type_str)
end
# @param factor [Number|nil] Factor at which the CPU will be throttled (2x, 2.5x. 3x, ...). Passing `nil` disables cpu throttling.
def emulate_cpu_throttling(factor)
if factor.nil? || factor >= 1
@client.send_message('Emulation.setCPUThrottlingRate', rate: factor || 1)
else
raise ArgumentError.new('Throttling rate should be greater or equal to 1')
end
end
# @param features [Array]
def emulate_media_features(features)
if features.nil?
@client.send_message('Emulation.setEmulatedMedia', features: nil)
elsif features.is_a?(Array)
features.each do |media_feature|
name = media_feature[:name]
unless /^(?:prefers-(?:color-scheme|reduced-motion)|color-gamut)$/.match?(name)
raise ArgumentError.new("Unsupported media feature: #{name}")
end
end
@client.send_message('Emulation.setEmulatedMedia', features: features)
end
end
# @param timezone_id [String?]
def emulate_timezone(timezone_id)
@client.send_message('Emulation.setTimezoneOverride', timezoneId: timezone_id || '')
rescue => err
if err.message.include?('Invalid timezone')
raise ArgumentError.new("Invalid timezone ID: #{timezone_id}")
else
raise err
end
end
VISION_DEFICIENCY_TYPES = %w[
none
achromatopsia
blurredVision
deuteranopia
protanopia
tritanopia
].freeze
def emulate_vision_deficiency(vision_deficiency_type)
value = vision_deficiency_type || 'none'
unless VISION_DEFICIENCY_TYPES.include?(value)
raise ArgumentError.new("Unsupported vision deficiency: #{vision_deficiency_type}")
end
@client.send_message('Emulation.setEmulatedVisionDeficiency', type: value)
end
# @param is_user_active [Boolean]
# @param is_screen_unlocked [Boolean]
def emulate_idle_state(is_user_active: nil, is_screen_unlocked: nil)
overrides = {
isUserActive: is_user_active,
isScreenUnlocked: is_screen_unlocked,
}.compact
if overrides.empty?
@client.send_message('Emulation.clearIdleOverride')
else
@client.send_message('Emulation.setIdleOverride', overrides)
end
end
# @param viewport [Viewport]
def viewport=(viewport)
needs_reload = @emulation_manager.emulate_viewport(viewport)
@viewport = viewport
reload if needs_reload
end
attr_reader :viewport
# @param {Function|string} pageFunction
# @param {!Array<*>} args
# @return {!Promise<*>}
def evaluate(page_function, *args)
main_frame.evaluate(page_function, *args)
end
define_async_method :async_evaluate
class JavaScriptFunction
def initialize(expression, args)
@expression = expression
@args = args
end
def source
"(#{@expression})(#{arguments})"
end
private def arguments
@args.map { |arg| arg.nil? ? nil : JSON.dump(arg) }.join(", ")
end
end
class JavaScriptExpression
def initialize(expression)
@expression = expression
end
def source
@expression
end
end
def evaluate_on_new_document(page_function, *args)