OLD | NEW |
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 function focus(element) { | 5 function focus(element) { |
6 // Focus the target element in order to send keys to it. | 6 // Focus the target element in order to send keys to it. |
7 // First, the currently active element is blurred, if it is different from | 7 // First, the currently active element is blurred, if it is different from |
8 // the target element. We do not want to blur an element unnecessarily, | 8 // the target element. We do not want to blur an element unnecessarily, |
9 // because this may cause us to lose the current cursor position in the | 9 // because this may cause us to lose the current cursor position in the |
10 // element. | 10 // element. |
(...skipping 20 matching lines...) Expand all Loading... |
31 if (element != prevActiveElement && element.value && | 31 if (element != prevActiveElement && element.value && |
32 element.value.length && element.setSelectionRange) { | 32 element.value.length && element.setSelectionRange) { |
33 try { | 33 try { |
34 element.setSelectionRange(element.value.length, element.value.length); | 34 element.setSelectionRange(element.value.length, element.value.length); |
35 } catch (error) { | 35 } catch (error) { |
36 if (!(error instanceof TypeError) && !(error instanceof DOMException && | 36 if (!(error instanceof TypeError) && !(error instanceof DOMException && |
37 error.code == DOMException.INVALID_STATE_ERR)) | 37 error.code == DOMException.INVALID_STATE_ERR)) |
38 throw error; | 38 throw error; |
39 } | 39 } |
40 } | 40 } |
41 if (element != doc.activeElement) | 41 |
| 42 var activeElement = doc.activeElement; |
| 43 // If the element is in a shadow DOM, then as far as the document is |
| 44 // concerned, the shadow host is the active element. We need to go through the |
| 45 // tree of shadow DOMs to check that the element we gave focus to is now |
| 46 // active. |
| 47 if (element != activeElement) { |
| 48 var shadowRoot = activeElement.shadowRoot; |
| 49 while (shadowRoot) { |
| 50 var activeElement = shadowRoot.activeElement; |
| 51 if (element == activeElement) { |
| 52 // the shadow DOM's active element is our requested element. We're good. |
| 53 break; |
| 54 } |
| 55 // The shadow DOM's active element isn't our requested element, check to |
| 56 // see if there's a nested shadow DOM. |
| 57 shadowRoot = activeElement.shadowRoot; |
| 58 } |
| 59 } |
| 60 if (element != activeElement) |
42 throw new Error('cannot focus element'); | 61 throw new Error('cannot focus element'); |
43 } | 62 } |
OLD | NEW |