@@ -21,6 +21,9 @@ class Selenium::WebDriver::Element
21
21
# To extend Appium related SearchContext into ::Selenium::WebDriver::Element
22
22
include ::Appium ::Core ::Base ::SearchContext
23
23
24
+ # TODO: Probably can remove own TakesScreenshot since Selenium 4
25
+ include ::Appium ::Core ::Base ::TakesScreenshot
26
+
24
27
# Returns the value of attributes like below. Read each platform to know more details.
25
28
#
26
29
# uiautomator2: https://github.com/appium/appium-uiautomator2-server/blob/203cc7e57ce477f3cff5d95b135d1b3450a6033a/app/src/main/java/io/appium/uiautomator2/utils/Attribute.java#L19
@@ -99,6 +102,56 @@ def location_rel(driver)
99
102
w = driver . window_size
100
103
::Selenium ::WebDriver ::Point . new "#{ center_x } / #{ w . width . to_f } " , "#{ center_y } / #{ w . height . to_f } "
101
104
end
105
+
106
+ # Return an element screenshot as base64
107
+ #
108
+ # @return String Base 64 encoded string
109
+ #
110
+ # @example
111
+ #
112
+ # element.screenshot #=> "iVBORw0KGgoAAAANSUhEUgAABDgAAAB+CAIAAABOPDa6AAAAAX"
113
+ #
114
+ def screenshot
115
+ bridge . take_element_screenshot ( self )
116
+ end
117
+
118
+ # Return an element screenshot in the given format
119
+ #
120
+ # @param [:base64, :png] format
121
+ # @return String screenshot
122
+ #
123
+ # @example
124
+ #
125
+ # element.screenshot_as :base64 #=> "iVBORw0KGgoAAAANSUhEUgAABDgAAAB+CAIAAABOPDa6AAAAAX"
126
+ #
127
+ def screenshot_as ( format )
128
+ case format
129
+ when :base64
130
+ bridge . take_element_screenshot ( self )
131
+ when :png
132
+ bridge . take_element_screenshot ( self ) . unpack ( 'm' ) [ 0 ]
133
+ else
134
+ raise Core ::Error ::UnsupportedOperationError , "unsupported format: #{ format . inspect } "
135
+ end
136
+ end
137
+
138
+ # Save an element screenshot to the given path
139
+ #
140
+ # @param [String] png_path A path to save the screenshot
141
+ # @return [File] Path to the element screenshot.
142
+ #
143
+ # @example
144
+ #
145
+ # element.save_screenshot("fine_name.png")
146
+ #
147
+ def save_screenshot ( png_path )
148
+ extension = File . extname ( png_path ) . downcase
149
+ if extension != '.png'
150
+ ::Appium ::Logger . warn 'name used for saved screenshot does not match file type. ' \
151
+ 'It should end with .png extension'
152
+ end
153
+ File . open ( png_path , 'wb' ) { |f | f << screenshot_as ( :png ) }
154
+ end
102
155
end
103
156
end # module Core
104
157
end # module Appium
0 commit comments