Class: Puppeteer::Bidi::Page
- Inherits:
-
Object
- Object
- Puppeteer::Bidi::Page
- Defined in:
- lib/puppeteer/bidi/page.rb,
sig/puppeteer/bidi/page.rbs
Overview
Page represents a single page/tab in the browser This is a high-level wrapper around Core::BrowsingContext
Constant Summary collapse
- UNIT_TO_PIXELS =
{ "px" => 1, "in" => 96, "cm" => 37.8, "mm" => 3.78 }.freeze
- PAPER_FORMATS =
{ "letter" => { "cm" => { width: 21.59, height: 27.94 }, "in" => { width: 8.5, height: 11 } }, "legal" => { "cm" => { width: 21.59, height: 35.56 }, "in" => { width: 8.5, height: 14 } }, "tabloid" => { "cm" => { width: 27.94, height: 43.18 }, "in" => { width: 11, height: 17 } }, "ledger" => { "cm" => { width: 43.18, height: 27.94 }, "in" => { width: 17, height: 11 } }, "a0" => { "cm" => { width: 84.1, height: 118.9 }, "in" => { width: 33.1102, height: 46.811 } }, "a1" => { "cm" => { width: 59.4, height: 84.1 }, "in" => { width: 23.3858, height: 33.1102 } }, "a2" => { "cm" => { width: 42, height: 59.4 }, "in" => { width: 16.5354, height: 23.3858 } }, "a3" => { "cm" => { width: 29.7, height: 42 }, "in" => { width: 11.6929, height: 16.5354 } }, "a4" => { "cm" => { width: 21, height: 29.7 }, "in" => { width: 8.2677, height: 11.6929 } }, "a5" => { "cm" => { width: 14.8, height: 21 }, "in" => { width: 5.8268, height: 8.2677 } }, "a6" => { "cm" => { width: 10.5, height: 14.8 }, "in" => { width: 4.1339, height: 5.8268 } } }.freeze
Instance Attribute Summary collapse
-
#browser_context ⇒ BrowserContext
readonly
: BrowserContext.
-
#browsing_context ⇒ Core::BrowsingContext
readonly
: Core::BrowsingContext.
-
#request_interception_semaphore ⇒ Object
readonly
Returns the value of attribute request_interception_semaphore.
-
#timeout_settings ⇒ TimeoutSettings
readonly
: TimeoutSettings.
Instance Method Summary collapse
-
#assert_not_closed ⇒ void
Check if this page is closed and raise error if so.
-
#authenticate(credentials) ⇒ void
Authenticate to HTTP Basic auth challenges.
-
#build_evaluation_expression(page_function, *args) ⇒ String
Build an evaluation expression from a function and arguments.
-
#click(selector, button: Mouse::LEFT, count: 1, delay: nil, offset: nil) ⇒ void
Click an element matching the selector.
-
#close ⇒ void
Close the page.
-
#closed? ⇒ Boolean
Check if page is closed.
-
#collect_frames(frame) ⇒ Array[Frame]
Recursively collect all frames starting from the given frame.
-
#content ⇒ String
Get the full HTML contents of the page, including the DOCTYPE.
- #convert_print_parameter_to_length_unit(parameter, length_unit) ⇒ Object
-
#cookies(*urls) ⇒ Array[Hash[String, untyped]]
Retrieve cookies for the current page.
- #credentials ⇒ Hash[Symbol, String]?
-
#default_navigation_timeout ⇒ Numeric
Get the current default navigation timeout in milliseconds.
-
#default_timeout ⇒ Numeric
Get the current default timeout in milliseconds.
-
#delete_cookie(*cookies, **cookie) ⇒ void
Delete cookies from the current page.
-
#emit(event, data = nil) ⇒ void
Emit an event to all registered listeners.
-
#emulate_locale(locale = nil) ⇒ void
Emulate locale.
-
#eval_on_selector(selector, page_function, *args) ⇒ Object
Evaluate a function on the first element matching the selector.
-
#eval_on_selector_all(selector, page_function, *args) ⇒ Object
Evaluate a function on all elements matching the selector.
-
#evaluate(script, *args) ⇒ Object
Evaluate JavaScript in the page context.
-
#evaluate_handle(script, *args) ⇒ JSHandle
Evaluate JavaScript and return a handle to the result.
-
#evaluate_on_new_document(page_function, *args) ⇒ NewDocumentScriptEvaluation
Evaluate a function before any script runs on every page load.
-
#expose_function(name, pptr_function = nil) {|arg0| ... } ⇒ void
Expose a Ruby callable as a function in the page's global context.
-
#focus(selector) ⇒ void
Focus an element matching the selector.
-
#focused_frame ⇒ Frame
Get the focused frame.
-
#frames ⇒ Array[Frame]
Get all frames (main frame + all nested child frames) Following Puppeteer's pattern of returning all frames recursively.
-
#get_default_navigation_timeout ⇒ Numeric
Get the current default navigation timeout in milliseconds.
-
#get_default_timeout ⇒ Numeric
Get the current default timeout in milliseconds.
-
#go(delta, wait_until:, timeout:) ⇒ HTTPResponse?
Navigate history by delta.
-
#go_back(wait_until: 'load', timeout: nil) ⇒ HTTPResponse?
Navigate backward in history.
-
#go_forward(wait_until: 'load', timeout: nil) ⇒ HTTPResponse?
Navigate forward in history.
-
#goto(url, wait_until: 'load', timeout: nil) ⇒ HTTPResponse?
Navigate to a URL.
-
#hover(selector) ⇒ void
Hover over an element matching the selector.
-
#initialize(browser_context, browsing_context) ⇒ Page
constructor
A new instance of Page.
-
#javascript_enabled? ⇒ Boolean
Check if JavaScript is enabled.
- #js_typeof(value) ⇒ Object
-
#keyboard ⇒ Keyboard
Get the keyboard instance.
-
#locator(selector = nil, function: nil) ⇒ Locator
Create a locator for a selector or function.
-
#main_frame ⇒ Frame
Get the main frame.
-
#mouse ⇒ Mouse
Get the mouse instance.
- #network_interception_enabled? ⇒ Boolean
-
#normalize_client_hints_metadata(client_hints) ⇒ Hash[String, untyped]
Normalize user agent metadata/client hints keys to camelCase.
-
#off(event) {|arg0| ... } ⇒ void
Remove an event listener.
-
#on(event) {|arg0| ... } ⇒ void
Register an event listener.
-
#once(event) {|arg0| ... } ⇒ void
Register a one-time event listener.
- #parse_cookie_url(cookie_url) ⇒ URI::Generic?
- #parse_cookie_url_strict(cookie_url) ⇒ Object
- #parse_pdf_options(options, length_unit) ⇒ Object
- #parse_print_parameter_value(text, value_text) ⇒ Object
-
#pdf(path: nil, scale: nil, display_header_footer: nil, header_template: nil, footer_template: nil, print_background: nil, landscape: nil, page_ranges: nil, format: nil, width: nil, height: nil, prefer_css_page_size: nil, margin: nil, omit_background: nil, tagged: nil, outline: nil, timeout: nil, wait_for_fonts: nil) ⇒ String
Generate a PDF of the page.
- #process_clip(clip_x:, clip_y:, clip_width:, clip_height:) ⇒ Array[Integer]
-
#query_selector(selector) ⇒ ElementHandle?
Query for an element matching the selector.
-
#query_selector_all(selector) ⇒ Array[ElementHandle]
Query for all elements matching the selector.
-
#reload(timeout: nil, wait_until: 'load', ignore_cache: false) ⇒ HTTPResponse?
Reloads the page.
-
#remove_exposed_function(name) ⇒ void
Remove an exposed function.
-
#remove_script_to_evaluate_on_new_document(identifier) ⇒ void
Remove a script injected by evaluateOnNewDocument.
-
#screenshot(path: nil, type: 'png', full_page: false, clip: nil, capture_beyond_viewport: true) ⇒ String
Take a screenshot.
-
#select(selector, *values) ⇒ Array[String]
Select options on a
-
#serialize_arg_for_preload(arg) ⇒ String
Serialize an argument for use in preload script.
-
#set_cache_enabled(enabled) ⇒ void
Enable or disable cache.
-
#set_content(html, wait_until: 'load', timeout: nil) ⇒ void
Set page content.
-
#set_cookie(*cookies, **cookie) ⇒ void
Set cookies for the current page.
-
#set_default_navigation_timeout(timeout) ⇒ void
(also: #default_navigation_timeout=)
Set the default navigation timeout.
-
#set_default_timeout(timeout) ⇒ void
(also: #default_timeout=)
Set the default timeout for waiting operations (e.g., waitForFunction).
-
#set_extra_http_headers(headers) ⇒ void
Set extra HTTP headers for the page.
-
#set_geolocation(longitude:, latitude:, accuracy: nil) ⇒ void
Set geolocation override.
-
#set_javascript_enabled(enabled) ⇒ void
Set JavaScript enabled state.
-
#set_request_interception(enable) ⇒ void
Enable or disable request interception.
-
#set_user_agent(user_agent, user_agent_metadata = nil) ⇒ void
Set user agent.
-
#set_viewport(width:, height:, device_scale_factor: nil, has_touch: nil, is_mobile: nil, is_landscape: nil) ⇒ void
(also: #viewport=)
Set viewport size.
-
#target ⇒ PageTarget
Get the target associated with this page.
-
#title ⇒ String
Get the page title.
- #toggle_interception(phases, interception, expected) ⇒ Object
-
#type(selector, text, delay: 0) ⇒ void
Type text into an element matching the selector.
-
#url ⇒ String
Get the page URL.
-
#viewport ⇒ Hash[Symbol, Integer]?
Get current viewport size.
-
#wait_for_file_chooser(timeout: nil, &block) ⇒ void
Wait for a file chooser to be opened.
-
#wait_for_function(page_function, options = {}, *args, &block) ⇒ void
Wait for a function to return a truthy value.
-
#wait_for_navigation(timeout: nil, wait_until: 'load', &block) ⇒ void
Wait for navigation to complete.
-
#wait_for_network_idle(idle_time: 500, timeout: nil, concurrency: 0) ⇒ void
Wait for network to be idle (no more than concurrency connections for idle_time) Based on Puppeteer's waitForNetworkIdle implementation.
-
#wait_for_request(url_or_predicate, timeout: nil, &block) ⇒ void
Wait for a request that matches a URL or predicate.
-
#wait_for_response(url_or_predicate, timeout: nil, &block) ⇒ void
Wait for a response that matches a URL or predicate.
-
#wait_for_selector(selector, visible: nil, hidden: nil, timeout: nil, &block) ⇒ void
Wait for an element matching the selector to appear in the page.
-
#window_id ⇒ String
Get the client window ID for this page.
Constructor Details
#initialize(browser_context, browsing_context) ⇒ Page
Returns a new instance of Page.
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/puppeteer/bidi/page.rb', line 74 def initialize(browser_context, browsing_context) @browser_context = browser_context @browsing_context = browsing_context @timeout_settings = TimeoutSettings.new @emitter = Core::EventEmitter.new @file_chooser_waiters = [] @request_interception_semaphore = Async::Semaphore.new(1) @request_handlers = begin ObjectSpace::WeakMap.new rescue NameError {} end @request_interception = nil @auth_interception = nil @credentials = nil end |
Instance Attribute Details
#browser_context ⇒ BrowserContext (readonly)
: BrowserContext
68 69 70 |
# File 'lib/puppeteer/bidi/page.rb', line 68 def browser_context @browser_context end |
#browsing_context ⇒ Core::BrowsingContext (readonly)
: Core::BrowsingContext
67 68 69 |
# File 'lib/puppeteer/bidi/page.rb', line 67 def browsing_context @browsing_context end |
#request_interception_semaphore ⇒ Object (readonly)
Returns the value of attribute request_interception_semaphore.
158 159 160 |
# File 'lib/puppeteer/bidi/page.rb', line 158 def request_interception_semaphore @request_interception_semaphore end |
#timeout_settings ⇒ TimeoutSettings (readonly)
: TimeoutSettings
69 70 71 |
# File 'lib/puppeteer/bidi/page.rb', line 69 def timeout_settings @timeout_settings end |
Instance Method Details
#assert_not_closed ⇒ void
This method returns an undefined value.
Check if this page is closed and raise error if so
1507 1508 1509 |
# File 'lib/puppeteer/bidi/page.rb', line 1507 def assert_not_closed raise PageClosedError if closed? end |
#authenticate(credentials) ⇒ void
This method returns an undefined value.
Authenticate to HTTP Basic auth challenges.
666 667 668 669 670 671 672 673 674 675 676 |
# File 'lib/puppeteer/bidi/page.rb', line 666 def authenticate(credentials) assert_not_closed @auth_interception = toggle_interception( ["authRequired"], @auth_interception, !credentials.nil?, ) @credentials = credentials end |
#build_evaluation_expression(page_function, *args) ⇒ String
Build an evaluation expression from a function and arguments. Following Puppeteer's evaluationExpression pattern.
1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 |
# File 'lib/puppeteer/bidi/page.rb', line 1565 def build_evaluation_expression(page_function, *args) page_function_str = page_function.strip is_function = page_function_str.match?(/\A\s*(?:async\s+)?(?:\(.*?\)|[a-zA-Z_$][\w$]*)\s*=>/) || page_function_str.match?(/\A\s*(?:async\s+)?function\s*\w*\s*\(/) if !args.empty? && !is_function raise ArgumentError, "Cannot evaluate a string with arguments" end args_str = args.map { |arg| serialize_arg_for_preload(arg) }.join(", ") if is_function "() => { (#{page_function_str})(#{args_str}); }" else "() => { #{page_function_str} }" end end |
#click(selector, button: Mouse::LEFT, count: 1, delay: nil, offset: nil) ⇒ void
This method returns an undefined value.
Click an element matching the selector
515 516 517 |
# File 'lib/puppeteer/bidi/page.rb', line 515 def click(selector, button: Mouse::LEFT, count: 1, delay: nil, offset: nil) main_frame.click(selector, button: , count: count, delay: delay, offset: offset) end |
#close ⇒ void
This method returns an undefined value.
Close the page
597 598 599 600 601 |
# File 'lib/puppeteer/bidi/page.rb', line 597 def close return if closed? @browsing_context.close.wait end |
#closed? ⇒ Boolean
Check if page is closed
605 606 607 |
# File 'lib/puppeteer/bidi/page.rb', line 605 def closed? @browsing_context.closed? end |
#collect_frames(frame) ⇒ Array[Frame]
Recursively collect all frames starting from the given frame
1497 1498 1499 1500 1501 1502 1503 |
# File 'lib/puppeteer/bidi/page.rb', line 1497 def collect_frames(frame) result = [frame] frame.child_frames.each do |child| result.concat(collect_frames(child)) end result end |
#content ⇒ String
Get the full HTML contents of the page, including the DOCTYPE.
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 |
# File 'lib/puppeteer/bidi/page.rb', line 572 def content assert_not_closed # Port of Puppeteer's Frame.content(). # https://github.com/puppeteer/puppeteer/blob/main/packages/puppeteer-core/src/api/Frame.ts main_frame.evaluate(<<~JS) () => { let content = ''; for (const node of document.childNodes) { switch (node) { case document.documentElement: content += document.documentElement.outerHTML; break; default: content += new XMLSerializer().serializeToString(node); break; } } return content; } JS end |
#convert_print_parameter_to_length_unit(parameter, length_unit) ⇒ Object
1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 |
# File 'lib/puppeteer/bidi/page.rb', line 1676 def convert_print_parameter_to_length_unit(parameter, length_unit) return nil if parameter.nil? pixels = nil if parameter.is_a?(Numeric) pixels = parameter elsif parameter.is_a?(String) text = parameter unit = text[-2, 2].to_s.downcase if UNIT_TO_PIXELS.key?(unit) value_text = text[0...-2] else unit = "px" value_text = text end value = parse_print_parameter_value(text, value_text) pixels = value * UNIT_TO_PIXELS[unit] else raise "page.pdf() Cannot handle parameter type: #{js_typeof(parameter)}" end pixels / UNIT_TO_PIXELS.fetch(length_unit) end |
#cookies(*urls) ⇒ Array[Hash[String, untyped]]
Retrieve cookies for the current page.
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 |
# File 'lib/puppeteer/bidi/page.rb', line 906 def (*urls) assert_not_closed normalized_urls = (urls.empty? ? [url] : urls).map do || () end @browsing_context..wait .map { || CookieUtils.() } .select do || normalized_urls.any? do |normalized_url| CookieUtils.(, normalized_url) end end end |
#credentials ⇒ Hash[Symbol, String]?
153 154 155 |
# File 'lib/puppeteer/bidi/page.rb', line 153 def credentials @credentials end |
#default_navigation_timeout ⇒ Numeric
Get the current default navigation timeout in milliseconds.
792 793 794 |
# File 'lib/puppeteer/bidi/page.rb', line 792 def @timeout_settings. end |
#default_timeout ⇒ Numeric
Get the current default timeout in milliseconds.
786 787 788 |
# File 'lib/puppeteer/bidi/page.rb', line 786 def default_timeout @timeout_settings.timeout end |
#delete_cookie(*cookies, **cookie) ⇒ void
This method returns an undefined value.
Delete cookies from the current page.
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 |
# File 'lib/puppeteer/bidi/page.rb', line 994 def (*, **) assert_not_closed = .dup << unless .empty? page_url = url tasks = .map do || = CookieUtils.() = ["url"] || page_url normalized_url = (.to_s) domain = ["domain"] || normalized_url&.host if domain.nil? raise ArgumentError, "At least one of the url and domain needs to be specified" end filter = { "domain" => domain, "name" => ["name"], } filter["path"] = ["path"] if .key?("path") -> { @browsing_context.(filter).wait } end AsyncUtils.await_promise_all(*tasks) unless tasks.empty? end |
#emit(event, data = nil) ⇒ void
This method returns an undefined value.
Emit an event to all registered listeners
143 144 145 |
# File 'lib/puppeteer/bidi/page.rb', line 143 def emit(event, data = nil) @emitter.emit(event, data) end |
#emulate_locale(locale = nil) ⇒ void
This method returns an undefined value.
Emulate locale
1203 1204 1205 1206 1207 |
# File 'lib/puppeteer/bidi/page.rb', line 1203 def emulate_locale(locale = nil) assert_not_closed @browsing_context.set_locale_override(locale).wait end |
#eval_on_selector(selector, page_function, *args) ⇒ Object
Evaluate a function on the first element matching the selector
495 496 497 |
# File 'lib/puppeteer/bidi/page.rb', line 495 def eval_on_selector(selector, page_function, *args) main_frame.eval_on_selector(selector, page_function, *args) end |
#eval_on_selector_all(selector, page_function, *args) ⇒ Object
Evaluate a function on all elements matching the selector
504 505 506 |
# File 'lib/puppeteer/bidi/page.rb', line 504 def eval_on_selector_all(selector, page_function, *args) main_frame.eval_on_selector_all(selector, page_function, *args) end |
#evaluate(script, *args) ⇒ Object
Evaluate JavaScript in the page context
446 447 448 |
# File 'lib/puppeteer/bidi/page.rb', line 446 def evaluate(script, *args) main_frame.evaluate(script, *args) end |
#evaluate_handle(script, *args) ⇒ JSHandle
Evaluate JavaScript and return a handle to the result
454 455 456 |
# File 'lib/puppeteer/bidi/page.rb', line 454 def evaluate_handle(script, *args) main_frame.evaluate_handle(script, *args) end |
#evaluate_on_new_document(page_function, *args) ⇒ NewDocumentScriptEvaluation
Evaluate a function before any script runs on every page load.
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 |
# File 'lib/puppeteer/bidi/page.rb', line 1302 def evaluate_on_new_document(page_function, *args) assert_not_closed # Build the evaluation expression as an IIFE expression = build_evaluation_expression(page_function, *args) # Add as preload script script_id = @browsing_context.add_preload_script(expression).wait NewDocumentScriptEvaluation.new(script_id) end |
#expose_function(name, pptr_function = nil) {|arg0| ... } ⇒ void
This method returns an undefined value.
Expose a Ruby callable as a function in the page's global context. The function persists across navigations.
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 |
# File 'lib/puppeteer/bidi/page.rb', line 1328 def expose_function(name, pptr_function = nil, &block) assert_not_closed handler = block if handler.nil? if pptr_function.respond_to?(:call) handler = pptr_function elsif pptr_function.is_a?(Hash) handler = pptr_function[:default] || pptr_function["default"] end end unless handler&.respond_to?(:call) raise ArgumentError, "expose_function requires a callable" end main_frame.expose_function(name, handler) end |
#focus(selector) ⇒ void
This method returns an undefined value.
Focus an element matching the selector
547 548 549 550 551 552 553 554 555 556 |
# File 'lib/puppeteer/bidi/page.rb', line 547 def focus(selector) handle = main_frame.query_selector(selector) raise SelectorNotFoundError, selector unless handle begin handle.focus ensure handle.dispose end end |
#focused_frame ⇒ Frame
Get the focused frame
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 |
# File 'lib/puppeteer/bidi/page.rb', line 689 def focused_frame assert_not_closed # Evaluate in main frame to find the focused window handle = main_frame.evaluate_handle(<<~JS) () => { let win = window; while ( win.document.activeElement instanceof win.HTMLIFrameElement || win.document.activeElement instanceof win.HTMLFrameElement ) { if (win.document.activeElement.contentWindow === null) { break; } win = win.document.activeElement.contentWindow; } return win; } JS # Get the remote value (should be a window object) remote_value = handle.remote_value handle.dispose unless remote_value['type'] == 'window' raise "Expected window type, got #{remote_value['type']}" end # Find the frame with matching context ID context_id = remote_value['value']['context'] frame = frames.find { |f| f.browsing_context.id == context_id } raise "Could not find frame with context #{context_id}" unless frame frame end |
#frames ⇒ Array[Frame]
Get all frames (main frame + all nested child frames) Following Puppeteer's pattern of returning all frames recursively
729 730 731 |
# File 'lib/puppeteer/bidi/page.rb', line 729 def frames collect_frames(main_frame) end |
#get_default_navigation_timeout ⇒ Numeric
Get the current default navigation timeout in milliseconds.
804 805 806 |
# File 'lib/puppeteer/bidi/page.rb', line 804 def end |
#get_default_timeout ⇒ Numeric
Get the current default timeout in milliseconds.
798 799 800 |
# File 'lib/puppeteer/bidi/page.rb', line 798 def get_default_timeout default_timeout end |
#go(delta, wait_until:, timeout:) ⇒ HTTPResponse?
Navigate history by delta.
In Firefox, BFCache restores may emit browsingContext.navigationStarted
without firing domContentLoaded / load. We treat such navigations as
completed if we don't observe a navigation request shortly after start.
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 |
# File 'lib/puppeteer/bidi/page.rb', line 1387 def go(delta, wait_until:, timeout:) assert_not_closed timeout_ms = timeout || @timeout_settings. load_event = wait_until == 'domcontentloaded' ? :dom_content_loaded : :load started_promise = Async::Promise.new load_promise = Async::Promise.new = Async::Promise.new = nil = nil session = @browsing_context.user_context.browser.session history_listener = proc do started_promise.resolve(:history_updated) unless started_promise.resolved? end fragment_listener = proc do started_promise.resolve(:fragment_navigated) unless started_promise.resolved? end nav_started_listener = proc do |info| next unless info['context'] == @browsing_context.id = info['navigation'] = info['url'] started_promise.resolve(:navigation_started) unless started_promise.resolved? end request_listener = proc do |request| next unless next unless request&. == .resolve(nil) unless .resolved? end load_listener = proc do load_promise.resolve(nil) unless load_promise.resolved? end closed_listener = proc do started_promise.reject(PageClosedError.new) unless started_promise.resolved? end begin session.on('browsingContext.navigationStarted', &nav_started_listener) @browsing_context.on(:history_updated, &history_listener) @browsing_context.on(:fragment_navigated, &fragment_listener) @browsing_context.on(:request, &request_listener) @browsing_context.once(load_event, &load_listener) @browsing_context.once(:closed, &closed_listener) @browsing_context.traverse_history(delta).wait rescue Connection::ProtocolError => e # "History entry with delta X not found" - at history edge return nil if e..include?('not found') raise end begin # If nothing starts soon, assume we're at the history edge. start_timeout_ms = timeout_ms.positive? ? [timeout_ms.to_i, 500].min : 500 start_type = AsyncUtils.async_timeout(start_timeout_ms, started_promise).wait rescue Async::TimeoutError return nil end case start_type when :history_updated, :fragment_navigated nil when :navigation_started # Determine BFCache restore (no navigation request) vs full navigation. begin AsyncUtils.async_timeout(200, ).wait begin if timeout_ms == 0 load_promise.wait else AsyncUtils.async_timeout(timeout_ms, load_promise).wait end rescue Async::TimeoutError raise Puppeteer::Bidi::TimeoutError, "Navigation timeout of #{timeout_ms} ms exceeded" end HTTPResponse.for_bfcache(url: @browsing_context.url) rescue Async::TimeoutError # No navigation request observed: treat as BFCache restore. @browsing_context.instance_variable_set(:@url, ) if @browsing_context.&.dispose unless @browsing_context.&.disposed? HTTPResponse.for_bfcache(url: || @browsing_context.url) end else nil end ensure session.off('browsingContext.navigationStarted', &nav_started_listener) @browsing_context.off(:history_updated, &history_listener) @browsing_context.off(:fragment_navigated, &fragment_listener) @browsing_context.off(:request, &request_listener) @browsing_context.off(load_event, &load_listener) @browsing_context.off(:closed, &closed_listener) end |
#go_back(wait_until: 'load', timeout: nil) ⇒ HTTPResponse?
Navigate backward in history
1364 1365 1366 |
# File 'lib/puppeteer/bidi/page.rb', line 1364 def go_back(wait_until: 'load', timeout: nil) go(-1, wait_until: wait_until, timeout: timeout) end |
#go_forward(wait_until: 'load', timeout: nil) ⇒ HTTPResponse?
Navigate forward in history
1372 1373 1374 |
# File 'lib/puppeteer/bidi/page.rb', line 1372 def go_forward(wait_until: 'load', timeout: nil) go(1, wait_until: wait_until, timeout: timeout) end |
#goto(url, wait_until: 'load', timeout: nil) ⇒ HTTPResponse?
Navigate to a URL
165 166 167 168 169 |
# File 'lib/puppeteer/bidi/page.rb', line 165 def goto(url, wait_until: 'load', timeout: nil) assert_not_closed main_frame.goto(url, wait_until: wait_until, timeout: timeout) end |
#hover(selector) ⇒ void
This method returns an undefined value.
Hover over an element matching the selector
531 532 533 |
# File 'lib/puppeteer/bidi/page.rb', line 531 def hover(selector) main_frame.hover(selector) end |
#javascript_enabled? ⇒ Boolean
Check if JavaScript is enabled
1356 1357 1358 |
# File 'lib/puppeteer/bidi/page.rb', line 1356 def javascript_enabled? @browsing_context.javascript_enabled? end |
#js_typeof(value) ⇒ Object
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 |
# File 'lib/puppeteer/bidi/page.rb', line 1710 def js_typeof(value) case value when String "string" when Numeric "number" when TrueClass, FalseClass "boolean" when Proc, Method "function" else "object" end end |
#keyboard ⇒ Keyboard
Get the keyboard instance
741 742 743 |
# File 'lib/puppeteer/bidi/page.rb', line 741 def keyboard @keyboard ||= Keyboard.new(self, @browsing_context) end |
#locator(selector = nil, function: nil) ⇒ Locator
Create a locator for a selector or function.
476 477 478 479 480 481 482 483 484 485 486 487 488 |
# File 'lib/puppeteer/bidi/page.rb', line 476 def locator(selector = nil, function: nil) assert_not_closed if function raise ArgumentError, "selector and function cannot both be set" if selector FunctionLocator.create(self, function) elsif selector NodeLocator.create(self, selector) else raise ArgumentError, "selector or function must be provided" end end |
#main_frame ⇒ Frame
Get the main frame
611 612 613 |
# File 'lib/puppeteer/bidi/page.rb', line 611 def main_frame @main_frame ||= Frame.from(self, @browsing_context) end |
#mouse ⇒ Mouse
Get the mouse instance
735 736 737 |
# File 'lib/puppeteer/bidi/page.rb', line 735 def mouse @mouse ||= Mouse.new(@browsing_context) end |
#network_interception_enabled? ⇒ Boolean
148 149 150 |
# File 'lib/puppeteer/bidi/page.rb', line 148 def network_interception_enabled? !@request_interception.nil? || !@auth_interception.nil? end |
#normalize_client_hints_metadata(client_hints) ⇒ Hash[String, untyped]
Normalize user agent metadata/client hints keys to camelCase.
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 |
# File 'lib/puppeteer/bidi/page.rb', line 1608 def (client_hints) hints = client_hints || {} hints.each_with_object({}) do |(key, value), result| key_string = key.to_s normalized_key = if key_string.include?('_') parts = key_string.split('_') parts[0] + parts[1..].map(&:capitalize).join else key_string end result[normalized_key] = value end end |
#off(event) {|arg0| ... } ⇒ void
This method returns an undefined value.
Remove an event listener
125 126 127 128 129 130 131 132 133 134 135 136 137 |
# File 'lib/puppeteer/bidi/page.rb', line 125 def off(event, &block) if event.to_sym == :request && block # WeakMap#delete was added in Ruby 3.3, so we need to handle older versions wrapper = if @request_handlers.respond_to?(:delete) @request_handlers.delete(block) else @request_handlers[block] end return @emitter.off(event, &(wrapper || block)) end @emitter.off(event, &block) end |
#on(event) {|arg0| ... } ⇒ void
This method returns an undefined value.
Register an event listener
98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/puppeteer/bidi/page.rb', line 98 def on(event, &block) return @emitter.on(event, &block) unless event.to_sym == :request wrapper = @request_handlers[block] unless wrapper wrapper = lambda do |request| request.enqueue_intercept_action do block.call(request) end end @request_handlers[block] = wrapper end @emitter.on(event, &wrapper) end |
#once(event) {|arg0| ... } ⇒ void
This method returns an undefined value.
Register a one-time event listener
117 118 119 |
# File 'lib/puppeteer/bidi/page.rb', line 117 def once(event, &block) @emitter.once(event, &block) end |
#parse_cookie_url(cookie_url) ⇒ URI::Generic?
1513 1514 1515 1516 1517 1518 1519 |
# File 'lib/puppeteer/bidi/page.rb', line 1513 def () return nil if .nil? || .empty? URI.parse() rescue URI::InvalidURIError nil end |
#parse_cookie_url_strict(cookie_url) ⇒ Object
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 |
# File 'lib/puppeteer/bidi/page.rb', line 1521 def () normalized_url = URI.parse(.to_s) if normalized_url.scheme.nil? || (normalized_url.scheme.match?(/\Ahttps?\z/i) && normalized_url.host.to_s.empty?) raise ArgumentError, "Invalid URL" end normalized_url rescue URI::InvalidURIError raise ArgumentError, "Invalid URL" end |
#parse_pdf_options(options, length_unit) ⇒ Object
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 |
# File 'lib/puppeteer/bidi/page.rb', line 1622 def (, length_unit) defaults = { scale: 1, display_header_footer: false, header_template: "", footer_template: "", print_background: false, landscape: false, page_ranges: "", prefer_css_page_size: false, omit_background: false, outline: false, tagged: true, wait_for_fonts: true } width = 8.5 height = 11 format = [:format] if format format_key = format.to_s.downcase format_dimensions = PAPER_FORMATS[format_key] raise "Unknown paper format: #{format}" unless format_dimensions dimensions = format_dimensions[length_unit] width = dimensions[:width] height = dimensions[:height] else width = convert_print_parameter_to_length_unit([:width], length_unit) || width height = convert_print_parameter_to_length_unit([:height], length_unit) || height end = [:margin] if .is_a?(Hash) = .transform_keys(&:to_sym) else = {} end margin = { top: convert_print_parameter_to_length_unit([:top], length_unit) || 0, left: convert_print_parameter_to_length_unit([:left], length_unit) || 0, bottom: convert_print_parameter_to_length_unit([:bottom], length_unit) || 0, right: convert_print_parameter_to_length_unit([:right], length_unit) || 0 } [:tagged] = true if [:outline] defaults.merge().merge( width: width, height: height, margin: margin ) end |
#parse_print_parameter_value(text, value_text) ⇒ Object
1701 1702 1703 1704 1705 1706 1707 1708 |
# File 'lib/puppeteer/bidi/page.rb', line 1701 def parse_print_parameter_value(text, value_text) value = Float(value_text) raise "Failed to parse parameter value: #{text}" if value.nan? value rescue ArgumentError raise "Failed to parse parameter value: #{text}" end |
#pdf(path: nil, scale: nil, display_header_footer: nil, header_template: nil, footer_template: nil, print_background: nil, landscape: nil, page_ranges: nil, format: nil, width: nil, height: nil, prefer_css_page_size: nil, margin: nil, omit_background: nil, tagged: nil, outline: nil, timeout: nil, wait_for_fonts: nil) ⇒ String
Generate a PDF of the page.
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 |
# File 'lib/puppeteer/bidi/page.rb', line 352 def pdf( path: nil, scale: nil, display_header_footer: nil, header_template: nil, footer_template: nil, print_background: nil, landscape: nil, page_ranges: nil, format: nil, width: nil, height: nil, prefer_css_page_size: nil, margin: nil, omit_background: nil, tagged: nil, outline: nil, timeout: nil, wait_for_fonts: nil ) assert_not_closed timeout_ms = timeout.nil? ? @timeout_settings.timeout : timeout = { scale: scale, display_header_footer: , header_template: header_template, footer_template: , print_background: print_background, landscape: landscape, page_ranges: page_ranges, format: format, width: width, height: height, prefer_css_page_size: prefer_css_page_size, margin: margin, omit_background: omit_background, tagged: tagged, outline: outline, wait_for_fonts: wait_for_fonts }.compact parsed = (, "cm") ranges = parsed[:page_ranges] page_ranges = ranges && !ranges.empty? ? ranges.split(", ") : [] # Wait for fonts to load begin if timeout_ms == 0 main_frame.isolated_realm.evaluate("() => document.fonts.ready") else AsyncUtils.async_timeout(timeout_ms, -> do main_frame.isolated_realm.evaluate("() => document.fonts.ready") end).wait end rescue Async::TimeoutError raise TimeoutError, "Timed out after waiting #{timeout_ms}ms" end = { background: parsed[:print_background], margin: parsed[:margin], orientation: parsed[:landscape] ? "landscape" : "portrait", page: { width: parsed[:width], height: parsed[:height] }, pageRanges: page_ranges, scale: parsed[:scale], shrinkToFit: !parsed[:prefer_css_page_size] } begin data = if timeout_ms == 0 @browsing_context.print(**).wait else AsyncUtils.async_timeout(timeout_ms, -> do @browsing_context.print(**).wait end).wait end rescue Async::TimeoutError raise TimeoutError, "Timed out after waiting #{timeout_ms}ms" end pdf_data = Base64.decode64(data) File.binwrite(path, pdf_data) if path pdf_data end |
#process_clip(clip_x:, clip_y:, clip_width:, clip_height:) ⇒ Array[Integer]
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 |
# File 'lib/puppeteer/bidi/page.rb', line 1549 def process_clip(clip_x:, clip_y:, clip_width:, clip_height:) rounded_x = clip_x.round rounded_y = clip_y.round [ rounded_x, rounded_y, (clip_width + (clip_x - rounded_x)).round, (clip_height + (clip_y - rounded_y)).round, ] end |
#query_selector(selector) ⇒ ElementHandle?
Query for an element matching the selector
461 462 463 |
# File 'lib/puppeteer/bidi/page.rb', line 461 def query_selector(selector) main_frame.query_selector(selector) end |
#query_selector_all(selector) ⇒ Array[ElementHandle]
Query for all elements matching the selector
468 469 470 |
# File 'lib/puppeteer/bidi/page.rb', line 468 def query_selector_all(selector) main_frame.query_selector_all(selector) end |
#reload(timeout: nil, wait_until: 'load', ignore_cache: false) ⇒ HTTPResponse?
Reloads the page.
626 627 628 629 630 631 632 633 634 635 |
# File 'lib/puppeteer/bidi/page.rb', line 626 def reload(timeout: nil, wait_until: 'load', ignore_cache: false) assert_not_closed = {} [:ignoreCache] = true if ignore_cache (timeout: timeout, wait_until: wait_until) do @browsing_context.reload(**).wait end end |
#remove_exposed_function(name) ⇒ void
This method returns an undefined value.
Remove an exposed function.
1349 1350 1351 1352 |
# File 'lib/puppeteer/bidi/page.rb', line 1349 def remove_exposed_function(name) assert_not_closed main_frame.remove_exposed_function(name) end |
#remove_script_to_evaluate_on_new_document(identifier) ⇒ void
This method returns an undefined value.
Remove a script injected by evaluateOnNewDocument.
1317 1318 1319 1320 |
# File 'lib/puppeteer/bidi/page.rb', line 1317 def remove_script_to_evaluate_on_new_document(identifier) assert_not_closed @browsing_context.remove_preload_script(identifier).wait end |
#screenshot(path: nil, type: 'png', full_page: false, clip: nil, capture_beyond_viewport: true) ⇒ String
Take a screenshot
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 |
# File 'lib/puppeteer/bidi/page.rb', line 187 def screenshot(path: nil, type: 'png', full_page: false, clip: nil, capture_beyond_viewport: true) assert_not_closed = { format: { type: type == 'jpeg' ? 'image/jpeg' : 'image/png' } } # Handle fullPage screenshot if full_page # If captureBeyondViewport is false, then we set the viewport to # capture the full page. Note this may be affected by on-page CSS and JavaScript. unless # Get scroll dimensions scroll_dimensions = evaluate(<<~JS) (() => { const element = document.documentElement; return { width: element.scrollWidth, height: element.scrollHeight }; })() JS # Save original viewport (could be nil) = # If no viewport is set, save current window size unless original_size = evaluate('({ width: window.innerWidth, height: window.innerHeight })') = { width: original_size['width'].to_i, height: original_size['height'].to_i } end # Set viewport to full page size while preserving optional emulation flags. = { width: scroll_dimensions['width'].to_i, height: scroll_dimensions['height'].to_i } if [:device_scale_factor] = [:device_scale_factor] [:has_touch] = [:has_touch] [:is_mobile] = [:is_mobile] [:is_landscape] = [:is_landscape] end ( width: .fetch(:width), height: .fetch(:height), device_scale_factor: [:device_scale_factor], has_touch: [:has_touch], is_mobile: [:is_mobile], is_landscape: [:is_landscape] ) begin # Capture screenshot with viewport origin [:origin] = 'viewport' data = @browsing_context.capture_screenshot(**).wait ensure # Restore original viewport if ( width: .fetch(:width), height: .fetch(:height), device_scale_factor: [:device_scale_factor], has_touch: [:has_touch], is_mobile: [:is_mobile], is_landscape: [:is_landscape] ) end end # Save to file if path is provided if path dir = File.dirname(path) FileUtils.mkdir_p(dir) unless Dir.exist?(dir) File.binwrite(path, Base64.decode64(data)) end return data else # Capture full document with origin: document [:origin] = 'document' end elsif !clip # If not fullPage and no clip, force captureBeyondViewport to false = false end # Add clip region if specified if clip # Set origin based on captureBeyondViewport (only when clip is specified) if [:origin] = 'document' else [:origin] = 'viewport' end box = clip.dup # When captureBeyondViewport is false, convert document coordinates to viewport coordinates unless # Get viewport offset page_left = evaluate('window.visualViewport.pageLeft') page_top = evaluate('window.visualViewport.pageTop') # Convert to viewport coordinates box = { x: clip[:x] - page_left, y: clip[:y] - page_top, width: clip[:width], height: clip[:height] } end clip_x, clip_y, clip_width, clip_height = process_clip( clip_x: box[:x], clip_y: box[:y], clip_width: box[:width], clip_height: box[:height], ) [:clip] = { type: 'box', x: clip_x, y: clip_y, width: clip_width, height: clip_height } end # Get screenshot data from browsing context data = @browsing_context.capture_screenshot(**).wait # Save to file if path is provided if path # Ensure directory exists dir = File.dirname(path) FileUtils.mkdir_p(dir) unless Dir.exist?(dir) # data is base64 encoded, decode and write File.binwrite(path, Base64.decode64(data)) end data end |
#select(selector, *values) ⇒ Array[String]
Select options on a
540 541 542 |
# File 'lib/puppeteer/bidi/page.rb', line 540 def select(selector, *values) main_frame.select(selector, *values) end |
#serialize_arg_for_preload(arg) ⇒ String
Serialize an argument for use in preload script. Unlike BiDi serialization, this produces JavaScript literal strings.
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 |
# File 'lib/puppeteer/bidi/page.rb', line 1588 def serialize_arg_for_preload(arg) case arg when String JSON.generate(arg) when Integer, Float arg.to_s when TrueClass, FalseClass arg.to_s when NilClass "null" when Array, Hash JSON.generate(arg) else JSON.generate(arg.to_s) end end |
#set_cache_enabled(enabled) ⇒ void
This method returns an undefined value.
Enable or disable cache.
681 682 683 684 685 |
# File 'lib/puppeteer/bidi/page.rb', line 681 def set_cache_enabled(enabled) assert_not_closed @browsing_context.set_cache_behavior(enabled ? "default" : "bypass").wait end |
#set_content(html, wait_until: 'load', timeout: nil) ⇒ void
This method returns an undefined value.
Set page content
176 177 178 |
# File 'lib/puppeteer/bidi/page.rb', line 176 def set_content(html, wait_until: 'load', timeout: nil) main_frame.set_content(html, wait_until: wait_until, timeout: timeout) end |
#set_cookie(*cookies, **cookie) ⇒ void
This method returns an undefined value.
Set cookies for the current page.
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 |
# File 'lib/puppeteer/bidi/page.rb', line 926 def (*, **) assert_not_closed = .dup << unless .empty? page_url = url page_url_starts_with_http = page_url&.start_with?("http") .each do || = CookieUtils.() = ["url"].to_s if .empty? && page_url_starts_with_http = page_url end if == "about:blank" raise ArgumentError, "Blank page can not have cookie \"#{["name"]}\"" end if .start_with?("data:") raise ArgumentError, "Data URL page can not have cookie \"#{["name"]}\"" end partition_key = ["partitionKey"] if !partition_key.nil? && !partition_key.is_a?(String) raise ArgumentError, "BiDi only allows domain partition keys" end normalized_url = () domain = ["domain"] || normalized_url&.host if domain.nil? raise ArgumentError, "At least one of the url and domain needs to be specified" end = { "domain" => domain, "name" => ["name"], "value" => { "type" => "string", "value" => ["value"] }, } ["path"] = ["path"] if .key?("path") ["httpOnly"] = ["httpOnly"] if .key?("httpOnly") ["secure"] = ["secure"] if .key?("secure") if .key?("sameSite") && !["sameSite"].nil? ["sameSite"] = CookieUtils.( ["sameSite"] ) end expiry = CookieUtils.(["expires"]) ["expiry"] = expiry unless expiry.nil? .merge!(CookieUtils.( , "sourceScheme", "priority", "url" )) if partition_key @browser_context.user_context.(, source_origin: partition_key).wait else @browsing_context.().wait end end end |
#set_default_navigation_timeout(timeout) ⇒ void Also known as:
This method returns an undefined value.
Set the default navigation timeout.
778 779 780 781 782 |
# File 'lib/puppeteer/bidi/page.rb', line 778 def (timeout) raise ArgumentError, 'timeout must be a non-negative number' unless timeout.is_a?(Numeric) && timeout >= 0 @timeout_settings.(timeout) end |
#set_default_timeout(timeout) ⇒ void Also known as: default_timeout=
This method returns an undefined value.
Set the default timeout for waiting operations (e.g., waitForFunction).
769 770 771 772 773 |
# File 'lib/puppeteer/bidi/page.rb', line 769 def set_default_timeout(timeout) raise ArgumentError, 'timeout must be a non-negative number' unless timeout.is_a?(Numeric) && timeout >= 0 @timeout_settings.set_default_timeout(timeout) end |
#set_extra_http_headers(headers) ⇒ void
This method returns an undefined value.
Set extra HTTP headers for the page.
653 654 655 656 657 658 659 660 661 |
# File 'lib/puppeteer/bidi/page.rb', line 653 def set_extra_http_headers(headers) assert_not_closed normalized = {} headers.each do |key, value| normalized[key.to_s] = value.to_s end @browsing_context.set_extra_http_headers(normalized).wait end |
#set_geolocation(longitude:, latitude:, accuracy: nil) ⇒ void
This method returns an undefined value.
Set geolocation override
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 |
# File 'lib/puppeteer/bidi/page.rb', line 1214 def set_geolocation(longitude:, latitude:, accuracy: nil) assert_not_closed if longitude < -180 || longitude > 180 raise ArgumentError, "Invalid longitude \"#{longitude}\": precondition -180 <= LONGITUDE <= 180 failed." end if latitude < -90 || latitude > 90 raise ArgumentError, "Invalid latitude \"#{latitude}\": precondition -90 <= LATITUDE <= 90 failed." end accuracy_value = accuracy.nil? ? 0 : accuracy if accuracy_value < 0 raise ArgumentError, "Invalid accuracy \"#{accuracy_value}\": precondition 0 <= ACCURACY failed." end coordinates = { latitude: latitude, longitude: longitude } coordinates[:accuracy] = accuracy unless accuracy.nil? @browsing_context.set_geolocation_override( coordinates: coordinates ).wait end |
#set_javascript_enabled(enabled) ⇒ void
This method returns an undefined value.
Set JavaScript enabled state
1293 1294 1295 1296 |
# File 'lib/puppeteer/bidi/page.rb', line 1293 def set_javascript_enabled(enabled) assert_not_closed @browsing_context.set_javascript_enabled(enabled).wait end |
#set_request_interception(enable) ⇒ void
This method returns an undefined value.
Enable or disable request interception.
640 641 642 643 644 645 646 647 648 |
# File 'lib/puppeteer/bidi/page.rb', line 640 def set_request_interception(enable) assert_not_closed @request_interception = toggle_interception( ["beforeRequestSent"], @request_interception, enable, ) end |
#set_user_agent(user_agent, user_agent_metadata = nil) ⇒ void
This method returns an undefined value.
Set user agent
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 |
# File 'lib/puppeteer/bidi/page.rb', line 1243 def set_user_agent(user_agent, = nil) assert_not_closed parsed_user_agent = nil client_hints = nil platform = nil if user_agent.is_a?(Hash) = user_agent.transform_keys(&:to_sym) parsed_user_agent = .key?(:userAgent) ? [:userAgent] : [:user_agent] client_hints = [:userAgentMetadata] || [:user_agent_metadata] platform = [:platform] platform = nil if platform == '' else parsed_user_agent = user_agent client_hints = end parsed_user_agent = nil if parsed_user_agent == "" @browsing_context.set_user_agent(parsed_user_agent).wait if platform && platform != '' client_hints = (client_hints) client_hints['platform'] = platform end @browsing_context.set_client_hints_override( client_hints ? (client_hints) : nil ).wait end |
#set_viewport(width:, height:, device_scale_factor: nil, has_touch: nil, is_mobile: nil, is_landscape: nil) ⇒ void Also known as: viewport=
This method returns an undefined value.
Set viewport size
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 |
# File 'lib/puppeteer/bidi/page.rb', line 1167 def (width:, height:, device_scale_factor: nil, has_touch: nil, is_mobile: nil, is_landscape: nil) previous_has_touch = @viewport ? !!@viewport[:has_touch] : false current_has_touch = !!has_touch needs_reload = previous_has_touch != current_has_touch @viewport = { width: width, height: height } @viewport[:device_scale_factor] = device_scale_factor unless device_scale_factor.nil? @viewport[:has_touch] = has_touch unless has_touch.nil? @viewport[:is_mobile] = is_mobile unless is_mobile.nil? @viewport[:is_landscape] = is_landscape unless is_landscape.nil? @browsing_context.( viewport: { width: width, height: height }, devicePixelRatio: device_scale_factor ).wait if needs_reload max_touch_points = current_has_touch ? 1 : nil begin @browsing_context.set_touch_override(max_touch_points).wait rescue Connection::ProtocolError => error unsupported_error = error..include?('unknown command') || error..include?('unsupported operation') || error..include?('emulation.setTouchOverride') raise unless unsupported_error end reload end end |
#target ⇒ PageTarget
Get the target associated with this page.
617 618 619 |
# File 'lib/puppeteer/bidi/page.rb', line 617 def target @target ||= PageTarget.new(self) end |
#title ⇒ String
Get the page title
560 561 562 |
# File 'lib/puppeteer/bidi/page.rb', line 560 def title evaluate('document.title') end |
#toggle_interception(phases, interception, expected) ⇒ Object
1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 |
# File 'lib/puppeteer/bidi/page.rb', line 1532 def toggle_interception(phases, interception, expected) if expected && interception.nil? return @browsing_context.add_intercept(phases: phases).wait end if !expected && interception @browsing_context.user_context.browser.remove_intercept(interception).wait return nil end interception end |
#type(selector, text, delay: 0) ⇒ void
This method returns an undefined value.
Type text into an element matching the selector
524 525 526 |
# File 'lib/puppeteer/bidi/page.rb', line 524 def type(selector, text, delay: 0) main_frame.type(selector, text, delay: delay) end |
#url ⇒ String
Get the page URL
566 567 568 |
# File 'lib/puppeteer/bidi/page.rb', line 566 def url @browsing_context.url end |
#viewport ⇒ Hash[Symbol, Integer]?
Get current viewport size
1282 1283 1284 |
# File 'lib/puppeteer/bidi/page.rb', line 1282 def @viewport end |
#wait_for_file_chooser(timeout: nil, &block) ⇒ void
This method returns an undefined value.
Wait for a file chooser to be opened
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 |
# File 'lib/puppeteer/bidi/page.rb', line 1027 def wait_for_file_chooser(timeout: nil, &block) assert_not_closed # Use provided timeout, or default timeout, treating 0 as infinite effective_timeout = timeout || @timeout_settings.timeout promise = Async::Promise.new @file_chooser_waiters << promise # Listener for file dialog opened event file_dialog_listener = lambda do |info| # info contains: element, multiple element_info = info['element'] return unless element_info # Create ElementHandle from the element info # The element info should have sharedId and/or handle element_remote_value = { 'type' => 'node', 'sharedId' => element_info['sharedId'], 'handle' => element_info['handle'] }.compact element = ElementHandle.from(element_remote_value, @browsing_context.default_realm) multiple = info['multiple'] || false file_chooser = FileChooser.new(element, multiple) @file_chooser_waiters.each do |waiter| waiter.resolve(file_chooser) unless waiter.resolved? end @file_chooser_waiters.clear end begin # Register listener before executing the block @browsing_context.once(:filedialogopened, &file_dialog_listener) # Execute the block that triggers the file chooser Async(&block).wait if block # Wait for file chooser with timeout if effective_timeout == 0 promise.wait else AsyncUtils.async_timeout(effective_timeout, promise).wait end rescue Async::TimeoutError @file_chooser_waiters.delete(promise) raise TimeoutError, "Waiting for `FileChooser` failed: #{effective_timeout}ms exceeded" ensure @browsing_context.off(:filedialogopened, &file_dialog_listener) @file_chooser_waiters.delete(promise) end end |
#wait_for_function(page_function, options = {}, *args, &block) ⇒ void
This method returns an undefined value.
Wait for a function to return a truthy value
751 752 753 |
# File 'lib/puppeteer/bidi/page.rb', line 751 def wait_for_function(page_function, = {}, *args, &block) main_frame.wait_for_function(page_function, , *args, &block) end |
#wait_for_navigation(timeout: nil, wait_until: 'load', &block) ⇒ void
This method returns an undefined value.
Wait for navigation to complete
813 814 815 |
# File 'lib/puppeteer/bidi/page.rb', line 813 def (timeout: nil, wait_until: 'load', &block) main_frame.(timeout: timeout, wait_until: wait_until, &block) end |
#wait_for_network_idle(idle_time: 500, timeout: nil, concurrency: 0) ⇒ void
This method returns an undefined value.
Wait for network to be idle (no more than concurrency connections for idle_time) Based on Puppeteer's waitForNetworkIdle implementation
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 |
# File 'lib/puppeteer/bidi/page.rb', line 1088 def wait_for_network_idle(idle_time: 500, timeout: nil, concurrency: 0) assert_not_closed timeout_ms = timeout || @timeout_settings.timeout promise = Async::Promise.new idle_timer = nil idle_timer_mutex = Thread::Mutex.new # Listener for inflight changes inflight_listener = lambda do |data| inflight = data[:inflight] idle_timer_mutex.synchronize do # Cancel existing timer if any idle_timer&.stop # If inflight requests exceed concurrency, don't start timer if inflight > concurrency idle_timer = nil return end # Start idle timer idle_timer = Async do |task| task.sleep(idle_time / 1000.0) promise.resolve(nil) end end end # Close listener close_listener = lambda do |_data| promise.reject(PageClosedError.new) end begin # Register listeners @browsing_context.on(:inflight_changed, &inflight_listener) @browsing_context.on(:closed, &close_listener) # Check initial state - if already idle, start timer immediately current_inflight = @browsing_context.inflight_requests if current_inflight <= concurrency idle_timer_mutex.synchronize do idle_timer = Async do |task| task.sleep(idle_time / 1000.0) promise.resolve(nil) end end end # Wait with timeout if timeout_ms == 0 promise.wait else AsyncUtils.async_timeout(timeout_ms, promise).wait end rescue Async::TimeoutError raise TimeoutError, "Timed out after waiting #{timeout_ms}ms" ensure # Clean up idle_timer_mutex.synchronize do idle_timer&.stop end @browsing_context.off(:inflight_changed, &inflight_listener) @browsing_context.off(:closed, &close_listener) end nil end |
#wait_for_request(url_or_predicate, timeout: nil, &block) ⇒ void
This method returns an undefined value.
Wait for a request that matches a URL or predicate.
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 |
# File 'lib/puppeteer/bidi/page.rb', line 822 def wait_for_request(url_or_predicate, timeout: nil, &block) assert_not_closed timeout_ms = timeout || @timeout_settings.timeout predicate = if url_or_predicate.is_a?(Proc) url_or_predicate else ->(request) { request.url == url_or_predicate } end promise = Async::Promise.new listener = proc do |request| next unless predicate.call(request) promise.resolve(request) unless promise.resolved? end close_listener = proc do promise.reject(PageClosedError.new) unless promise.resolved? end begin on(:request, &listener) @browsing_context.once(:closed, &close_listener) Async(&block).wait if block if timeout_ms == 0 promise.wait else AsyncUtils.async_timeout(timeout_ms, promise).wait end rescue Async::TimeoutError raise TimeoutError, "Timed out after waiting #{timeout_ms}ms" ensure off(:request, &listener) @browsing_context.off(:closed, &close_listener) end end |
#wait_for_response(url_or_predicate, timeout: nil, &block) ⇒ void
This method returns an undefined value.
Wait for a response that matches a URL or predicate.
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 |
# File 'lib/puppeteer/bidi/page.rb', line 865 def wait_for_response(url_or_predicate, timeout: nil, &block) assert_not_closed timeout_ms = timeout || @timeout_settings.timeout predicate = if url_or_predicate.is_a?(Proc) url_or_predicate else ->(response) { response.url == url_or_predicate } end promise = Async::Promise.new listener = proc do |response| next unless predicate.call(response) promise.resolve(response) unless promise.resolved? end close_listener = proc do promise.reject(PageClosedError.new) unless promise.resolved? end begin on(:response, &listener) @browsing_context.once(:closed, &close_listener) Async(&block).wait if block if timeout_ms == 0 promise.wait else AsyncUtils.async_timeout(timeout_ms, promise).wait end rescue Async::TimeoutError raise TimeoutError, "Timed out after waiting #{timeout_ms}ms" ensure off(:response, &listener) @browsing_context.off(:closed, &close_listener) end end |
#wait_for_selector(selector, visible: nil, hidden: nil, timeout: nil, &block) ⇒ void
This method returns an undefined value.
Wait for an element matching the selector to appear in the page
762 763 764 |
# File 'lib/puppeteer/bidi/page.rb', line 762 def wait_for_selector(selector, visible: nil, hidden: nil, timeout: nil, &block) main_frame.wait_for_selector(selector, visible: visible, hidden: hidden, timeout: timeout, &block) end |
#window_id ⇒ String
Get the client window ID for this page.
1276 1277 1278 |
# File 'lib/puppeteer/bidi/page.rb', line 1276 def window_id @browsing_context.window_id end |