@@ -148,10 +148,15 @@ function setupGlobalFocusEvents(root?: RootNode) {
148
148
149
149
// Overwrite via assignment does not work in happy dom:
150
150
// https://github.com/capricorn86/happy-dom/issues/1214
151
- Object . defineProperty ( win . HTMLElement . prototype , "focus" , {
152
- configurable : true ,
153
- value : patchedFocus ,
154
- } )
151
+ try {
152
+ Object . defineProperty ( win . HTMLElement . prototype , "focus" , {
153
+ configurable : true ,
154
+ value : patchedFocus ,
155
+ } )
156
+ } catch {
157
+ // Failed to patch - property may be non-configurable or already patched
158
+ // The focus tracking will still work via keyboard/pointer event listeners
159
+ }
155
160
156
161
doc . addEventListener ( "keydown" , handleKeyboardEvent , true )
157
162
doc . addEventListener ( "keyup" , handleKeyboardEvent , true )
@@ -190,11 +195,19 @@ const tearDownWindowFocusTracking = (root?: RootNode, loadListener?: () => void)
190
195
doc . removeEventListener ( "DOMContentLoaded" , loadListener )
191
196
}
192
197
193
- if ( ! listenerMap . has ( win ) ) {
198
+ const listenerData = listenerMap . get ( win )
199
+ if ( ! listenerData ) {
194
200
return
195
201
}
196
202
197
- win . HTMLElement . prototype . focus = listenerMap . get ( win ) ! . focus
203
+ try {
204
+ Object . defineProperty ( win . HTMLElement . prototype , "focus" , {
205
+ configurable : true ,
206
+ value : listenerData . focus ,
207
+ } )
208
+ } catch {
209
+ // Failed to restore - ignore silently
210
+ }
198
211
199
212
doc . removeEventListener ( "keydown" , handleKeyboardEvent , true )
200
213
doc . removeEventListener ( "keyup" , handleKeyboardEvent , true )
0 commit comments