|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# Licensed to the Software Freedom Conservancy (SFC) under one |
| 4 | +# or more contributor license agreements. See the NOTICE file |
| 5 | +# distributed with this work for additional information |
| 6 | +# regarding copyright ownership. The SFC licenses this file |
| 7 | +# to you under the Apache License, Version 2.0 (the |
| 8 | +# "License"); you may not use this file except in compliance |
| 9 | +# with the License. You may obtain a copy of the License at |
| 10 | +# |
| 11 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | +# |
| 13 | +# Unless required by applicable law or agreed to in writing, |
| 14 | +# software distributed under the License is distributed on an |
| 15 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 16 | +# KIND, either express or implied. See the License for the |
| 17 | +# specific language governing permissions and limitations |
| 18 | +# under the License. |
| 19 | + |
| 20 | +module Selenium |
| 21 | + module WebDriver |
| 22 | + class BiDi |
| 23 | + class LogHandler |
| 24 | + ConsoleLogEntry = BiDi::Struct.new(:level, :text, :timestamp, :method, :args, :type) |
| 25 | + JavaScriptLogEntry = BiDi::Struct.new(:level, :text, :timestamp, :stack_trace, :type) |
| 26 | + |
| 27 | + def initialize(bidi) |
| 28 | + @bidi = bidi |
| 29 | + @log_entry_subscribed = false |
| 30 | + end |
| 31 | + |
| 32 | + # @return [int] id of the handler |
| 33 | + def add_message_handler(type) |
| 34 | + subscribe_log_entry unless @log_entry_subscribed |
| 35 | + @bidi.add_callback('log.entryAdded') do |params| |
| 36 | + if params['type'] == type |
| 37 | + log_entry_klass = type == 'console' ? ConsoleLogEntry : JavaScriptLogEntry |
| 38 | + yield(log_entry_klass.new(**params)) |
| 39 | + end |
| 40 | + end |
| 41 | + end |
| 42 | + |
| 43 | + # @param [int] id of the handler previously added |
| 44 | + def remove_message_handler(id) |
| 45 | + @bidi.remove_callback('log.entryAdded', id) |
| 46 | + unsubscribe_log_entry if @log_entry_subscribed && @bidi.callbacks['log.entryAdded'].empty? |
| 47 | + end |
| 48 | + |
| 49 | + private |
| 50 | + |
| 51 | + def subscribe_log_entry |
| 52 | + @bidi.session.subscribe('log.entryAdded') |
| 53 | + @log_entry_subscribed = true |
| 54 | + end |
| 55 | + |
| 56 | + def unsubscribe_log_entry |
| 57 | + @bidi.session.unsubscribe('log.entryAdded') |
| 58 | + @log_entry_subscribed = false |
| 59 | + end |
| 60 | + end # LogHandler |
| 61 | + end # Bidi |
| 62 | + end # WebDriver |
| 63 | +end # Selenium |
0 commit comments