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| ... } ⇒ Page
Remove an event listener.
-
#on(event) {|arg0| ... } ⇒ Page
Register an event listener.
-
#once(event) {|arg0| ... } ⇒ Page
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.
- #request_listener_for(listener) ⇒ Object
-
#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.
151 152 153 |
# File 'lib/puppeteer/bidi/page.rb', line 151 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
1508 1509 1510 |
# File 'lib/puppeteer/bidi/page.rb', line 1508 def assert_not_closed raise PageClosedError if closed? end |
#authenticate(credentials) ⇒ void
This method returns an undefined value.
Authenticate to HTTP Basic auth challenges.
659 660 661 662 663 664 665 666 667 668 669 |
# File 'lib/puppeteer/bidi/page.rb', line 659 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.
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 |
# File 'lib/puppeteer/bidi/page.rb', line 1566 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
508 509 510 |
# File 'lib/puppeteer/bidi/page.rb', line 508 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
590 591 592 593 594 |
# File 'lib/puppeteer/bidi/page.rb', line 590 def close return if closed? @browsing_context.close.wait end |
#closed? ⇒ Boolean
Check if page is closed
598 599 600 |
# File 'lib/puppeteer/bidi/page.rb', line 598 def closed? @browsing_context.closed? end |
#collect_frames(frame) ⇒ Array[Frame]
Recursively collect all frames starting from the given frame
1498 1499 1500 1501 1502 1503 1504 |
# File 'lib/puppeteer/bidi/page.rb', line 1498 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.
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 |
# File 'lib/puppeteer/bidi/page.rb', line 565 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(" () => {\n let content = '';\n for (const node of document.childNodes) {\n switch (node) {\n case document.documentElement:\n content += document.documentElement.outerHTML;\n break;\n default:\n content += new XMLSerializer().serializeToString(node);\n break;\n }\n }\n return content;\n }\n JS\nend\n") |
#convert_print_parameter_to_length_unit(parameter, length_unit) ⇒ Object
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 |
# File 'lib/puppeteer/bidi/page.rb', line 1677 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.
899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 |
# File 'lib/puppeteer/bidi/page.rb', line 899 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]?
146 147 148 |
# File 'lib/puppeteer/bidi/page.rb', line 146 def credentials @credentials end |
#default_navigation_timeout ⇒ Numeric
Get the current default navigation timeout in milliseconds.
785 786 787 |
# File 'lib/puppeteer/bidi/page.rb', line 785 def @timeout_settings. end |
#default_timeout ⇒ Numeric
Get the current default timeout in milliseconds.
779 780 781 |
# File 'lib/puppeteer/bidi/page.rb', line 779 def default_timeout @timeout_settings.timeout end |
#delete_cookie(*cookies, **cookie) ⇒ void
This method returns an undefined value.
Delete cookies from the current page.
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 |
# File 'lib/puppeteer/bidi/page.rb', line 987 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
136 137 138 |
# File 'lib/puppeteer/bidi/page.rb', line 136 def emit(event, data = nil) @emitter.emit(event, data) end |
#emulate_locale(locale = nil) ⇒ void
This method returns an undefined value.
Emulate locale
1196 1197 1198 1199 1200 |
# File 'lib/puppeteer/bidi/page.rb', line 1196 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
488 489 490 |
# File 'lib/puppeteer/bidi/page.rb', line 488 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
497 498 499 |
# File 'lib/puppeteer/bidi/page.rb', line 497 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
439 440 441 |
# File 'lib/puppeteer/bidi/page.rb', line 439 def evaluate(script, *args) main_frame.evaluate(script, *args) end |
#evaluate_handle(script, *args) ⇒ JSHandle
Evaluate JavaScript and return a handle to the result
447 448 449 |
# File 'lib/puppeteer/bidi/page.rb', line 447 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.
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 |
# File 'lib/puppeteer/bidi/page.rb', line 1295 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.
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 |
# File 'lib/puppeteer/bidi/page.rb', line 1321 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
540 541 542 543 544 545 546 547 548 549 |
# File 'lib/puppeteer/bidi/page.rb', line 540 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
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 |
# File 'lib/puppeteer/bidi/page.rb', line 682 def focused_frame assert_not_closed # Evaluate in main frame to find the focused window handle = main_frame.evaluate_handle(" () => {\n let win = window;\n while (\n win.document.activeElement instanceof win.HTMLIFrameElement ||\n win.document.activeElement instanceof win.HTMLFrameElement\n ) {\n if (win.document.activeElement.contentWindow === null) {\n break;\n }\n win = win.document.activeElement.contentWindow;\n }\n return win;\n }\n JS\n\n # Get the remote value (should be a window object)\n remote_value = handle.remote_value\n handle.dispose\n\n unless remote_value['type'] == 'window'\n raise \"Expected window type, got \#{remote_value['type']}\"\n end\n\n # Find the frame with matching context ID\n context_id = remote_value['value']['context']\n frame = frames.find { |f| f.browsing_context.id == context_id }\n\n raise \"Could not find frame with context \#{context_id}\" unless frame\n\n frame\nend\n") |
#frames ⇒ Array[Frame]
Get all frames (main frame + all nested child frames) Following Puppeteer's pattern of returning all frames recursively
722 723 724 |
# File 'lib/puppeteer/bidi/page.rb', line 722 def frames collect_frames(main_frame) end |
#get_default_navigation_timeout ⇒ Numeric
Get the current default navigation timeout in milliseconds.
797 798 799 |
# File 'lib/puppeteer/bidi/page.rb', line 797 def end |
#get_default_timeout ⇒ Numeric
Get the current default timeout in milliseconds.
791 792 793 |
# File 'lib/puppeteer/bidi/page.rb', line 791 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.
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 1493 |
# File 'lib/puppeteer/bidi/page.rb', line 1388 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
1357 1358 1359 |
# File 'lib/puppeteer/bidi/page.rb', line 1357 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
1365 1366 1367 |
# File 'lib/puppeteer/bidi/page.rb', line 1365 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
158 159 160 161 162 |
# File 'lib/puppeteer/bidi/page.rb', line 158 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
524 525 526 |
# File 'lib/puppeteer/bidi/page.rb', line 524 def hover(selector) main_frame.hover(selector) end |
#javascript_enabled? ⇒ Boolean
Check if JavaScript is enabled
1349 1350 1351 |
# File 'lib/puppeteer/bidi/page.rb', line 1349 def javascript_enabled? @browsing_context.javascript_enabled? end |
#js_typeof(value) ⇒ Object
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 |
# File 'lib/puppeteer/bidi/page.rb', line 1711 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
734 735 736 |
# File 'lib/puppeteer/bidi/page.rb', line 734 def keyboard @keyboard ||= Keyboard.new(self, @browsing_context) end |
#locator(selector = nil, function: nil) ⇒ Locator
Create a locator for a selector or function.
469 470 471 472 473 474 475 476 477 478 479 480 481 |
# File 'lib/puppeteer/bidi/page.rb', line 469 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
604 605 606 |
# File 'lib/puppeteer/bidi/page.rb', line 604 def main_frame @main_frame ||= Frame.from(self, @browsing_context) end |
#mouse ⇒ Mouse
Get the mouse instance
728 729 730 |
# File 'lib/puppeteer/bidi/page.rb', line 728 def mouse @mouse ||= Mouse.new(@browsing_context) end |
#network_interception_enabled? ⇒ Boolean
141 142 143 |
# File 'lib/puppeteer/bidi/page.rb', line 141 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.
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 |
# File 'lib/puppeteer/bidi/page.rb', line 1609 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| ... } ⇒ Page
Remove an event listener
117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
# File 'lib/puppeteer/bidi/page.rb', line 117 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 @emitter.off(event, &(wrapper || block)) else @emitter.off(event, &block) end self end |
#on(event) {|arg0| ... } ⇒ Page
Register an event listener
98 99 100 101 102 |
# File 'lib/puppeteer/bidi/page.rb', line 98 def on(event, &block) listener = event.to_sym == :request ? request_listener_for(block) : block @emitter.on(event, &listener) self end |
#once(event) {|arg0| ... } ⇒ Page
Register a one-time event listener
108 109 110 111 |
# File 'lib/puppeteer/bidi/page.rb', line 108 def once(event, &block) @emitter.once(event, &block) self end |
#parse_cookie_url(cookie_url) ⇒ URI::Generic?
1514 1515 1516 1517 1518 1519 1520 |
# File 'lib/puppeteer/bidi/page.rb', line 1514 def () return nil if .nil? || .empty? URI.parse() rescue URI::InvalidURIError nil end |
#parse_cookie_url_strict(cookie_url) ⇒ Object
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 |
# File 'lib/puppeteer/bidi/page.rb', line 1522 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
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 1675 |
# File 'lib/puppeteer/bidi/page.rb', line 1623 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
1702 1703 1704 1705 1706 1707 1708 1709 |
# File 'lib/puppeteer/bidi/page.rb', line 1702 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.
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 |
# File 'lib/puppeteer/bidi/page.rb', line 345 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]
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 |
# File 'lib/puppeteer/bidi/page.rb', line 1550 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
454 455 456 |
# File 'lib/puppeteer/bidi/page.rb', line 454 def query_selector(selector) main_frame.query_selector(selector) end |
#query_selector_all(selector) ⇒ Array[ElementHandle]
Query for all elements matching the selector
461 462 463 |
# File 'lib/puppeteer/bidi/page.rb', line 461 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.
619 620 621 622 623 624 625 626 627 628 |
# File 'lib/puppeteer/bidi/page.rb', line 619 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.
1342 1343 1344 1345 |
# File 'lib/puppeteer/bidi/page.rb', line 1342 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.
1310 1311 1312 1313 |
# File 'lib/puppeteer/bidi/page.rb', line 1310 def remove_script_to_evaluate_on_new_document(identifier) assert_not_closed @browsing_context.remove_preload_script(identifier).wait end |
#request_listener_for(listener) ⇒ Object
1371 1372 1373 1374 1375 1376 1377 |
# File 'lib/puppeteer/bidi/page.rb', line 1371 def request_listener_for(listener) @request_handlers[listener] ||= lambda do |request| request.enqueue_intercept_action do listener.call(request) end end end |
#screenshot(path: nil, type: 'png', full_page: false, clip: nil, capture_beyond_viewport: true) ⇒ String
Take a screenshot
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 |
# File 'lib/puppeteer/bidi/page.rb', line 180 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(" (() => {\n const element = document.documentElement;\n return {\n width: element.scrollWidth,\n height: element.scrollHeight\n };\n })()\n JS\n\n # Save original viewport (could be nil)\n original_viewport = viewport\n\n # If no viewport is set, save current window size\n unless original_viewport\n original_size = evaluate('({ width: window.innerWidth, height: window.innerHeight })')\n original_viewport = { width: original_size['width'].to_i, height: original_size['height'].to_i }\n end\n\n # Set viewport to full page size while preserving optional emulation flags.\n temporary_viewport = {\n width: scroll_dimensions['width'].to_i,\n height: scroll_dimensions['height'].to_i\n }\n if original_viewport\n temporary_viewport[:device_scale_factor] = original_viewport[:device_scale_factor]\n temporary_viewport[:has_touch] = original_viewport[:has_touch]\n temporary_viewport[:is_mobile] = original_viewport[:is_mobile]\n temporary_viewport[:is_landscape] = original_viewport[:is_landscape]\n end\n set_viewport(\n width: temporary_viewport.fetch(:width),\n height: temporary_viewport.fetch(:height),\n device_scale_factor: temporary_viewport[:device_scale_factor],\n has_touch: temporary_viewport[:has_touch],\n is_mobile: temporary_viewport[:is_mobile],\n is_landscape: temporary_viewport[:is_landscape]\n )\n\n begin\n # Capture screenshot with viewport origin\n options[:origin] = 'viewport'\n data = @browsing_context.capture_screenshot(**options).wait\n ensure\n # Restore original viewport\n if original_viewport\n set_viewport(\n width: original_viewport.fetch(:width),\n height: original_viewport.fetch(:height),\n device_scale_factor: original_viewport[:device_scale_factor],\n has_touch: original_viewport[:has_touch],\n is_mobile: original_viewport[:is_mobile],\n is_landscape: original_viewport[:is_landscape]\n )\n end\n end\n\n # Save to file if path is provided\n if path\n dir = File.dirname(path)\n FileUtils.mkdir_p(dir) unless Dir.exist?(dir)\n File.binwrite(path, Base64.decode64(data))\n end\n\n return data\n else\n # Capture full document with origin: document\n options[:origin] = 'document'\n end\n elsif !clip\n # If not fullPage and no clip, force captureBeyondViewport to false\n capture_beyond_viewport = false\n end\n\n # Add clip region if specified\n if clip\n # Set origin based on captureBeyondViewport (only when clip is specified)\n if capture_beyond_viewport\n options[:origin] = 'document'\n else\n options[:origin] = 'viewport'\n end\n box = clip.dup\n\n # When captureBeyondViewport is false, convert document coordinates to viewport coordinates\n unless capture_beyond_viewport\n # Get viewport offset\n page_left = evaluate('window.visualViewport.pageLeft')\n page_top = evaluate('window.visualViewport.pageTop')\n\n # Convert to viewport coordinates\n box = {\n x: clip[:x] - page_left,\n y: clip[:y] - page_top,\n width: clip[:width],\n height: clip[:height]\n }\n end\n\n clip_x, clip_y, clip_width, clip_height = process_clip(\n clip_x: box[:x],\n clip_y: box[:y],\n clip_width: box[:width],\n clip_height: box[:height],\n )\n options[:clip] = {\n type: 'box',\n x: clip_x,\n y: clip_y,\n width: clip_width,\n height: clip_height\n }\n end\n\n # Get screenshot data from browsing context\n data = @browsing_context.capture_screenshot(**options).wait\n\n # Save to file if path is provided\n if path\n # Ensure directory exists\n dir = File.dirname(path)\n FileUtils.mkdir_p(dir) unless Dir.exist?(dir)\n\n # data is base64 encoded, decode and write\n File.binwrite(path, Base64.decode64(data))\n end\n\n data\nend\n") |
#select(selector, *values) ⇒ Array[String]
Select options on a
533 534 535 |
# File 'lib/puppeteer/bidi/page.rb', line 533 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.
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 |
# File 'lib/puppeteer/bidi/page.rb', line 1589 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.
674 675 676 677 678 |
# File 'lib/puppeteer/bidi/page.rb', line 674 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
169 170 171 |
# File 'lib/puppeteer/bidi/page.rb', line 169 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.
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 |
# File 'lib/puppeteer/bidi/page.rb', line 919 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 \"#{normalized_cookie["name"]}\"" end if .start_with?("data:") raise ArgumentError, "Data URL page can not have cookie \"#{normalized_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.
771 772 773 774 775 |
# File 'lib/puppeteer/bidi/page.rb', line 771 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).
762 763 764 765 766 |
# File 'lib/puppeteer/bidi/page.rb', line 762 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.
646 647 648 649 650 651 652 653 654 |
# File 'lib/puppeteer/bidi/page.rb', line 646 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
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 |
# File 'lib/puppeteer/bidi/page.rb', line 1207 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
1286 1287 1288 1289 |
# File 'lib/puppeteer/bidi/page.rb', line 1286 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.
633 634 635 636 637 638 639 640 641 |
# File 'lib/puppeteer/bidi/page.rb', line 633 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
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 |
# File 'lib/puppeteer/bidi/page.rb', line 1236 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
1160 1161 1162 1163 1164 1165 1166 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 |
# File 'lib/puppeteer/bidi/page.rb', line 1160 def (width:, height:, device_scale_factor: nil, has_touch: nil, is_mobile: nil, is_landscape: nil) previous_has_touch = ? !![:has_touch] : false current_has_touch = !!has_touch needs_reload = previous_has_touch != current_has_touch = { width: width, height: height } [:device_scale_factor] = device_scale_factor unless device_scale_factor.nil? [:has_touch] = has_touch unless has_touch.nil? [:is_mobile] = is_mobile unless is_mobile.nil? [: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.
610 611 612 |
# File 'lib/puppeteer/bidi/page.rb', line 610 def target @target ||= PageTarget.new(self) end |
#title ⇒ String
Get the page title
553 554 555 |
# File 'lib/puppeteer/bidi/page.rb', line 553 def title evaluate('document.title') end |
#toggle_interception(phases, interception, expected) ⇒ Object
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 |
# File 'lib/puppeteer/bidi/page.rb', line 1533 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
517 518 519 |
# File 'lib/puppeteer/bidi/page.rb', line 517 def type(selector, text, delay: 0) main_frame.type(selector, text, delay: delay) end |
#url ⇒ String
Get the page URL
559 560 561 |
# File 'lib/puppeteer/bidi/page.rb', line 559 def url @browsing_context.url end |
#viewport ⇒ Hash[Symbol, Integer]?
Get current viewport size
1275 1276 1277 |
# File 'lib/puppeteer/bidi/page.rb', line 1275 def end |
#wait_for_file_chooser(timeout: nil, &block) ⇒ void
This method returns an undefined value.
Wait for a file chooser to be opened
1020 1021 1022 1023 1024 1025 1026 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 |
# File 'lib/puppeteer/bidi/page.rb', line 1020 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
744 745 746 |
# File 'lib/puppeteer/bidi/page.rb', line 744 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
806 807 808 |
# File 'lib/puppeteer/bidi/page.rb', line 806 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
1081 1082 1083 1084 1085 1086 1087 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 |
# File 'lib/puppeteer/bidi/page.rb', line 1081 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.
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 |
# File 'lib/puppeteer/bidi/page.rb', line 815 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.
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 |
# File 'lib/puppeteer/bidi/page.rb', line 858 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
755 756 757 |
# File 'lib/puppeteer/bidi/page.rb', line 755 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.
1269 1270 1271 |
# File 'lib/puppeteer/bidi/page.rb', line 1269 def window_id @browsing_context.window_id end |