Best Selenium code snippet using Selenium.WebDriver.Remote.clear_local_storage
driver.rb
Source:driver.rb
...3require 'English'4class Capybara::Selenium::Driver < Capybara::Driver::Base5 DEFAULT_OPTIONS = {6 browser: :firefox,7 clear_local_storage: nil,8 clear_session_storage: nil9 }.freeze10 SPECIAL_OPTIONS = %i[browser clear_local_storage clear_session_storage timeout].freeze11 attr_reader :app, :options12 def self.load_selenium13 require 'selenium-webdriver'14 warn "Warning: You're using an unsupported version of selenium-webdriver, please upgrade." if Gem.loaded_specs['selenium-webdriver'].version < Gem::Version.new('3.5.0')15 rescue LoadError => err16 raise err if err.message !~ /selenium-webdriver/17 raise LoadError, "Capybara's selenium driver is unable to load `selenium-webdriver`, please install the gem and add `gem 'selenium-webdriver'` to your Gemfile if you are using bundler."18 end19 def browser20 @browser ||= begin21 if options[:timeout]22 options[:http_client] ||= Selenium::WebDriver::Remote::Http::Default.new(read_timeout: options[:timeout])23 end24 processed_options = options.reject { |key, _val| SPECIAL_OPTIONS.include?(key) }25 Selenium::WebDriver.for(options[:browser], processed_options).tap do |driver|26 specialize_driver(driver)27 setup_exit_handler28 end29 end30 @browser31 end32 def initialize(app, **options)33 self.class.load_selenium34 @app = app35 @browser = nil36 @exit_status = nil37 @frame_handles = Hash.new { |hash, handle| hash[handle] = [] }38 @options = DEFAULT_OPTIONS.merge(options)39 @node_class = ::Capybara::Selenium::Node40 end41 def visit(path)42 browser.navigate.to(path)43 end44 def refresh45 browser.navigate.refresh46 end47 def go_back48 browser.navigate.back49 end50 def go_forward51 browser.navigate.forward52 end53 def html54 browser.page_source55 end56 def title57 browser.title58 end59 def current_url60 browser.current_url61 end62 def find_xpath(selector)63 browser.find_elements(:xpath, selector).map(&method(:build_node))64 end65 def find_css(selector)66 browser.find_elements(:css, selector).map(&method(:build_node))67 end68 def wait?; true; end69 def needs_server?; true; end70 def execute_script(script, *args)71 browser.execute_script(script, *native_args(args))72 end73 def evaluate_script(script, *args)74 result = execute_script("return #{script}", *args)75 unwrap_script_result(result)76 end77 def evaluate_async_script(script, *args)78 browser.manage.timeouts.script_timeout = Capybara.default_max_wait_time79 result = browser.execute_async_script(script, *native_args(args))80 unwrap_script_result(result)81 end82 def save_screenshot(path, **_options)83 browser.save_screenshot(path)84 end85 def reset!86 # Use instance variable directly so we avoid starting the browser just to reset the session87 return unless @browser88 navigated = false89 timer = Capybara::Helpers.timer(expire_in: 10)90 begin91 # Only trigger a navigation if we haven't done it already, otherwise it92 # can trigger an endless series of unload modals93 reset_browser_state unless navigated94 navigated = true95 # Ensure the page is empty and trigger an UnhandledAlertError for any modals that appear during unload96 wait_for_empty_page(timer)97 rescue Selenium::WebDriver::Error::UnhandledAlertError, Selenium::WebDriver::Error::UnexpectedAlertOpenError98 # This error is thrown if an unhandled alert is on the page99 # Firefox appears to automatically dismiss this alert, chrome does not100 # We'll try to accept it101 accept_unhandled_reset_alert102 # try cleaning up the browser again103 retry104 end105 end106 def switch_to_frame(frame)107 handles = @frame_handles[current_window_handle]108 case frame109 when :top110 handles.clear111 browser.switch_to.default_content112 when :parent113 handles.pop114 browser.switch_to.parent_frame115 else116 handles << frame.native117 browser.switch_to.frame(frame.native)118 end119 end120 def current_window_handle121 browser.window_handle122 end123 def window_size(handle)124 within_given_window(handle) do125 size = browser.manage.window.size126 [size.width, size.height]127 end128 end129 def resize_window_to(handle, width, height)130 within_given_window(handle) do131 browser.manage.window.resize_to(width, height)132 end133 end134 def maximize_window(handle)135 within_given_window(handle) do136 browser.manage.window.maximize137 end138 sleep 0.1 # work around for https://code.google.com/p/selenium/issues/detail?id=7405139 end140 def fullscreen_window(handle)141 within_given_window(handle) do142 browser.manage.window.full_screen143 end144 end145 def close_window(handle)146 raise ArgumentError, 'Not allowed to close the primary window' if handle == window_handles.first147 within_given_window(handle) do148 browser.close149 end150 end151 def window_handles152 browser.window_handles153 end154 def open_new_window155 browser.execute_script('window.open();')156 end157 def switch_to_window(handle)158 browser.switch_to.window handle159 end160 def accept_modal(_type, **options)161 yield if block_given?162 modal = find_modal(options)163 modal.send_keys options[:with] if options[:with]164 message = modal.text165 modal.accept166 message167 end168 def dismiss_modal(_type, **options)169 yield if block_given?170 modal = find_modal(options)171 message = modal.text172 modal.dismiss173 message174 end175 def quit176 @browser&.quit177 rescue Selenium::WebDriver::Error::SessionNotCreatedError, Errno::ECONNREFUSED # rubocop:disable Lint/HandleExceptions178 # Browser must have already gone179 rescue Selenium::WebDriver::Error::UnknownError => err180 unless silenced_unknown_error_message?(err.message) # Most likely already gone181 # probably already gone but not sure - so warn182 warn "Ignoring Selenium UnknownError during driver quit: #{err.message}"183 end184 ensure185 @browser = nil186 end187 def invalid_element_errors188 [189 ::Selenium::WebDriver::Error::StaleElementReferenceError,190 ::Selenium::WebDriver::Error::UnhandledError,191 ::Selenium::WebDriver::Error::ElementNotVisibleError,192 ::Selenium::WebDriver::Error::InvalidSelectorError, # Work around a chromedriver go_back/go_forward race condition193 ::Selenium::WebDriver::Error::ElementNotInteractableError,194 ::Selenium::WebDriver::Error::ElementClickInterceptedError,195 ::Selenium::WebDriver::Error::InvalidElementStateError,196 ::Selenium::WebDriver::Error::ElementNotSelectableError,197 ::Selenium::WebDriver::Error::ElementNotSelectableError,198 ::Selenium::WebDriver::Error::NoSuchElementError, # IE199 ::Selenium::WebDriver::Error::InvalidArgumentError # IE200 ]201 end202 def no_such_window_error203 Selenium::WebDriver::Error::NoSuchWindowError204 end205private206 def native_args(args)207 args.map { |arg| arg.is_a?(Capybara::Selenium::Node) ? arg.native : arg }208 end209 def clear_browser_state210 delete_all_cookies211 clear_storage212 rescue Selenium::WebDriver::Error::UnhandledError # rubocop:disable Lint/HandleExceptions213 # delete_all_cookies fails when we've previously gone214 # to about:blank, so we rescue this error and do nothing215 # instead.216 end217 def delete_all_cookies218 @browser.manage.delete_all_cookies219 end220 def clear_storage221 clear_session_storage unless options[:clear_session_storage] == false222 clear_local_storage unless options[:clear_local_storage] == false223 rescue Selenium::WebDriver::Error::JavascriptError # rubocop:disable Lint/HandleExceptions224 # session/local storage may not be available if on non-http pages (e.g. about:blank)225 end226 def clear_session_storage227 if @browser.respond_to? :session_storage228 @browser.session_storage.clear229 else230 warn 'sessionStorage clear requested but is not supported by this driver' unless options[:clear_session_storage].nil?231 end232 end233 def clear_local_storage234 if @browser.respond_to? :local_storage235 @browser.local_storage.clear236 else237 warn 'localStorage clear requested but is not supported by this driver' unless options[:clear_local_storage].nil?238 end239 end240 def navigate_with_accept(url)241 @browser.navigate.to(url)242 sleep 0.1 # slight wait for alert243 @browser.switch_to.alert.accept244 rescue modal_error # rubocop:disable Lint/HandleExceptions245 # alert now gone, should mean navigation happened246 end247 def modal_error248 Selenium::WebDriver::Error::NoSuchAlertError249 end250 def within_given_window(handle)251 original_handle = current_window_handle...
clear_local_storage
Using AI Code Generation
1driver.get("https://www.google.com")2driver.get("https://www.google.com")3driver.get("https://www.google.com")
clear_local_storage
Using AI Code Generation
1driver.execute_script("localStorage.clear();")2driver.execute_script("sessionStorage.clear();")3driver.execute_script("window.localStorage.clear();")4driver.execute_script("window.sessionStorage.clear();")
clear_local_storage
Using AI Code Generation
1driver.execute_script("localStorage.clear();")2driver.execute_script("sessionStorage.clear();")3driver.execute_script("window.localStorage.clear();")4driver.execute_script("window.sessionStorage.clear();")
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!