1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/autofill/content/renderer/form_autofill_util.h"
9 #include "base/command_line.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_vector.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "components/autofill/core/common/autofill_data_validation.h"
15 #include "components/autofill/core/common/autofill_switches.h"
16 #include "components/autofill/core/common/form_data.h"
17 #include "components/autofill/core/common/form_field_data.h"
18 #include "third_party/WebKit/public/platform/WebString.h"
19 #include "third_party/WebKit/public/platform/WebVector.h"
20 #include "third_party/WebKit/public/web/WebDocument.h"
21 #include "third_party/WebKit/public/web/WebElement.h"
22 #include "third_party/WebKit/public/web/WebElementCollection.h"
23 #include "third_party/WebKit/public/web/WebFormControlElement.h"
24 #include "third_party/WebKit/public/web/WebFormElement.h"
25 #include "third_party/WebKit/public/web/WebInputElement.h"
26 #include "third_party/WebKit/public/web/WebLabelElement.h"
27 #include "third_party/WebKit/public/web/WebLocalFrame.h"
28 #include "third_party/WebKit/public/web/WebNode.h"
29 #include "third_party/WebKit/public/web/WebNodeList.h"
30 #include "third_party/WebKit/public/web/WebOptionElement.h"
31 #include "third_party/WebKit/public/web/WebSelectElement.h"
32 #include "third_party/WebKit/public/web/WebTextAreaElement.h"
34 using blink::WebDocument
;
35 using blink::WebElement
;
36 using blink::WebElementCollection
;
37 using blink::WebFormControlElement
;
38 using blink::WebFormElement
;
39 using blink::WebFrame
;
40 using blink::WebInputElement
;
41 using blink::WebLabelElement
;
43 using blink::WebNodeList
;
44 using blink::WebOptionElement
;
45 using blink::WebSelectElement
;
46 using blink::WebTextAreaElement
;
47 using blink::WebString
;
48 using blink::WebVector
;
53 // A bit field mask for FillForm functions to not fill some fields.
54 enum FieldFilterMask
{
56 FILTER_DISABLED_ELEMENTS
= 1 << 0,
57 FILTER_READONLY_ELEMENTS
= 1 << 1,
58 FILTER_NON_FOCUSABLE_ELEMENTS
= 1 << 2,
59 FILTER_ALL_NON_EDITABLE_ELEMENTS
= FILTER_DISABLED_ELEMENTS
|
60 FILTER_READONLY_ELEMENTS
|
61 FILTER_NON_FOCUSABLE_ELEMENTS
,
64 RequirementsMask
ExtractionRequirements() {
65 return base::CommandLine::ForCurrentProcess()->HasSwitch(
66 switches::kRespectAutocompleteOffForAutofill
)
67 ? REQUIRE_AUTOCOMPLETE
71 void TruncateString(base::string16
* str
, size_t max_length
) {
72 if (str
->length() > max_length
)
73 str
->resize(max_length
);
76 bool IsOptionElement(const WebElement
& element
) {
77 CR_DEFINE_STATIC_LOCAL(WebString
, kOption
, ("option"));
78 return element
.hasHTMLTagName(kOption
);
81 bool IsScriptElement(const WebElement
& element
) {
82 CR_DEFINE_STATIC_LOCAL(WebString
, kScript
, ("script"));
83 return element
.hasHTMLTagName(kScript
);
86 bool IsNoScriptElement(const WebElement
& element
) {
87 CR_DEFINE_STATIC_LOCAL(WebString
, kNoScript
, ("noscript"));
88 return element
.hasHTMLTagName(kNoScript
);
91 bool HasTagName(const WebNode
& node
, const blink::WebString
& tag
) {
92 return node
.isElementNode() && node
.toConst
<WebElement
>().hasHTMLTagName(tag
);
95 bool IsAutofillableElement(const WebFormControlElement
& element
) {
96 const WebInputElement
* input_element
= toWebInputElement(&element
);
97 return IsAutofillableInputElement(input_element
) ||
98 IsSelectElement(element
) ||
99 IsTextAreaElement(element
);
102 bool IsElementInControlElementSet(
103 const WebElement
& element
,
104 const std::vector
<WebFormControlElement
>& control_elements
) {
105 if (!element
.isFormControlElement())
107 const WebFormControlElement form_control_element
=
108 element
.toConst
<WebFormControlElement
>();
109 return std::find(control_elements
.begin(),
110 control_elements
.end(),
111 form_control_element
) != control_elements
.end();
114 bool IsElementInsideFormOrFieldSet(const WebElement
& element
) {
115 for (WebNode parent_node
= element
.parentNode();
116 !parent_node
.isNull();
117 parent_node
= parent_node
.parentNode()) {
118 if (!parent_node
.isElementNode())
121 WebElement cur_element
= parent_node
.to
<WebElement
>();
122 if (cur_element
.hasHTMLTagName("form") ||
123 cur_element
.hasHTMLTagName("fieldset")) {
130 // Check whether the given field satisfies the REQUIRE_AUTOCOMPLETE requirement.
131 bool SatisfiesRequireAutocomplete(const WebInputElement
& input_element
) {
132 return input_element
.autoComplete();
135 // Appends |suffix| to |prefix| so that any intermediary whitespace is collapsed
136 // to a single space. If |force_whitespace| is true, then the resulting string
137 // is guaranteed to have a space between |prefix| and |suffix|. Otherwise, the
138 // result includes a space only if |prefix| has trailing whitespace or |suffix|
139 // has leading whitespace.
141 // * CombineAndCollapseWhitespace("foo", "bar", false) -> "foobar"
142 // * CombineAndCollapseWhitespace("foo", "bar", true) -> "foo bar"
143 // * CombineAndCollapseWhitespace("foo ", "bar", false) -> "foo bar"
144 // * CombineAndCollapseWhitespace("foo", " bar", false) -> "foo bar"
145 // * CombineAndCollapseWhitespace("foo", " bar", true) -> "foo bar"
146 // * CombineAndCollapseWhitespace("foo ", " bar", false) -> "foo bar"
147 // * CombineAndCollapseWhitespace(" foo", "bar ", false) -> " foobar "
148 // * CombineAndCollapseWhitespace(" foo", "bar ", true) -> " foo bar "
149 const base::string16
CombineAndCollapseWhitespace(
150 const base::string16
& prefix
,
151 const base::string16
& suffix
,
152 bool force_whitespace
) {
153 base::string16 prefix_trimmed
;
154 base::TrimPositions prefix_trailing_whitespace
=
155 base::TrimWhitespace(prefix
, base::TRIM_TRAILING
, &prefix_trimmed
);
157 // Recursively compute the children's text.
158 base::string16 suffix_trimmed
;
159 base::TrimPositions suffix_leading_whitespace
=
160 base::TrimWhitespace(suffix
, base::TRIM_LEADING
, &suffix_trimmed
);
162 if (prefix_trailing_whitespace
|| suffix_leading_whitespace
||
164 return prefix_trimmed
+ base::ASCIIToUTF16(" ") + suffix_trimmed
;
166 return prefix_trimmed
+ suffix_trimmed
;
170 // This is a helper function for the FindChildText() function (see below).
171 // Search depth is limited with the |depth| parameter.
172 base::string16
FindChildTextInner(const WebNode
& node
, int depth
) {
173 if (depth
<= 0 || node
.isNull())
174 return base::string16();
176 // Skip over comments.
177 if (node
.nodeType() == WebNode::CommentNode
)
178 return FindChildTextInner(node
.nextSibling(), depth
- 1);
180 if (node
.nodeType() != WebNode::ElementNode
&&
181 node
.nodeType() != WebNode::TextNode
)
182 return base::string16();
184 // Ignore elements known not to contain inferable labels.
185 if (node
.isElementNode()) {
186 const WebElement element
= node
.toConst
<WebElement
>();
187 if (IsOptionElement(element
) ||
188 IsScriptElement(element
) ||
189 IsNoScriptElement(element
) ||
190 (element
.isFormControlElement() &&
191 IsAutofillableElement(element
.toConst
<WebFormControlElement
>()))) {
192 return base::string16();
196 // Extract the text exactly at this node.
197 base::string16 node_text
= node
.nodeValue();
199 // Recursively compute the children's text.
200 // Preserve inter-element whitespace separation.
201 base::string16 child_text
= FindChildTextInner(node
.firstChild(), depth
- 1);
202 bool add_space
= node
.nodeType() == WebNode::TextNode
&& node_text
.empty();
203 node_text
= CombineAndCollapseWhitespace(node_text
, child_text
, add_space
);
205 // Recursively compute the siblings' text.
206 // Again, preserve inter-element whitespace separation.
207 base::string16 sibling_text
=
208 FindChildTextInner(node
.nextSibling(), depth
- 1);
209 add_space
= node
.nodeType() == WebNode::TextNode
&& node_text
.empty();
210 node_text
= CombineAndCollapseWhitespace(node_text
, sibling_text
, add_space
);
215 // Returns the aggregated values of the descendants of |element| that are
216 // non-empty text nodes. This is a faster alternative to |innerText()| for
217 // performance critical operations. It does a full depth-first search so can be
218 // used when the structure is not directly known. However, unlike with
219 // |innerText()|, the search depth and breadth are limited to a fixed threshold.
220 // Whitespace is trimmed from text accumulated at descendant nodes.
221 base::string16
FindChildText(const WebNode
& node
) {
222 if (node
.isTextNode())
223 return node
.nodeValue();
225 WebNode child
= node
.firstChild();
227 const int kChildSearchDepth
= 10;
228 base::string16 node_text
= FindChildTextInner(child
, kChildSearchDepth
);
229 base::TrimWhitespace(node_text
, base::TRIM_ALL
, &node_text
);
233 // Shared function for InferLabelFromPrevious() and InferLabelFromNext().
234 base::string16
InferLabelFromSibling(const WebFormControlElement
& element
,
236 base::string16 inferred_label
;
237 WebNode sibling
= element
;
239 sibling
= forward
? sibling
.nextSibling() : sibling
.previousSibling();
240 if (sibling
.isNull())
243 // Skip over comments.
244 WebNode::NodeType node_type
= sibling
.nodeType();
245 if (node_type
== WebNode::CommentNode
)
248 // Otherwise, only consider normal HTML elements and their contents.
249 if (node_type
!= WebNode::TextNode
&&
250 node_type
!= WebNode::ElementNode
)
253 // A label might be split across multiple "lightweight" nodes.
254 // Coalesce any text contained in multiple consecutive
255 // (a) plain text nodes or
256 // (b) inline HTML elements that are essentially equivalent to text nodes.
257 CR_DEFINE_STATIC_LOCAL(WebString
, kBold
, ("b"));
258 CR_DEFINE_STATIC_LOCAL(WebString
, kStrong
, ("strong"));
259 CR_DEFINE_STATIC_LOCAL(WebString
, kSpan
, ("span"));
260 CR_DEFINE_STATIC_LOCAL(WebString
, kFont
, ("font"));
261 if (sibling
.isTextNode() ||
262 HasTagName(sibling
, kBold
) || HasTagName(sibling
, kStrong
) ||
263 HasTagName(sibling
, kSpan
) || HasTagName(sibling
, kFont
)) {
264 base::string16 value
= FindChildText(sibling
);
265 // A text node's value will be empty if it is for a line break.
266 bool add_space
= sibling
.isTextNode() && value
.empty();
268 CombineAndCollapseWhitespace(value
, inferred_label
, add_space
);
272 // If we have identified a partial label and have reached a non-lightweight
273 // element, consider the label to be complete.
274 base::string16 trimmed_label
;
275 base::TrimWhitespace(inferred_label
, base::TRIM_ALL
, &trimmed_label
);
276 if (!trimmed_label
.empty())
279 // <img> and <br> tags often appear between the input element and its
280 // label text, so skip over them.
281 CR_DEFINE_STATIC_LOCAL(WebString
, kImage
, ("img"));
282 CR_DEFINE_STATIC_LOCAL(WebString
, kBreak
, ("br"));
283 if (HasTagName(sibling
, kImage
) || HasTagName(sibling
, kBreak
))
286 // We only expect <p> and <label> tags to contain the full label text.
287 CR_DEFINE_STATIC_LOCAL(WebString
, kPage
, ("p"));
288 CR_DEFINE_STATIC_LOCAL(WebString
, kLabel
, ("label"));
289 if (HasTagName(sibling
, kPage
) || HasTagName(sibling
, kLabel
))
290 inferred_label
= FindChildText(sibling
);
295 base::TrimWhitespace(inferred_label
, base::TRIM_ALL
, &inferred_label
);
296 return inferred_label
;
299 // Helper for |InferLabelForElement()| that infers a label, if possible, from
300 // a previous sibling of |element|,
301 // e.g. Some Text <input ...>
302 // or Some <span>Text</span> <input ...>
303 // or <p>Some Text</p><input ...>
304 // or <label>Some Text</label> <input ...>
305 // or Some Text <img><input ...>
306 // or <b>Some Text</b><br/> <input ...>.
307 base::string16
InferLabelFromPrevious(const WebFormControlElement
& element
) {
308 return InferLabelFromSibling(element
, false /* forward? */);
311 // Same as InferLabelFromPrevious(), but in the other direction.
312 // Useful for cases like: <span><input type="checkbox">Label For Checkbox</span>
313 base::string16
InferLabelFromNext(const WebFormControlElement
& element
) {
314 return InferLabelFromSibling(element
, true /* forward? */);
317 // Helper for |InferLabelForElement()| that infers a label, if possible, from
319 base::string16
InferLabelFromPlaceholder(const WebFormControlElement
& element
) {
320 CR_DEFINE_STATIC_LOCAL(WebString
, kPlaceholder
, ("placeholder"));
321 if (element
.hasAttribute(kPlaceholder
))
322 return element
.getAttribute(kPlaceholder
);
324 return base::string16();
327 // Helper for |InferLabelForElement()| that infers a label, if possible, from
328 // enclosing list item,
329 // e.g. <li>Some Text<input ...><input ...><input ...></tr>
330 base::string16
InferLabelFromListItem(const WebFormControlElement
& element
) {
331 WebNode parent
= element
.parentNode();
332 CR_DEFINE_STATIC_LOCAL(WebString
, kListItem
, ("li"));
333 while (!parent
.isNull() && parent
.isElementNode() &&
334 !parent
.to
<WebElement
>().hasHTMLTagName(kListItem
)) {
335 parent
= parent
.parentNode();
338 if (!parent
.isNull() && HasTagName(parent
, kListItem
))
339 return FindChildText(parent
);
341 return base::string16();
344 // Helper for |InferLabelForElement()| that infers a label, if possible, from
345 // surrounding table structure,
346 // e.g. <tr><td>Some Text</td><td><input ...></td></tr>
347 // or <tr><th>Some Text</th><td><input ...></td></tr>
348 // or <tr><td><b>Some Text</b></td><td><b><input ...></b></td></tr>
349 // or <tr><th><b>Some Text</b></th><td><b><input ...></b></td></tr>
350 base::string16
InferLabelFromTableColumn(const WebFormControlElement
& element
) {
351 CR_DEFINE_STATIC_LOCAL(WebString
, kTableCell
, ("td"));
352 WebNode parent
= element
.parentNode();
353 while (!parent
.isNull() && parent
.isElementNode() &&
354 !parent
.to
<WebElement
>().hasHTMLTagName(kTableCell
)) {
355 parent
= parent
.parentNode();
359 return base::string16();
361 // Check all previous siblings, skipping non-element nodes, until we find a
362 // non-empty text block.
363 base::string16 inferred_label
;
364 WebNode previous
= parent
.previousSibling();
365 CR_DEFINE_STATIC_LOCAL(WebString
, kTableHeader
, ("th"));
366 while (inferred_label
.empty() && !previous
.isNull()) {
367 if (HasTagName(previous
, kTableCell
) || HasTagName(previous
, kTableHeader
))
368 inferred_label
= FindChildText(previous
);
370 previous
= previous
.previousSibling();
373 return inferred_label
;
376 // Helper for |InferLabelForElement()| that infers a label, if possible, from
377 // surrounding table structure,
378 // e.g. <tr><td>Some Text</td></tr><tr><td><input ...></td></tr>
379 base::string16
InferLabelFromTableRow(const WebFormControlElement
& element
) {
380 CR_DEFINE_STATIC_LOCAL(WebString
, kTableRow
, ("tr"));
381 WebNode parent
= element
.parentNode();
382 while (!parent
.isNull() && parent
.isElementNode() &&
383 !parent
.to
<WebElement
>().hasHTMLTagName(kTableRow
)) {
384 parent
= parent
.parentNode();
388 return base::string16();
390 // Check all previous siblings, skipping non-element nodes, until we find a
391 // non-empty text block.
392 base::string16 inferred_label
;
393 WebNode previous
= parent
.previousSibling();
394 while (inferred_label
.empty() && !previous
.isNull()) {
395 if (HasTagName(previous
, kTableRow
))
396 inferred_label
= FindChildText(previous
);
398 previous
= previous
.previousSibling();
401 return inferred_label
;
404 // Helper for |InferLabelForElement()| that infers a label, if possible, from
405 // a surrounding div table,
406 // e.g. <div>Some Text<span><input ...></span></div>
407 // e.g. <div>Some Text</div><div><input ...></div>
408 base::string16
InferLabelFromDivTable(const WebFormControlElement
& element
) {
409 WebNode node
= element
.parentNode();
410 bool looking_for_parent
= true;
412 // Search the sibling and parent <div>s until we find a candidate label.
413 base::string16 inferred_label
;
414 CR_DEFINE_STATIC_LOCAL(WebString
, kDiv
, ("div"));
415 CR_DEFINE_STATIC_LOCAL(WebString
, kTable
, ("table"));
416 CR_DEFINE_STATIC_LOCAL(WebString
, kFieldSet
, ("fieldset"));
417 while (inferred_label
.empty() && !node
.isNull()) {
418 if (HasTagName(node
, kDiv
)) {
419 inferred_label
= FindChildText(node
);
420 // Avoid sibling DIVs that contain autofillable fields.
421 if (!looking_for_parent
&& !inferred_label
.empty()) {
422 CR_DEFINE_STATIC_LOCAL(WebString
, kSelector
,
423 ("input, select, textarea"));
424 blink::WebExceptionCode ec
= 0;
425 WebElement result_element
= node
.querySelector(kSelector
, ec
);
426 if (!result_element
.isNull())
427 inferred_label
.clear();
430 looking_for_parent
= false;
431 } else if (looking_for_parent
&&
432 (HasTagName(node
, kTable
) || HasTagName(node
, kFieldSet
))) {
433 // If the element is in a table or fieldset, its label most likely is too.
437 if (node
.previousSibling().isNull()) {
438 // If there are no more siblings, continue walking up the tree.
439 looking_for_parent
= true;
442 node
= looking_for_parent
? node
.parentNode() : node
.previousSibling();
445 return inferred_label
;
448 // Helper for |InferLabelForElement()| that infers a label, if possible, from
449 // a surrounding definition list,
450 // e.g. <dl><dt>Some Text</dt><dd><input ...></dd></dl>
451 // e.g. <dl><dt><b>Some Text</b></dt><dd><b><input ...></b></dd></dl>
452 base::string16
InferLabelFromDefinitionList(
453 const WebFormControlElement
& element
) {
454 CR_DEFINE_STATIC_LOCAL(WebString
, kDefinitionData
, ("dd"));
455 WebNode parent
= element
.parentNode();
456 while (!parent
.isNull() && parent
.isElementNode() &&
457 !parent
.to
<WebElement
>().hasHTMLTagName(kDefinitionData
))
458 parent
= parent
.parentNode();
460 if (parent
.isNull() || !HasTagName(parent
, kDefinitionData
))
461 return base::string16();
463 // Skip by any intervening text nodes.
464 WebNode previous
= parent
.previousSibling();
465 while (!previous
.isNull() && previous
.isTextNode())
466 previous
= previous
.previousSibling();
468 CR_DEFINE_STATIC_LOCAL(WebString
, kDefinitionTag
, ("dt"));
469 if (previous
.isNull() || !HasTagName(previous
, kDefinitionTag
))
470 return base::string16();
472 return FindChildText(previous
);
475 // Returns true if the closest ancestor is a <div> and not a <td>.
476 // Returns false if the closest ancestor is a <td> tag,
477 // or if there is no <div> or <td> ancestor.
478 bool ClosestAncestorIsDivAndNotTD(const WebFormControlElement
& element
) {
479 for (WebNode parent_node
= element
.parentNode();
480 !parent_node
.isNull();
481 parent_node
= parent_node
.parentNode()) {
482 if (!parent_node
.isElementNode())
485 WebElement cur_element
= parent_node
.to
<WebElement
>();
486 if (cur_element
.hasHTMLTagName("div"))
488 if (cur_element
.hasHTMLTagName("td"))
494 // Infers corresponding label for |element| from surrounding context in the DOM,
495 // e.g. the contents of the preceding <p> tag or text element.
496 base::string16
InferLabelForElement(const WebFormControlElement
& element
) {
497 base::string16 inferred_label
;
498 if (IsCheckableElement(toWebInputElement(&element
))) {
499 inferred_label
= InferLabelFromNext(element
);
500 if (!inferred_label
.empty())
501 return inferred_label
;
504 inferred_label
= InferLabelFromPrevious(element
);
505 if (!inferred_label
.empty())
506 return inferred_label
;
508 // If we didn't find a label, check for placeholder text.
509 inferred_label
= InferLabelFromPlaceholder(element
);
510 if (!inferred_label
.empty())
511 return inferred_label
;
513 // If we didn't find a label, check for list item case.
514 inferred_label
= InferLabelFromListItem(element
);
515 if (!inferred_label
.empty())
516 return inferred_label
;
518 // If we didn't find a label, check for definition list case.
519 inferred_label
= InferLabelFromDefinitionList(element
);
520 if (!inferred_label
.empty())
521 return inferred_label
;
523 bool check_div_first
= ClosestAncestorIsDivAndNotTD(element
);
524 if (check_div_first
) {
525 // If we didn't find a label, check for div table case first since it's the
527 inferred_label
= InferLabelFromDivTable(element
);
528 if (!inferred_label
.empty())
529 return inferred_label
;
532 // If we didn't find a label, check for table cell case.
533 inferred_label
= InferLabelFromTableColumn(element
);
534 if (!inferred_label
.empty())
535 return inferred_label
;
537 // If we didn't find a label, check for table row case.
538 inferred_label
= InferLabelFromTableRow(element
);
539 if (!inferred_label
.empty())
540 return inferred_label
;
542 if (!check_div_first
) {
543 // If we didn't find a label from the table, check for div table case if we
545 inferred_label
= InferLabelFromDivTable(element
);
547 return inferred_label
;
550 // Fills |option_strings| with the values of the <option> elements present in
552 void GetOptionStringsFromElement(const WebSelectElement
& select_element
,
553 std::vector
<base::string16
>* option_values
,
554 std::vector
<base::string16
>* option_contents
) {
555 DCHECK(!select_element
.isNull());
557 option_values
->clear();
558 option_contents
->clear();
559 WebVector
<WebElement
> list_items
= select_element
.listItems();
561 // Constrain the maximum list length to prevent a malicious site from DOS'ing
562 // the browser, without entirely breaking autocomplete for some extreme
563 // legitimate sites: http://crbug.com/49332 and http://crbug.com/363094
564 if (list_items
.size() > kMaxListSize
)
567 option_values
->reserve(list_items
.size());
568 option_contents
->reserve(list_items
.size());
569 for (size_t i
= 0; i
< list_items
.size(); ++i
) {
570 if (IsOptionElement(list_items
[i
])) {
571 const WebOptionElement option
= list_items
[i
].toConst
<WebOptionElement
>();
572 option_values
->push_back(option
.value());
573 option_contents
->push_back(option
.text());
578 // The callback type used by |ForEachMatchingFormField()|.
579 typedef void (*Callback
)(const FormFieldData
&,
580 bool, /* is_initiating_element */
581 blink::WebFormControlElement
*);
583 void ForEachMatchingFormFieldCommon(
584 std::vector
<WebFormControlElement
>* control_elements
,
585 const WebElement
& initiating_element
,
586 const FormData
& data
,
587 FieldFilterMask filters
,
590 DCHECK(control_elements
);
591 if (control_elements
->size() != data
.fields
.size()) {
592 // This case should be reachable only for pathological websites and tests,
593 // which add or remove form fields while the user is interacting with the
598 // It's possible that the site has injected fields into the form after the
599 // page has loaded, so we can't assert that the size of the cached control
600 // elements is equal to the size of the fields in |form|. Fortunately, the
601 // one case in the wild where this happens, paypal.com signup form, the fields
602 // are appended to the end of the form and are not visible.
603 for (size_t i
= 0; i
< control_elements
->size(); ++i
) {
604 WebFormControlElement
* element
= &(*control_elements
)[i
];
606 if (base::string16(element
->nameForAutofill()) != data
.fields
[i
].name
) {
607 // This case should be reachable only for pathological websites, which
608 // rename form fields while the user is interacting with the Autofill
609 // popup. I (isherman) am not aware of any such websites, and so am
610 // optimistically including a NOTREACHED(). If you ever trip this check,
611 // please file a bug against me.
616 bool is_initiating_element
= (*element
== initiating_element
);
618 // Only autofill empty fields and the field that initiated the filling,
619 // i.e. the field the user is currently editing and interacting with.
620 const WebInputElement
* input_element
= toWebInputElement(element
);
621 if (!force_override
&& !is_initiating_element
&&
622 ((IsAutofillableInputElement(input_element
) ||
623 IsTextAreaElement(*element
)) &&
624 !element
->value().isEmpty()))
627 if (((filters
& FILTER_DISABLED_ELEMENTS
) && !element
->isEnabled()) ||
628 ((filters
& FILTER_READONLY_ELEMENTS
) && element
->isReadOnly()) ||
629 ((filters
& FILTER_NON_FOCUSABLE_ELEMENTS
) && !element
->isFocusable()))
632 callback(data
.fields
[i
], is_initiating_element
, element
);
636 // For each autofillable field in |data| that matches a field in the |form|,
637 // the |callback| is invoked with the corresponding |form| field data.
638 void ForEachMatchingFormField(const WebFormElement
& form_element
,
639 const WebElement
& initiating_element
,
640 const FormData
& data
,
641 FieldFilterMask filters
,
644 std::vector
<WebFormControlElement
> control_elements
=
645 ExtractAutofillableElementsInForm(form_element
, ExtractionRequirements());
646 ForEachMatchingFormFieldCommon(&control_elements
, initiating_element
, data
,
647 filters
, force_override
, callback
);
650 // For each autofillable field in |data| that matches a field in the set of
651 // unowned autofillable form fields, the |callback| is invoked with the
652 // corresponding |data| field.
653 void ForEachMatchingUnownedFormField(const WebElement
& initiating_element
,
654 const FormData
& data
,
655 FieldFilterMask filters
,
658 if (initiating_element
.isNull())
661 std::vector
<WebFormControlElement
> control_elements
=
662 GetUnownedAutofillableFormFieldElements(
663 initiating_element
.document().all(), nullptr);
664 if (!IsElementInControlElementSet(initiating_element
, control_elements
))
667 ForEachMatchingFormFieldCommon(&control_elements
, initiating_element
, data
,
668 filters
, force_override
, callback
);
671 // Sets the |field|'s value to the value in |data|.
672 // Also sets the "autofilled" attribute, causing the background to be yellow.
673 void FillFormField(const FormFieldData
& data
,
674 bool is_initiating_node
,
675 blink::WebFormControlElement
* field
) {
677 if (data
.value
.empty())
680 if (!data
.is_autofilled
)
683 WebInputElement
* input_element
= toWebInputElement(field
);
684 if (IsCheckableElement(input_element
)) {
685 input_element
->setChecked(data
.is_checked
, true);
687 base::string16 value
= data
.value
;
688 if (IsTextInput(input_element
) || IsMonthInput(input_element
)) {
689 // If the maxlength attribute contains a negative value, maxLength()
690 // returns the default maxlength value.
691 TruncateString(&value
, input_element
->maxLength());
693 field
->setValue(value
, true);
696 field
->setAutofilled(true);
698 if (is_initiating_node
&&
699 ((IsTextInput(input_element
) || IsMonthInput(input_element
)) ||
700 IsTextAreaElement(*field
))) {
701 int length
= field
->value().length();
702 field
->setSelectionRange(length
, length
);
703 // Clear the current IME composition (the underline), if there is one.
704 field
->document().frame()->unmarkText();
708 // Sets the |field|'s "suggested" (non JS visible) value to the value in |data|.
709 // Also sets the "autofilled" attribute, causing the background to be yellow.
710 void PreviewFormField(const FormFieldData
& data
,
711 bool is_initiating_node
,
712 blink::WebFormControlElement
* field
) {
713 // Nothing to preview.
714 if (data
.value
.empty())
717 if (!data
.is_autofilled
)
720 // Preview input, textarea and select fields. For input fields, excludes
721 // checkboxes and radio buttons, as there is no provision for
722 // setSuggestedCheckedValue in WebInputElement.
723 WebInputElement
* input_element
= toWebInputElement(field
);
724 if (IsTextInput(input_element
) || IsMonthInput(input_element
)) {
725 // If the maxlength attribute contains a negative value, maxLength()
726 // returns the default maxlength value.
727 input_element
->setSuggestedValue(
728 data
.value
.substr(0, input_element
->maxLength()));
729 input_element
->setAutofilled(true);
730 } else if (IsTextAreaElement(*field
) || IsSelectElement(*field
)) {
731 field
->setSuggestedValue(data
.value
);
732 field
->setAutofilled(true);
735 if (is_initiating_node
&&
736 (IsTextInput(input_element
) || IsTextAreaElement(*field
))) {
737 // Select the part of the text that the user didn't type.
738 int start
= field
->value().length();
739 int end
= field
->suggestedValue().length();
740 field
->setSelectionRange(start
, end
);
744 // Recursively checks whether |node| or any of its children have a non-empty
745 // bounding box. The recursion depth is bounded by |depth|.
746 bool IsWebNodeVisibleImpl(const blink::WebNode
& node
, const int depth
) {
749 if (node
.hasNonEmptyBoundingBox())
752 // The childNodes method is not a const method. Therefore it cannot be called
753 // on a const reference. Therefore we need a const cast.
754 const blink::WebNodeList
& children
=
755 const_cast<blink::WebNode
&>(node
).childNodes();
756 size_t length
= children
.length();
757 for (size_t i
= 0; i
< length
; ++i
) {
758 const blink::WebNode
& item
= children
.item(i
);
759 if (IsWebNodeVisibleImpl(item
, depth
- 1))
765 bool ExtractFieldsFromControlElements(
766 const WebVector
<WebFormControlElement
>& control_elements
,
767 RequirementsMask requirements
,
768 ExtractMask extract_mask
,
769 ScopedVector
<FormFieldData
>* form_fields
,
770 std::vector
<bool>* fields_extracted
,
771 std::map
<WebFormControlElement
, FormFieldData
*>* element_map
) {
772 for (size_t i
= 0; i
< control_elements
.size(); ++i
) {
773 const WebFormControlElement
& control_element
= control_elements
[i
];
775 if (!IsAutofillableElement(control_element
))
778 const WebInputElement
* input_element
= toWebInputElement(&control_element
);
779 if (requirements
& REQUIRE_AUTOCOMPLETE
&&
780 IsAutofillableInputElement(input_element
) &&
781 !SatisfiesRequireAutocomplete(*input_element
))
784 // Create a new FormFieldData, fill it out and map it to the field's name.
785 FormFieldData
* form_field
= new FormFieldData
;
786 WebFormControlElementToFormField(control_element
, extract_mask
, form_field
);
787 form_fields
->push_back(form_field
);
788 (*element_map
)[control_element
] = form_field
;
789 (*fields_extracted
)[i
] = true;
792 // If we failed to extract any fields, give up. Also, to avoid overly
793 // expensive computation, we impose a maximum number of allowable fields.
794 if (form_fields
->empty() || form_fields
->size() > kMaxParseableFields
)
799 // For each label element, get the corresponding form control element, use the
800 // form control element's name as a key into the
801 // <WebFormControlElement, FormFieldData> map to find the previously created
802 // FormFieldData and set the FormFieldData's label to the
803 // label.firstChild().nodeValue() of the label element.
804 void MatchLabelsAndFields(
805 const WebElementCollection
& labels
,
806 std::map
<WebFormControlElement
, FormFieldData
*>* element_map
) {
807 CR_DEFINE_STATIC_LOCAL(WebString
, kFor
, ("for"));
808 CR_DEFINE_STATIC_LOCAL(WebString
, kHidden
, ("hidden"));
810 for (WebElement item
= labels
.firstItem(); !item
.isNull();
811 item
= labels
.nextItem()) {
812 WebLabelElement label
= item
.to
<WebLabelElement
>();
813 WebFormControlElement field_element
=
814 label
.correspondingControl().to
<WebFormControlElement
>();
815 FormFieldData
* field_data
= nullptr;
817 if (field_element
.isNull()) {
818 // Sometimes site authors will incorrectly specify the corresponding
819 // field element's name rather than its id, so we compensate here.
820 base::string16 element_name
= label
.getAttribute(kFor
);
821 if (element_name
.empty())
823 // Look through the list for elements with this name. There can actually
824 // be more than one. In this case, the label may not be particularly
825 // useful, so just discard it.
826 for (const auto& iter
: *element_map
) {
827 if (iter
.second
->name
== element_name
) {
829 field_data
= nullptr;
832 field_data
= iter
.second
;
836 } else if (!field_element
.isFormControlElement() ||
837 field_element
.formControlType() == kHidden
) {
840 // Typical case: look up |field_data| in |element_map|.
841 auto iter
= element_map
->find(field_element
);
842 if (iter
== element_map
->end())
844 field_data
= iter
->second
;
850 base::string16 label_text
= FindChildText(label
);
852 // Concatenate labels because some sites might have multiple label
854 if (!field_data
->label
.empty() && !label_text
.empty())
855 field_data
->label
+= base::ASCIIToUTF16(" ");
856 field_data
->label
+= label_text
;
860 // Common function shared by WebFormElementToFormData() and
861 // UnownedFormElementsAndFieldSetsToFormData(). Either pass in:
862 // 1) |form_element| and an empty |fieldsets|.
864 // 2) a NULL |form_element|.
866 // If |field| is not NULL, then |form_control_element| should be not NULL.
867 bool FormOrFieldsetsToFormData(
868 const blink::WebFormElement
* form_element
,
869 const blink::WebFormControlElement
* form_control_element
,
870 const std::vector
<blink::WebElement
>& fieldsets
,
871 const WebVector
<WebFormControlElement
>& control_elements
,
872 RequirementsMask requirements
,
873 ExtractMask extract_mask
,
875 FormFieldData
* field
) {
876 CR_DEFINE_STATIC_LOCAL(WebString
, kLabel
, ("label"));
879 DCHECK(fieldsets
.empty());
881 DCHECK(form_control_element
);
883 // A map from a FormFieldData's name to the FormFieldData itself.
884 std::map
<WebFormControlElement
, FormFieldData
*> element_map
;
886 // The extracted FormFields. We use pointers so we can store them in
888 ScopedVector
<FormFieldData
> form_fields
;
890 // A vector of bools that indicate whether each field in the form meets the
891 // requirements and thus will be in the resulting |form|.
892 std::vector
<bool> fields_extracted(control_elements
.size(), false);
894 if (!ExtractFieldsFromControlElements(control_elements
, requirements
,
895 extract_mask
, &form_fields
,
896 &fields_extracted
, &element_map
)) {
901 // Loop through the label elements inside the form element. For each label
902 // element, get the corresponding form control element, use the form control
903 // element's name as a key into the <name, FormFieldData> map to find the
904 // previously created FormFieldData and set the FormFieldData's label to the
905 // label.firstChild().nodeValue() of the label element.
906 WebElementCollection labels
=
907 form_element
->getElementsByHTMLTagName(kLabel
);
908 DCHECK(!labels
.isNull());
909 MatchLabelsAndFields(labels
, &element_map
);
911 // Same as the if block, but for all the labels in fieldsets.
912 for (size_t i
= 0; i
< fieldsets
.size(); ++i
) {
913 WebElementCollection labels
=
914 fieldsets
[i
].getElementsByHTMLTagName(kLabel
);
915 DCHECK(!labels
.isNull());
916 MatchLabelsAndFields(labels
, &element_map
);
920 // Loop through the form control elements, extracting the label text from
921 // the DOM. We use the |fields_extracted| vector to make sure we assign the
922 // extracted label to the correct field, as it's possible |form_fields| will
923 // not contain all of the elements in |control_elements|.
924 for (size_t i
= 0, field_idx
= 0;
925 i
< control_elements
.size() && field_idx
< form_fields
.size(); ++i
) {
926 // This field didn't meet the requirements, so don't try to find a label
928 if (!fields_extracted
[i
])
931 const WebFormControlElement
& control_element
= control_elements
[i
];
932 if (form_fields
[field_idx
]->label
.empty())
933 form_fields
[field_idx
]->label
= InferLabelForElement(control_element
);
934 TruncateString(&form_fields
[field_idx
]->label
, kMaxDataLength
);
936 if (field
&& *form_control_element
== control_element
)
937 *field
= *form_fields
[field_idx
];
942 // Copy the created FormFields into the resulting FormData object.
943 for (const auto& iter
: form_fields
)
944 form
->fields
.push_back(*iter
);
950 const size_t kMaxParseableFields
= 200;
952 bool IsMonthInput(const WebInputElement
* element
) {
953 CR_DEFINE_STATIC_LOCAL(WebString
, kMonth
, ("month"));
954 return element
&& !element
->isNull() && element
->formControlType() == kMonth
;
957 // All text fields, including password fields, should be extracted.
958 bool IsTextInput(const WebInputElement
* element
) {
959 return element
&& !element
->isNull() && element
->isTextField();
962 bool IsSelectElement(const WebFormControlElement
& element
) {
963 // Static for improved performance.
964 CR_DEFINE_STATIC_LOCAL(WebString
, kSelectOne
, ("select-one"));
965 return !element
.isNull() && element
.formControlType() == kSelectOne
;
968 bool IsTextAreaElement(const WebFormControlElement
& element
) {
969 // Static for improved performance.
970 CR_DEFINE_STATIC_LOCAL(WebString
, kTextArea
, ("textarea"));
971 return !element
.isNull() && element
.formControlType() == kTextArea
;
974 bool IsCheckableElement(const WebInputElement
* element
) {
975 if (!element
|| element
->isNull())
978 return element
->isCheckbox() || element
->isRadioButton();
981 bool IsAutofillableInputElement(const WebInputElement
* element
) {
982 return IsTextInput(element
) ||
983 IsMonthInput(element
) ||
984 IsCheckableElement(element
);
987 const base::string16
GetFormIdentifier(const WebFormElement
& form
) {
988 base::string16 identifier
= form
.name();
989 CR_DEFINE_STATIC_LOCAL(WebString
, kId
, ("id"));
990 if (identifier
.empty())
991 identifier
= form
.getAttribute(kId
);
996 bool IsWebNodeVisible(const blink::WebNode
& node
) {
997 // In the bug http://crbug.com/237216 the form's bounding box is empty
998 // however the form has non empty children. Thus we need to look at the
1000 int kNodeSearchDepth
= 2;
1001 return IsWebNodeVisibleImpl(node
, kNodeSearchDepth
);
1004 std::vector
<blink::WebFormControlElement
> ExtractAutofillableElementsFromSet(
1005 const WebVector
<WebFormControlElement
>& control_elements
,
1006 RequirementsMask requirements
) {
1007 std::vector
<blink::WebFormControlElement
> autofillable_elements
;
1008 for (size_t i
= 0; i
< control_elements
.size(); ++i
) {
1009 WebFormControlElement element
= control_elements
[i
];
1010 if (!IsAutofillableElement(element
))
1013 if (requirements
& REQUIRE_AUTOCOMPLETE
) {
1014 // TODO(isherman): WebKit currently doesn't handle the autocomplete
1015 // attribute for select or textarea elements, but it probably should.
1016 const WebInputElement
* input_element
=
1017 toWebInputElement(&control_elements
[i
]);
1018 if (IsAutofillableInputElement(input_element
) &&
1019 !SatisfiesRequireAutocomplete(*input_element
))
1023 autofillable_elements
.push_back(element
);
1025 return autofillable_elements
;
1028 std::vector
<WebFormControlElement
> ExtractAutofillableElementsInForm(
1029 const WebFormElement
& form_element
,
1030 RequirementsMask requirements
) {
1031 WebVector
<WebFormControlElement
> control_elements
;
1032 form_element
.getFormControlElements(control_elements
);
1034 return ExtractAutofillableElementsFromSet(control_elements
, requirements
);
1037 void WebFormControlElementToFormField(const WebFormControlElement
& element
,
1038 ExtractMask extract_mask
,
1039 FormFieldData
* field
) {
1041 DCHECK(!element
.isNull());
1042 CR_DEFINE_STATIC_LOCAL(WebString
, kAutocomplete
, ("autocomplete"));
1043 CR_DEFINE_STATIC_LOCAL(WebString
, kRole
, ("role"));
1045 // The label is not officially part of a WebFormControlElement; however, the
1046 // labels for all form control elements are scraped from the DOM and set in
1047 // WebFormElementToFormData.
1048 field
->name
= element
.nameForAutofill();
1049 field
->form_control_type
= base::UTF16ToUTF8(element
.formControlType());
1050 field
->autocomplete_attribute
=
1051 base::UTF16ToUTF8(element
.getAttribute(kAutocomplete
));
1052 if (field
->autocomplete_attribute
.size() > kMaxDataLength
) {
1053 // Discard overly long attribute values to avoid DOS-ing the browser
1054 // process. However, send over a default string to indicate that the
1055 // attribute was present.
1056 field
->autocomplete_attribute
= "x-max-data-length-exceeded";
1058 if (LowerCaseEqualsASCII(element
.getAttribute(kRole
), "presentation"))
1059 field
->role
= FormFieldData::ROLE_ATTRIBUTE_PRESENTATION
;
1061 if (!IsAutofillableElement(element
))
1064 const WebInputElement
* input_element
= toWebInputElement(&element
);
1065 if (IsAutofillableInputElement(input_element
) ||
1066 IsTextAreaElement(element
)) {
1067 field
->is_autofilled
= element
.isAutofilled();
1068 field
->is_focusable
= element
.isFocusable();
1069 field
->should_autocomplete
= element
.autoComplete();
1070 field
->text_direction
= element
.directionForFormData() ==
1071 "rtl" ? base::i18n::RIGHT_TO_LEFT
: base::i18n::LEFT_TO_RIGHT
;
1074 if (IsAutofillableInputElement(input_element
)) {
1075 if (IsTextInput(input_element
))
1076 field
->max_length
= input_element
->maxLength();
1078 field
->is_checkable
= IsCheckableElement(input_element
);
1079 field
->is_checked
= input_element
->isChecked();
1080 } else if (IsTextAreaElement(element
)) {
1081 // Nothing more to do in this case.
1082 } else if (extract_mask
& EXTRACT_OPTIONS
) {
1083 // Set option strings on the field if available.
1084 DCHECK(IsSelectElement(element
));
1085 const WebSelectElement select_element
= element
.toConst
<WebSelectElement
>();
1086 GetOptionStringsFromElement(select_element
,
1087 &field
->option_values
,
1088 &field
->option_contents
);
1091 if (!(extract_mask
& EXTRACT_VALUE
))
1094 base::string16 value
= element
.value();
1096 if (IsSelectElement(element
) && (extract_mask
& EXTRACT_OPTION_TEXT
)) {
1097 const WebSelectElement select_element
= element
.toConst
<WebSelectElement
>();
1098 // Convert the |select_element| value to text if requested.
1099 WebVector
<WebElement
> list_items
= select_element
.listItems();
1100 for (size_t i
= 0; i
< list_items
.size(); ++i
) {
1101 if (IsOptionElement(list_items
[i
])) {
1102 const WebOptionElement option_element
=
1103 list_items
[i
].toConst
<WebOptionElement
>();
1104 if (option_element
.value() == value
) {
1105 value
= option_element
.text();
1112 // Constrain the maximum data length to prevent a malicious site from DOS'ing
1113 // the browser: http://crbug.com/49332
1114 TruncateString(&value
, kMaxDataLength
);
1116 field
->value
= value
;
1119 bool WebFormElementToFormData(
1120 const blink::WebFormElement
& form_element
,
1121 const blink::WebFormControlElement
& form_control_element
,
1122 RequirementsMask requirements
,
1123 ExtractMask extract_mask
,
1125 FormFieldData
* field
) {
1126 const WebFrame
* frame
= form_element
.document().frame();
1130 if (requirements
& REQUIRE_AUTOCOMPLETE
&& !form_element
.autoComplete())
1133 form
->name
= GetFormIdentifier(form_element
);
1134 form
->origin
= frame
->document().url();
1135 form
->action
= frame
->document().completeURL(form_element
.action());
1136 form
->user_submitted
= form_element
.wasUserSubmitted();
1138 // If the completed URL is not valid, just use the action we get from
1140 if (!form
->action
.is_valid())
1141 form
->action
= GURL(form_element
.action());
1143 WebVector
<WebFormControlElement
> control_elements
;
1144 form_element
.getFormControlElements(control_elements
);
1146 std::vector
<blink::WebElement
> dummy_fieldset
;
1147 return FormOrFieldsetsToFormData(&form_element
, &form_control_element
,
1148 dummy_fieldset
, control_elements
,
1149 requirements
, extract_mask
, form
, field
);
1152 std::vector
<WebFormControlElement
>
1153 GetUnownedAutofillableFormFieldElements(
1154 const WebElementCollection
& elements
,
1155 std::vector
<WebElement
>* fieldsets
) {
1156 std::vector
<WebFormControlElement
> unowned_fieldset_children
;
1157 for (WebElement element
= elements
.firstItem();
1159 element
= elements
.nextItem()) {
1160 if (element
.isFormControlElement()) {
1161 WebFormControlElement control
= element
.to
<WebFormControlElement
>();
1162 if (control
.form().isNull())
1163 unowned_fieldset_children
.push_back(control
);
1166 if (fieldsets
&& element
.hasHTMLTagName("fieldset") &&
1167 !IsElementInsideFormOrFieldSet(element
)) {
1168 fieldsets
->push_back(element
);
1171 return ExtractAutofillableElementsFromSet(unowned_fieldset_children
,
1175 bool UnownedFormElementsAndFieldSetsToFormData(
1176 const std::vector
<blink::WebElement
>& fieldsets
,
1177 const std::vector
<blink::WebFormControlElement
>& control_elements
,
1178 const blink::WebFormControlElement
* element
,
1180 RequirementsMask requirements
,
1181 ExtractMask extract_mask
,
1183 FormFieldData
* field
) {
1184 form
->origin
= origin
;
1185 form
->user_submitted
= false;
1186 form
->is_form_tag
= false;
1188 return FormOrFieldsetsToFormData(nullptr, element
, fieldsets
,
1189 control_elements
, requirements
, extract_mask
,
1193 bool FindFormAndFieldForFormControlElement(const WebFormControlElement
& element
,
1195 FormFieldData
* field
,
1196 RequirementsMask requirements
) {
1197 if (!IsAutofillableElement(element
))
1200 ExtractMask extract_mask
=
1201 static_cast<ExtractMask
>(EXTRACT_VALUE
| EXTRACT_OPTIONS
);
1202 const WebFormElement form_element
= element
.form();
1203 if (form_element
.isNull()) {
1204 // No associated form, try the synthetic form for unowned form elements.
1205 WebDocument document
= element
.document();
1206 std::vector
<WebElement
> fieldsets
;
1207 std::vector
<WebFormControlElement
> control_elements
=
1208 GetUnownedAutofillableFormFieldElements(document
.all(), &fieldsets
);
1209 return UnownedFormElementsAndFieldSetsToFormData(
1210 fieldsets
, control_elements
, &element
, document
.url(), requirements
,
1211 extract_mask
, form
, field
);
1214 return WebFormElementToFormData(form_element
,
1222 void FillForm(const FormData
& form
, const WebFormControlElement
& element
) {
1223 WebFormElement form_element
= element
.form();
1224 if (form_element
.isNull()) {
1225 ForEachMatchingUnownedFormField(element
,
1227 FILTER_ALL_NON_EDITABLE_ELEMENTS
,
1228 false, /* dont force override */
1233 ForEachMatchingFormField(form_element
,
1236 FILTER_ALL_NON_EDITABLE_ELEMENTS
,
1237 false, /* dont force override */
1241 void FillFormIncludingNonFocusableElements(const FormData
& form_data
,
1242 const WebFormElement
& form_element
) {
1243 if (form_element
.isNull()) {
1248 FieldFilterMask filter_mask
= static_cast<FieldFilterMask
>(
1249 FILTER_DISABLED_ELEMENTS
| FILTER_READONLY_ELEMENTS
);
1250 ForEachMatchingFormField(form_element
,
1254 true, /* force override */
1258 void PreviewForm(const FormData
& form
, const WebFormControlElement
& element
) {
1259 WebFormElement form_element
= element
.form();
1260 if (form_element
.isNull()) {
1261 ForEachMatchingUnownedFormField(element
,
1263 FILTER_ALL_NON_EDITABLE_ELEMENTS
,
1264 false, /* dont force override */
1269 ForEachMatchingFormField(form_element
,
1272 FILTER_ALL_NON_EDITABLE_ELEMENTS
,
1273 false, /* dont force override */
1277 bool ClearPreviewedFormWithElement(const WebFormControlElement
& element
,
1278 bool was_autofilled
) {
1279 WebFormElement form_element
= element
.form();
1280 std::vector
<WebFormControlElement
> control_elements
;
1281 if (form_element
.isNull()) {
1282 control_elements
= GetUnownedAutofillableFormFieldElements(
1283 element
.document().all(), nullptr);
1284 if (!IsElementInControlElementSet(element
, control_elements
))
1287 control_elements
= ExtractAutofillableElementsInForm(
1288 form_element
, ExtractionRequirements());
1291 for (size_t i
= 0; i
< control_elements
.size(); ++i
) {
1292 // There might be unrelated elements in this form which have already been
1293 // auto-filled. For example, the user might have already filled the address
1294 // part of a form and now be dealing with the credit card section. We only
1295 // want to reset the auto-filled status for fields that were previewed.
1296 WebFormControlElement control_element
= control_elements
[i
];
1298 // Only text input, textarea and select elements can be previewed.
1299 WebInputElement
* input_element
= toWebInputElement(&control_element
);
1300 if (!IsTextInput(input_element
) &&
1301 !IsMonthInput(input_element
) &&
1302 !IsTextAreaElement(control_element
) &&
1303 !IsSelectElement(control_element
))
1306 // If the element is not auto-filled, we did not preview it,
1307 // so there is nothing to reset.
1308 if (!control_element
.isAutofilled())
1311 if ((IsTextInput(input_element
) ||
1312 IsMonthInput(input_element
) ||
1313 IsTextAreaElement(control_element
) ||
1314 IsSelectElement(control_element
)) &&
1315 control_element
.suggestedValue().isEmpty())
1318 // Clear the suggested value. For the initiating node, also restore the
1320 if (IsTextInput(input_element
) || IsMonthInput(input_element
) ||
1321 IsTextAreaElement(control_element
)) {
1322 control_element
.setSuggestedValue(WebString());
1323 bool is_initiating_node
= (element
== control_element
);
1324 if (is_initiating_node
) {
1325 control_element
.setAutofilled(was_autofilled
);
1326 // Clearing the suggested value in the focused node (above) can cause
1327 // selection to be lost. We force selection range to restore the text
1329 int length
= control_element
.value().length();
1330 control_element
.setSelectionRange(length
, length
);
1332 control_element
.setAutofilled(false);
1334 } else if (IsSelectElement(control_element
)) {
1335 control_element
.setSuggestedValue(WebString());
1336 control_element
.setAutofilled(false);
1343 bool IsWebpageEmpty(const blink::WebFrame
* frame
) {
1344 blink::WebDocument document
= frame
->document();
1346 return IsWebElementEmpty(document
.head()) &&
1347 IsWebElementEmpty(document
.body());
1350 bool IsWebElementEmpty(const blink::WebElement
& element
) {
1351 // This array contains all tags which can be present in an empty page.
1352 const char* const kAllowedValue
[] = {
1357 const size_t kAllowedValueLength
= arraysize(kAllowedValue
);
1359 if (element
.isNull())
1361 // The childNodes method is not a const method. Therefore it cannot be called
1362 // on a const reference. Therefore we need a const cast.
1363 const blink::WebNodeList
& children
=
1364 const_cast<blink::WebElement
&>(element
).childNodes();
1365 for (size_t i
= 0; i
< children
.length(); ++i
) {
1366 const blink::WebNode
& item
= children
.item(i
);
1368 if (item
.isTextNode() &&
1369 !base::ContainsOnlyChars(item
.nodeValue().utf8(),
1370 base::kWhitespaceASCII
))
1373 // We ignore all other items with names which begin with
1374 // the character # because they are not html tags.
1375 if (item
.nodeName().utf8()[0] == '#')
1378 bool tag_is_allowed
= false;
1379 // Test if the item name is in the kAllowedValue array
1380 for (size_t allowed_value_index
= 0;
1381 allowed_value_index
< kAllowedValueLength
; ++allowed_value_index
) {
1382 if (HasTagName(item
,
1383 WebString::fromUTF8(kAllowedValue
[allowed_value_index
]))) {
1384 tag_is_allowed
= true;
1388 if (!tag_is_allowed
)
1394 gfx::RectF
GetScaledBoundingBox(float scale
, WebElement
* element
) {
1395 gfx::Rect
bounding_box(element
->boundsInViewportSpace());
1396 return gfx::RectF(bounding_box
.x() * scale
,
1397 bounding_box
.y() * scale
,
1398 bounding_box
.width() * scale
,
1399 bounding_box
.height() * scale
);
1402 } // namespace autofill