Class: Puppeteer::Bidi::Page

Inherits:
Object
  • Object
show all
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 =

Returns:

{
  "px" => 1,
  "in" => 96,
  "cm" => 37.8,
  "mm" => 3.78
}.freeze
PAPER_FORMATS =

Returns:

{
  "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

Instance Method Summary collapse

Parameters:

Returns:



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.

Parameters:

Returns:



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.

Parameters:



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

Parameters:



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

This method returns an undefined value.

Set cookies for the current page.

Parameters:



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 set_cookie(*cookies, **cookie)
  assert_not_closed

  cookies = cookies.dup
  cookies << cookie unless cookie.empty?

  page_url = url
  page_url_starts_with_http = page_url&.start_with?("http")

  cookies.each do |raw_cookie|
    normalized_cookie = CookieUtils.normalize_cookie_input(raw_cookie)
    cookie_url = normalized_cookie["url"].to_s
    if cookie_url.empty? && page_url_starts_with_http
      cookie_url = page_url
    end

    if cookie_url == "about:blank"
      raise ArgumentError, "Blank page can not have cookie \"#{normalized_cookie["name"]}\""
    end
    if cookie_url.start_with?("data:")
      raise ArgumentError, "Data URL page can not have cookie \"#{normalized_cookie["name"]}\""
    end

    partition_key = normalized_cookie["partitionKey"]
    if !partition_key.nil? && !partition_key.is_a?(String)
      raise ArgumentError, "BiDi only allows domain partition keys"
    end

    normalized_url = parse_cookie_url(cookie_url)
    domain = normalized_cookie["domain"] || normalized_url&.host
    if domain.nil?
      raise ArgumentError, "At least one of the url and domain needs to be specified"
    end

    bidi_cookie = {
      "domain" => domain,
      "name" => normalized_cookie["name"],
      "value" => { "type" => "string", "value" => normalized_cookie["value"] },
    }
    bidi_cookie["path"] = normalized_cookie["path"] if normalized_cookie.key?("path")
    bidi_cookie["httpOnly"] = normalized_cookie["httpOnly"] if normalized_cookie.key?("httpOnly")
    bidi_cookie["secure"] = normalized_cookie["secure"] if normalized_cookie.key?("secure")
    if normalized_cookie.key?("sameSite") && !normalized_cookie["sameSite"].nil?
      bidi_cookie["sameSite"] = CookieUtils.convert_cookies_same_site_cdp_to_bidi(
        normalized_cookie["sameSite"]
      )
    end
    expiry = CookieUtils.convert_cookies_expiry_cdp_to_bidi(normalized_cookie["expires"])
    bidi_cookie["expiry"] = expiry unless expiry.nil?
    bidi_cookie.merge!(CookieUtils.cdp_specific_cookie_properties_from_puppeteer_to_bidi(
                         normalized_cookie,
                         "sourceScheme",
                         "priority",
                         "url"
                       ))

    if partition_key
      @browser_context.user_context.set_cookie(bidi_cookie, source_origin: partition_key).wait
    else
      @browsing_context.set_cookie(bidi_cookie).wait
    end
  end
end

#set_default_navigation_timeout(timeout) ⇒ void Also known as: default_navigation_timeout=

This method returns an undefined value.

Set the default navigation timeout.

Parameters:



771
772
773
774
775
# File 'lib/puppeteer/bidi/page.rb', line 771

def set_default_navigation_timeout(timeout)
  raise ArgumentError, 'timeout must be a non-negative number' unless timeout.is_a?(Numeric) && timeout >= 0

  @timeout_settings.set_default_navigation_timeout(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).

Parameters:



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.

Parameters:



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

Parameters:



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

Parameters:



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.

Parameters:



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

Parameters:



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)
    options = user_agent.transform_keys(&:to_sym)
    parsed_user_agent = options.key?(:userAgent) ? options[:userAgent] : options[:user_agent]
    client_hints = options[:userAgentMetadata] || options[:user_agent_metadata]
    platform = options[: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

Parameters:



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 set_viewport(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.set_viewport(
    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.message.include?('unknown command') ||
                          error.message.include?('unsupported operation') ||
                          error.message.include?('emulation.setTouchOverride')
      raise unless unsupported_error
    end
    reload
  end
end

#targetPageTarget

Get the target associated with this page.

Returns:



610
611
612
# File 'lib/puppeteer/bidi/page.rb', line 610

def target
  @target ||= PageTarget.new(self)
end

#titleString

Get the page title

Returns:



553
554
555
# File 'lib/puppeteer/bidi/page.rb', line 553

def title
  evaluate('document.title')
end

#toggle_interception(phases, interception, expected) ⇒ Object

Parameters:

Returns:



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

Parameters:



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

#urlString

Get the page URL

Returns:



559
560
561
# File 'lib/puppeteer/bidi/page.rb', line 559

def url
  @browsing_context.url
end

#viewportHash[Symbol, Integer]?

Get current viewport size

Returns:



1275
1276
1277
# File 'lib/puppeteer/bidi/page.rb', line 1275

def viewport
  @viewport
end

#wait_for_file_chooser(timeout: nil, &block) ⇒ void

This method returns an undefined value.

Wait for a file chooser to be opened

Parameters:



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

Parameters:



744
745
746
# File 'lib/puppeteer/bidi/page.rb', line 744

def wait_for_function(page_function, options = {}, *args, &block)
  main_frame.wait_for_function(page_function, options, *args, &block)
end

#wait_for_navigation(timeout: nil, wait_until: 'load', &block) ⇒ void

This method returns an undefined value.

Wait for navigation to complete

Parameters:



806
807
808
# File 'lib/puppeteer/bidi/page.rb', line 806

def wait_for_navigation(timeout: nil, wait_until: 'load', &block)
  main_frame.wait_for_navigation(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

Parameters:



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.

Parameters:



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.

Parameters:



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

Parameters:



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_idString

Get the client window ID for this page.

Returns:



1269
1270
1271
# File 'lib/puppeteer/bidi/page.rb', line 1269

def window_id
  @browsing_context.window_id
end