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 // Helper for |InferLabelForElement()| that infers a label, if possible, from
234 // a previous sibling of |element|,
235 // e.g. Some Text <input ...>
236 // or Some <span>Text</span> <input ...>
237 // or <p>Some Text</p><input ...>
238 // or <label>Some Text</label> <input ...>
239 // or Some Text <img><input ...>
240 // or <b>Some Text</b><br/> <input ...>.
241 base::string16
InferLabelFromPrevious(const WebFormControlElement
& element
) {
242 base::string16 inferred_label
;
243 WebNode previous
= element
;
245 previous
= previous
.previousSibling();
246 if (previous
.isNull())
249 // Skip over comments.
250 WebNode::NodeType node_type
= previous
.nodeType();
251 if (node_type
== WebNode::CommentNode
)
254 // Otherwise, only consider normal HTML elements and their contents.
255 if (node_type
!= WebNode::TextNode
&&
256 node_type
!= WebNode::ElementNode
)
259 // A label might be split across multiple "lightweight" nodes.
260 // Coalesce any text contained in multiple consecutive
261 // (a) plain text nodes or
262 // (b) inline HTML elements that are essentially equivalent to text nodes.
263 CR_DEFINE_STATIC_LOCAL(WebString
, kBold
, ("b"));
264 CR_DEFINE_STATIC_LOCAL(WebString
, kStrong
, ("strong"));
265 CR_DEFINE_STATIC_LOCAL(WebString
, kSpan
, ("span"));
266 CR_DEFINE_STATIC_LOCAL(WebString
, kFont
, ("font"));
267 if (previous
.isTextNode() ||
268 HasTagName(previous
, kBold
) || HasTagName(previous
, kStrong
) ||
269 HasTagName(previous
, kSpan
) || HasTagName(previous
, kFont
)) {
270 base::string16 value
= FindChildText(previous
);
271 // A text node's value will be empty if it is for a line break.
272 bool add_space
= previous
.isTextNode() && value
.empty();
274 CombineAndCollapseWhitespace(value
, inferred_label
, add_space
);
278 // If we have identified a partial label and have reached a non-lightweight
279 // element, consider the label to be complete.
280 base::string16 trimmed_label
;
281 base::TrimWhitespace(inferred_label
, base::TRIM_ALL
, &trimmed_label
);
282 if (!trimmed_label
.empty())
285 // <img> and <br> tags often appear between the input element and its
286 // label text, so skip over them.
287 CR_DEFINE_STATIC_LOCAL(WebString
, kImage
, ("img"));
288 CR_DEFINE_STATIC_LOCAL(WebString
, kBreak
, ("br"));
289 if (HasTagName(previous
, kImage
) || HasTagName(previous
, kBreak
))
292 // We only expect <p> and <label> tags to contain the full label text.
293 CR_DEFINE_STATIC_LOCAL(WebString
, kPage
, ("p"));
294 CR_DEFINE_STATIC_LOCAL(WebString
, kLabel
, ("label"));
295 if (HasTagName(previous
, kPage
) || HasTagName(previous
, kLabel
))
296 inferred_label
= FindChildText(previous
);
301 base::TrimWhitespace(inferred_label
, base::TRIM_ALL
, &inferred_label
);
302 return inferred_label
;
305 // Helper for |InferLabelForElement()| that infers a label, if possible, from
307 base::string16
InferLabelFromPlaceholder(const WebFormControlElement
& element
) {
308 CR_DEFINE_STATIC_LOCAL(WebString
, kPlaceholder
, ("placeholder"));
309 if (element
.hasAttribute(kPlaceholder
))
310 return element
.getAttribute(kPlaceholder
);
312 return base::string16();
315 // Helper for |InferLabelForElement()| that infers a label, if possible, from
316 // enclosing list item,
317 // e.g. <li>Some Text<input ...><input ...><input ...></tr>
318 base::string16
InferLabelFromListItem(const WebFormControlElement
& element
) {
319 WebNode parent
= element
.parentNode();
320 CR_DEFINE_STATIC_LOCAL(WebString
, kListItem
, ("li"));
321 while (!parent
.isNull() && parent
.isElementNode() &&
322 !parent
.to
<WebElement
>().hasHTMLTagName(kListItem
)) {
323 parent
= parent
.parentNode();
326 if (!parent
.isNull() && HasTagName(parent
, kListItem
))
327 return FindChildText(parent
);
329 return base::string16();
332 // Helper for |InferLabelForElement()| that infers a label, if possible, from
333 // surrounding table structure,
334 // e.g. <tr><td>Some Text</td><td><input ...></td></tr>
335 // or <tr><th>Some Text</th><td><input ...></td></tr>
336 // or <tr><td><b>Some Text</b></td><td><b><input ...></b></td></tr>
337 // or <tr><th><b>Some Text</b></th><td><b><input ...></b></td></tr>
338 base::string16
InferLabelFromTableColumn(const WebFormControlElement
& element
) {
339 CR_DEFINE_STATIC_LOCAL(WebString
, kTableCell
, ("td"));
340 WebNode parent
= element
.parentNode();
341 while (!parent
.isNull() && parent
.isElementNode() &&
342 !parent
.to
<WebElement
>().hasHTMLTagName(kTableCell
)) {
343 parent
= parent
.parentNode();
347 return base::string16();
349 // Check all previous siblings, skipping non-element nodes, until we find a
350 // non-empty text block.
351 base::string16 inferred_label
;
352 WebNode previous
= parent
.previousSibling();
353 CR_DEFINE_STATIC_LOCAL(WebString
, kTableHeader
, ("th"));
354 while (inferred_label
.empty() && !previous
.isNull()) {
355 if (HasTagName(previous
, kTableCell
) || HasTagName(previous
, kTableHeader
))
356 inferred_label
= FindChildText(previous
);
358 previous
= previous
.previousSibling();
361 return inferred_label
;
364 // Helper for |InferLabelForElement()| that infers a label, if possible, from
365 // surrounding table structure,
366 // e.g. <tr><td>Some Text</td></tr><tr><td><input ...></td></tr>
367 base::string16
InferLabelFromTableRow(const WebFormControlElement
& element
) {
368 CR_DEFINE_STATIC_LOCAL(WebString
, kTableRow
, ("tr"));
369 WebNode parent
= element
.parentNode();
370 while (!parent
.isNull() && parent
.isElementNode() &&
371 !parent
.to
<WebElement
>().hasHTMLTagName(kTableRow
)) {
372 parent
= parent
.parentNode();
376 return base::string16();
378 // Check all previous siblings, skipping non-element nodes, until we find a
379 // non-empty text block.
380 base::string16 inferred_label
;
381 WebNode previous
= parent
.previousSibling();
382 while (inferred_label
.empty() && !previous
.isNull()) {
383 if (HasTagName(previous
, kTableRow
))
384 inferred_label
= FindChildText(previous
);
386 previous
= previous
.previousSibling();
389 return inferred_label
;
392 // Helper for |InferLabelForElement()| that infers a label, if possible, from
393 // a surrounding div table,
394 // e.g. <div>Some Text<span><input ...></span></div>
395 // e.g. <div>Some Text</div><div><input ...></div>
396 base::string16
InferLabelFromDivTable(const WebFormControlElement
& element
) {
397 WebNode node
= element
.parentNode();
398 bool looking_for_parent
= true;
400 // Search the sibling and parent <div>s until we find a candidate label.
401 base::string16 inferred_label
;
402 CR_DEFINE_STATIC_LOCAL(WebString
, kDiv
, ("div"));
403 CR_DEFINE_STATIC_LOCAL(WebString
, kTable
, ("table"));
404 CR_DEFINE_STATIC_LOCAL(WebString
, kFieldSet
, ("fieldset"));
405 while (inferred_label
.empty() && !node
.isNull()) {
406 if (HasTagName(node
, kDiv
)) {
407 looking_for_parent
= false;
408 inferred_label
= FindChildText(node
);
409 } else if (looking_for_parent
&&
410 (HasTagName(node
, kTable
) || HasTagName(node
, kFieldSet
))) {
411 // If the element is in a table or fieldset, its label most likely is too.
415 if (node
.previousSibling().isNull()) {
416 // If there are no more siblings, continue walking up the tree.
417 looking_for_parent
= true;
420 if (looking_for_parent
)
421 node
= node
.parentNode();
423 node
= node
.previousSibling();
426 return inferred_label
;
429 // Helper for |InferLabelForElement()| that infers a label, if possible, from
430 // a surrounding definition list,
431 // e.g. <dl><dt>Some Text</dt><dd><input ...></dd></dl>
432 // e.g. <dl><dt><b>Some Text</b></dt><dd><b><input ...></b></dd></dl>
433 base::string16
InferLabelFromDefinitionList(
434 const WebFormControlElement
& element
) {
435 CR_DEFINE_STATIC_LOCAL(WebString
, kDefinitionData
, ("dd"));
436 WebNode parent
= element
.parentNode();
437 while (!parent
.isNull() && parent
.isElementNode() &&
438 !parent
.to
<WebElement
>().hasHTMLTagName(kDefinitionData
))
439 parent
= parent
.parentNode();
441 if (parent
.isNull() || !HasTagName(parent
, kDefinitionData
))
442 return base::string16();
444 // Skip by any intervening text nodes.
445 WebNode previous
= parent
.previousSibling();
446 while (!previous
.isNull() && previous
.isTextNode())
447 previous
= previous
.previousSibling();
449 CR_DEFINE_STATIC_LOCAL(WebString
, kDefinitionTag
, ("dt"));
450 if (previous
.isNull() || !HasTagName(previous
, kDefinitionTag
))
451 return base::string16();
453 return FindChildText(previous
);
456 // Returns true if the closest ancestor is a <div> and not a <td>.
457 // Returns false if the closest ancestor is a <td> tag,
458 // or if there is no <div> or <td> ancestor.
459 bool ClosestAncestorIsDivAndNotTD(const WebFormControlElement
& element
) {
460 for (WebNode parent_node
= element
.parentNode();
461 !parent_node
.isNull();
462 parent_node
= parent_node
.parentNode()) {
463 if (!parent_node
.isElementNode())
466 WebElement cur_element
= parent_node
.to
<WebElement
>();
467 if (cur_element
.hasHTMLTagName("div"))
469 if (cur_element
.hasHTMLTagName("td"))
475 // Infers corresponding label for |element| from surrounding context in the DOM,
476 // e.g. the contents of the preceding <p> tag or text element.
477 base::string16
InferLabelForElement(const WebFormControlElement
& element
) {
478 base::string16 inferred_label
= InferLabelFromPrevious(element
);
479 if (!inferred_label
.empty())
480 return inferred_label
;
482 // If we didn't find a label, check for placeholder text.
483 inferred_label
= InferLabelFromPlaceholder(element
);
484 if (!inferred_label
.empty())
485 return inferred_label
;
487 // If we didn't find a label, check for list item case.
488 inferred_label
= InferLabelFromListItem(element
);
489 if (!inferred_label
.empty())
490 return inferred_label
;
492 // If we didn't find a label, check for definition list case.
493 inferred_label
= InferLabelFromDefinitionList(element
);
494 if (!inferred_label
.empty())
495 return inferred_label
;
497 bool check_div_first
= ClosestAncestorIsDivAndNotTD(element
);
498 if (check_div_first
) {
499 // If we didn't find a label, check for div table case first since it's the
501 inferred_label
= InferLabelFromDivTable(element
);
502 if (!inferred_label
.empty())
503 return inferred_label
;
506 // If we didn't find a label, check for table cell case.
507 inferred_label
= InferLabelFromTableColumn(element
);
508 if (!inferred_label
.empty())
509 return inferred_label
;
511 // If we didn't find a label, check for table row case.
512 inferred_label
= InferLabelFromTableRow(element
);
513 if (!inferred_label
.empty())
514 return inferred_label
;
516 if (!check_div_first
) {
517 // If we didn't find a label from the table, check for div table case if we
519 inferred_label
= InferLabelFromDivTable(element
);
521 return inferred_label
;
524 // Fills |option_strings| with the values of the <option> elements present in
526 void GetOptionStringsFromElement(const WebSelectElement
& select_element
,
527 std::vector
<base::string16
>* option_values
,
528 std::vector
<base::string16
>* option_contents
) {
529 DCHECK(!select_element
.isNull());
531 option_values
->clear();
532 option_contents
->clear();
533 WebVector
<WebElement
> list_items
= select_element
.listItems();
535 // Constrain the maximum list length to prevent a malicious site from DOS'ing
536 // the browser, without entirely breaking autocomplete for some extreme
537 // legitimate sites: http://crbug.com/49332 and http://crbug.com/363094
538 if (list_items
.size() > kMaxListSize
)
541 option_values
->reserve(list_items
.size());
542 option_contents
->reserve(list_items
.size());
543 for (size_t i
= 0; i
< list_items
.size(); ++i
) {
544 if (IsOptionElement(list_items
[i
])) {
545 const WebOptionElement option
= list_items
[i
].toConst
<WebOptionElement
>();
546 option_values
->push_back(option
.value());
547 option_contents
->push_back(option
.text());
552 // The callback type used by |ForEachMatchingFormField()|.
553 typedef void (*Callback
)(const FormFieldData
&,
554 bool, /* is_initiating_element */
555 blink::WebFormControlElement
*);
557 void ForEachMatchingFormFieldCommon(
558 std::vector
<WebFormControlElement
>* control_elements
,
559 const WebElement
& initiating_element
,
560 const FormData
& data
,
561 FieldFilterMask filters
,
564 DCHECK(control_elements
);
565 if (control_elements
->size() != data
.fields
.size()) {
566 // This case should be reachable only for pathological websites and tests,
567 // which add or remove form fields while the user is interacting with the
572 // It's possible that the site has injected fields into the form after the
573 // page has loaded, so we can't assert that the size of the cached control
574 // elements is equal to the size of the fields in |form|. Fortunately, the
575 // one case in the wild where this happens, paypal.com signup form, the fields
576 // are appended to the end of the form and are not visible.
577 for (size_t i
= 0; i
< control_elements
->size(); ++i
) {
578 WebFormControlElement
* element
= &(*control_elements
)[i
];
580 if (base::string16(element
->nameForAutofill()) != data
.fields
[i
].name
) {
581 // This case should be reachable only for pathological websites, which
582 // rename form fields while the user is interacting with the Autofill
583 // popup. I (isherman) am not aware of any such websites, and so am
584 // optimistically including a NOTREACHED(). If you ever trip this check,
585 // please file a bug against me.
590 bool is_initiating_element
= (*element
== initiating_element
);
592 // Only autofill empty fields and the field that initiated the filling,
593 // i.e. the field the user is currently editing and interacting with.
594 const WebInputElement
* input_element
= toWebInputElement(element
);
595 if (!force_override
&& !is_initiating_element
&&
596 ((IsAutofillableInputElement(input_element
) ||
597 IsTextAreaElement(*element
)) &&
598 !element
->value().isEmpty()))
601 if (((filters
& FILTER_DISABLED_ELEMENTS
) && !element
->isEnabled()) ||
602 ((filters
& FILTER_READONLY_ELEMENTS
) && element
->isReadOnly()) ||
603 ((filters
& FILTER_NON_FOCUSABLE_ELEMENTS
) && !element
->isFocusable()))
606 callback(data
.fields
[i
], is_initiating_element
, element
);
610 // For each autofillable field in |data| that matches a field in the |form|,
611 // the |callback| is invoked with the corresponding |form| field data.
612 void ForEachMatchingFormField(const WebFormElement
& form_element
,
613 const WebElement
& initiating_element
,
614 const FormData
& data
,
615 FieldFilterMask filters
,
618 std::vector
<WebFormControlElement
> control_elements
=
619 ExtractAutofillableElementsInForm(form_element
, ExtractionRequirements());
620 ForEachMatchingFormFieldCommon(&control_elements
, initiating_element
, data
,
621 filters
, force_override
, callback
);
624 // For each autofillable field in |data| that matches a field in the set of
625 // unowned autofillable form fields, the |callback| is invoked with the
626 // corresponding |data| field.
627 void ForEachMatchingUnownedFormField(const WebElement
& initiating_element
,
628 const FormData
& data
,
629 FieldFilterMask filters
,
632 if (initiating_element
.isNull())
635 std::vector
<WebFormControlElement
> control_elements
=
636 GetUnownedAutofillableFormFieldElements(
637 initiating_element
.document().all(), nullptr);
638 if (!IsElementInControlElementSet(initiating_element
, control_elements
))
641 ForEachMatchingFormFieldCommon(&control_elements
, initiating_element
, data
,
642 filters
, force_override
, callback
);
645 // Sets the |field|'s value to the value in |data|.
646 // Also sets the "autofilled" attribute, causing the background to be yellow.
647 void FillFormField(const FormFieldData
& data
,
648 bool is_initiating_node
,
649 blink::WebFormControlElement
* field
) {
651 if (data
.value
.empty())
654 if (!data
.is_autofilled
)
657 WebInputElement
* input_element
= toWebInputElement(field
);
658 if (IsCheckableElement(input_element
)) {
659 input_element
->setChecked(data
.is_checked
, true);
661 base::string16 value
= data
.value
;
662 if (IsTextInput(input_element
) || IsMonthInput(input_element
)) {
663 // If the maxlength attribute contains a negative value, maxLength()
664 // returns the default maxlength value.
665 TruncateString(&value
, input_element
->maxLength());
667 field
->setValue(value
, true);
670 field
->setAutofilled(true);
672 if (is_initiating_node
&&
673 ((IsTextInput(input_element
) || IsMonthInput(input_element
)) ||
674 IsTextAreaElement(*field
))) {
675 int length
= field
->value().length();
676 field
->setSelectionRange(length
, length
);
677 // Clear the current IME composition (the underline), if there is one.
678 field
->document().frame()->unmarkText();
682 // Sets the |field|'s "suggested" (non JS visible) value to the value in |data|.
683 // Also sets the "autofilled" attribute, causing the background to be yellow.
684 void PreviewFormField(const FormFieldData
& data
,
685 bool is_initiating_node
,
686 blink::WebFormControlElement
* field
) {
687 // Nothing to preview.
688 if (data
.value
.empty())
691 if (!data
.is_autofilled
)
694 // Preview input, textarea and select fields. For input fields, excludes
695 // checkboxes and radio buttons, as there is no provision for
696 // setSuggestedCheckedValue in WebInputElement.
697 WebInputElement
* input_element
= toWebInputElement(field
);
698 if (IsTextInput(input_element
) || IsMonthInput(input_element
)) {
699 // If the maxlength attribute contains a negative value, maxLength()
700 // returns the default maxlength value.
701 input_element
->setSuggestedValue(
702 data
.value
.substr(0, input_element
->maxLength()));
703 input_element
->setAutofilled(true);
704 } else if (IsTextAreaElement(*field
) || IsSelectElement(*field
)) {
705 field
->setSuggestedValue(data
.value
);
706 field
->setAutofilled(true);
709 if (is_initiating_node
&&
710 (IsTextInput(input_element
) || IsTextAreaElement(*field
))) {
711 // Select the part of the text that the user didn't type.
712 int start
= field
->value().length();
713 int end
= field
->suggestedValue().length();
714 field
->setSelectionRange(start
, end
);
718 // Recursively checks whether |node| or any of its children have a non-empty
719 // bounding box. The recursion depth is bounded by |depth|.
720 bool IsWebNodeVisibleImpl(const blink::WebNode
& node
, const int depth
) {
723 if (node
.hasNonEmptyBoundingBox())
726 // The childNodes method is not a const method. Therefore it cannot be called
727 // on a const reference. Therefore we need a const cast.
728 const blink::WebNodeList
& children
=
729 const_cast<blink::WebNode
&>(node
).childNodes();
730 size_t length
= children
.length();
731 for (size_t i
= 0; i
< length
; ++i
) {
732 const blink::WebNode
& item
= children
.item(i
);
733 if (IsWebNodeVisibleImpl(item
, depth
- 1))
739 bool ExtractFieldsFromControlElements(
740 const WebVector
<WebFormControlElement
>& control_elements
,
741 RequirementsMask requirements
,
742 ExtractMask extract_mask
,
743 ScopedVector
<FormFieldData
>* form_fields
,
744 std::vector
<bool>* fields_extracted
,
745 std::map
<WebFormControlElement
, FormFieldData
*>* element_map
) {
746 for (size_t i
= 0; i
< control_elements
.size(); ++i
) {
747 const WebFormControlElement
& control_element
= control_elements
[i
];
749 if (!IsAutofillableElement(control_element
))
752 const WebInputElement
* input_element
= toWebInputElement(&control_element
);
753 if (requirements
& REQUIRE_AUTOCOMPLETE
&&
754 IsAutofillableInputElement(input_element
) &&
755 !SatisfiesRequireAutocomplete(*input_element
))
758 // Create a new FormFieldData, fill it out and map it to the field's name.
759 FormFieldData
* form_field
= new FormFieldData
;
760 WebFormControlElementToFormField(control_element
, extract_mask
, form_field
);
761 form_fields
->push_back(form_field
);
762 (*element_map
)[control_element
] = form_field
;
763 (*fields_extracted
)[i
] = true;
766 // If we failed to extract any fields, give up. Also, to avoid overly
767 // expensive computation, we impose a maximum number of allowable fields.
768 if (form_fields
->empty() || form_fields
->size() > kMaxParseableFields
)
773 // For each label element, get the corresponding form control element, use the
774 // form control element's name as a key into the
775 // <WebFormControlElement, FormFieldData> map to find the previously created
776 // FormFieldData and set the FormFieldData's label to the
777 // label.firstChild().nodeValue() of the label element.
778 void MatchLabelsAndFields(
779 const WebElementCollection
& labels
,
780 std::map
<WebFormControlElement
, FormFieldData
*>* element_map
) {
781 CR_DEFINE_STATIC_LOCAL(WebString
, kFor
, ("for"));
782 CR_DEFINE_STATIC_LOCAL(WebString
, kHidden
, ("hidden"));
784 for (WebElement item
= labels
.firstItem(); !item
.isNull();
785 item
= labels
.nextItem()) {
786 WebLabelElement label
= item
.to
<WebLabelElement
>();
787 WebFormControlElement field_element
=
788 label
.correspondingControl().to
<WebFormControlElement
>();
789 FormFieldData
* field_data
= nullptr;
791 if (field_element
.isNull()) {
792 // Sometimes site authors will incorrectly specify the corresponding
793 // field element's name rather than its id, so we compensate here.
794 base::string16 element_name
= label
.getAttribute(kFor
);
795 if (element_name
.empty())
797 // Look through the list for elements with this name. There can actually
798 // be more than one. In this case, the label may not be particularly
799 // useful, so just discard it.
800 for (const auto& iter
: *element_map
) {
801 if (iter
.second
->name
== element_name
) {
803 field_data
= nullptr;
806 field_data
= iter
.second
;
810 } else if (!field_element
.isFormControlElement() ||
811 field_element
.formControlType() == kHidden
) {
814 // Typical case: look up |field_data| in |element_map|.
815 auto iter
= element_map
->find(field_element
);
816 if (iter
== element_map
->end())
818 field_data
= iter
->second
;
824 base::string16 label_text
= FindChildText(label
);
826 // Concatenate labels because some sites might have multiple label
828 if (!field_data
->label
.empty() && !label_text
.empty())
829 field_data
->label
+= base::ASCIIToUTF16(" ");
830 field_data
->label
+= label_text
;
834 // Common function shared by WebFormElementToFormData() and
835 // UnownedFormElementsAndFieldSetsToFormData(). Either pass in:
836 // 1) |form_element| and an empty |fieldsets|.
838 // 2) a NULL |form_element|.
840 // If |field| is not NULL, then |form_control_element| should be not NULL.
841 bool FormOrFieldsetsToFormData(
842 const blink::WebFormElement
* form_element
,
843 const blink::WebFormControlElement
* form_control_element
,
844 const std::vector
<blink::WebElement
>& fieldsets
,
845 const WebVector
<WebFormControlElement
>& control_elements
,
846 RequirementsMask requirements
,
847 ExtractMask extract_mask
,
849 FormFieldData
* field
) {
850 CR_DEFINE_STATIC_LOCAL(WebString
, kLabel
, ("label"));
853 DCHECK(fieldsets
.empty());
855 DCHECK(form_control_element
);
857 // A map from a FormFieldData's name to the FormFieldData itself.
858 std::map
<WebFormControlElement
, FormFieldData
*> element_map
;
860 // The extracted FormFields. We use pointers so we can store them in
862 ScopedVector
<FormFieldData
> form_fields
;
864 // A vector of bools that indicate whether each field in the form meets the
865 // requirements and thus will be in the resulting |form|.
866 std::vector
<bool> fields_extracted(control_elements
.size(), false);
868 if (!ExtractFieldsFromControlElements(control_elements
, requirements
,
869 extract_mask
, &form_fields
,
870 &fields_extracted
, &element_map
)) {
875 // Loop through the label elements inside the form element. For each label
876 // element, get the corresponding form control element, use the form control
877 // element's name as a key into the <name, FormFieldData> map to find the
878 // previously created FormFieldData and set the FormFieldData's label to the
879 // label.firstChild().nodeValue() of the label element.
880 WebElementCollection labels
=
881 form_element
->getElementsByHTMLTagName(kLabel
);
882 DCHECK(!labels
.isNull());
883 MatchLabelsAndFields(labels
, &element_map
);
885 // Same as the if block, but for all the labels in fieldsets.
886 for (size_t i
= 0; i
< fieldsets
.size(); ++i
) {
887 WebElementCollection labels
=
888 fieldsets
[i
].getElementsByHTMLTagName(kLabel
);
889 DCHECK(!labels
.isNull());
890 MatchLabelsAndFields(labels
, &element_map
);
894 // Loop through the form control elements, extracting the label text from
895 // the DOM. We use the |fields_extracted| vector to make sure we assign the
896 // extracted label to the correct field, as it's possible |form_fields| will
897 // not contain all of the elements in |control_elements|.
898 for (size_t i
= 0, field_idx
= 0;
899 i
< control_elements
.size() && field_idx
< form_fields
.size(); ++i
) {
900 // This field didn't meet the requirements, so don't try to find a label
902 if (!fields_extracted
[i
])
905 const WebFormControlElement
& control_element
= control_elements
[i
];
906 if (form_fields
[field_idx
]->label
.empty())
907 form_fields
[field_idx
]->label
= InferLabelForElement(control_element
);
908 TruncateString(&form_fields
[field_idx
]->label
, kMaxDataLength
);
910 if (field
&& *form_control_element
== control_element
)
911 *field
= *form_fields
[field_idx
];
916 // Copy the created FormFields into the resulting FormData object.
917 for (const auto& iter
: form_fields
)
918 form
->fields
.push_back(*iter
);
924 const size_t kMaxParseableFields
= 200;
926 bool IsMonthInput(const WebInputElement
* element
) {
927 CR_DEFINE_STATIC_LOCAL(WebString
, kMonth
, ("month"));
928 return element
&& !element
->isNull() && element
->formControlType() == kMonth
;
931 // All text fields, including password fields, should be extracted.
932 bool IsTextInput(const WebInputElement
* element
) {
933 return element
&& !element
->isNull() && element
->isTextField();
936 bool IsSelectElement(const WebFormControlElement
& element
) {
937 // Static for improved performance.
938 CR_DEFINE_STATIC_LOCAL(WebString
, kSelectOne
, ("select-one"));
939 return !element
.isNull() && element
.formControlType() == kSelectOne
;
942 bool IsTextAreaElement(const WebFormControlElement
& element
) {
943 // Static for improved performance.
944 CR_DEFINE_STATIC_LOCAL(WebString
, kTextArea
, ("textarea"));
945 return !element
.isNull() && element
.formControlType() == kTextArea
;
948 bool IsCheckableElement(const WebInputElement
* element
) {
949 if (!element
|| element
->isNull())
952 return element
->isCheckbox() || element
->isRadioButton();
955 bool IsAutofillableInputElement(const WebInputElement
* element
) {
956 return IsTextInput(element
) ||
957 IsMonthInput(element
) ||
958 IsCheckableElement(element
);
961 const base::string16
GetFormIdentifier(const WebFormElement
& form
) {
962 base::string16 identifier
= form
.name();
963 CR_DEFINE_STATIC_LOCAL(WebString
, kId
, ("id"));
964 if (identifier
.empty())
965 identifier
= form
.getAttribute(kId
);
970 bool IsWebNodeVisible(const blink::WebNode
& node
) {
971 // In the bug http://crbug.com/237216 the form's bounding box is empty
972 // however the form has non empty children. Thus we need to look at the
974 int kNodeSearchDepth
= 2;
975 return IsWebNodeVisibleImpl(node
, kNodeSearchDepth
);
978 std::vector
<blink::WebFormControlElement
> ExtractAutofillableElementsFromSet(
979 const WebVector
<WebFormControlElement
>& control_elements
,
980 RequirementsMask requirements
) {
981 std::vector
<blink::WebFormControlElement
> autofillable_elements
;
982 for (size_t i
= 0; i
< control_elements
.size(); ++i
) {
983 WebFormControlElement element
= control_elements
[i
];
984 if (!IsAutofillableElement(element
))
987 if (requirements
& REQUIRE_AUTOCOMPLETE
) {
988 // TODO(isherman): WebKit currently doesn't handle the autocomplete
989 // attribute for select or textarea elements, but it probably should.
990 const WebInputElement
* input_element
=
991 toWebInputElement(&control_elements
[i
]);
992 if (IsAutofillableInputElement(input_element
) &&
993 !SatisfiesRequireAutocomplete(*input_element
))
997 autofillable_elements
.push_back(element
);
999 return autofillable_elements
;
1002 std::vector
<WebFormControlElement
> ExtractAutofillableElementsInForm(
1003 const WebFormElement
& form_element
,
1004 RequirementsMask requirements
) {
1005 WebVector
<WebFormControlElement
> control_elements
;
1006 form_element
.getFormControlElements(control_elements
);
1008 return ExtractAutofillableElementsFromSet(control_elements
, requirements
);
1011 void WebFormControlElementToFormField(const WebFormControlElement
& element
,
1012 ExtractMask extract_mask
,
1013 FormFieldData
* field
) {
1015 DCHECK(!element
.isNull());
1016 CR_DEFINE_STATIC_LOCAL(WebString
, kAutocomplete
, ("autocomplete"));
1017 CR_DEFINE_STATIC_LOCAL(WebString
, kRole
, ("role"));
1019 // The label is not officially part of a WebFormControlElement; however, the
1020 // labels for all form control elements are scraped from the DOM and set in
1021 // WebFormElementToFormData.
1022 field
->name
= element
.nameForAutofill();
1023 field
->form_control_type
= base::UTF16ToUTF8(element
.formControlType());
1024 field
->autocomplete_attribute
=
1025 base::UTF16ToUTF8(element
.getAttribute(kAutocomplete
));
1026 if (field
->autocomplete_attribute
.size() > kMaxDataLength
) {
1027 // Discard overly long attribute values to avoid DOS-ing the browser
1028 // process. However, send over a default string to indicate that the
1029 // attribute was present.
1030 field
->autocomplete_attribute
= "x-max-data-length-exceeded";
1032 if (LowerCaseEqualsASCII(element
.getAttribute(kRole
), "presentation"))
1033 field
->role
= FormFieldData::ROLE_ATTRIBUTE_PRESENTATION
;
1035 if (!IsAutofillableElement(element
))
1038 const WebInputElement
* input_element
= toWebInputElement(&element
);
1039 if (IsAutofillableInputElement(input_element
) ||
1040 IsTextAreaElement(element
)) {
1041 field
->is_autofilled
= element
.isAutofilled();
1042 field
->is_focusable
= element
.isFocusable();
1043 field
->should_autocomplete
= element
.autoComplete();
1044 field
->text_direction
= element
.directionForFormData() ==
1045 "rtl" ? base::i18n::RIGHT_TO_LEFT
: base::i18n::LEFT_TO_RIGHT
;
1048 if (IsAutofillableInputElement(input_element
)) {
1049 if (IsTextInput(input_element
))
1050 field
->max_length
= input_element
->maxLength();
1052 field
->is_checkable
= IsCheckableElement(input_element
);
1053 field
->is_checked
= input_element
->isChecked();
1054 } else if (IsTextAreaElement(element
)) {
1055 // Nothing more to do in this case.
1056 } else if (extract_mask
& EXTRACT_OPTIONS
) {
1057 // Set option strings on the field if available.
1058 DCHECK(IsSelectElement(element
));
1059 const WebSelectElement select_element
= element
.toConst
<WebSelectElement
>();
1060 GetOptionStringsFromElement(select_element
,
1061 &field
->option_values
,
1062 &field
->option_contents
);
1065 if (!(extract_mask
& EXTRACT_VALUE
))
1068 base::string16 value
= element
.value();
1070 if (IsSelectElement(element
) && (extract_mask
& EXTRACT_OPTION_TEXT
)) {
1071 const WebSelectElement select_element
= element
.toConst
<WebSelectElement
>();
1072 // Convert the |select_element| value to text if requested.
1073 WebVector
<WebElement
> list_items
= select_element
.listItems();
1074 for (size_t i
= 0; i
< list_items
.size(); ++i
) {
1075 if (IsOptionElement(list_items
[i
])) {
1076 const WebOptionElement option_element
=
1077 list_items
[i
].toConst
<WebOptionElement
>();
1078 if (option_element
.value() == value
) {
1079 value
= option_element
.text();
1086 // Constrain the maximum data length to prevent a malicious site from DOS'ing
1087 // the browser: http://crbug.com/49332
1088 TruncateString(&value
, kMaxDataLength
);
1090 field
->value
= value
;
1093 bool WebFormElementToFormData(
1094 const blink::WebFormElement
& form_element
,
1095 const blink::WebFormControlElement
& form_control_element
,
1096 RequirementsMask requirements
,
1097 ExtractMask extract_mask
,
1099 FormFieldData
* field
) {
1100 const WebFrame
* frame
= form_element
.document().frame();
1104 if (requirements
& REQUIRE_AUTOCOMPLETE
&& !form_element
.autoComplete())
1107 form
->name
= GetFormIdentifier(form_element
);
1108 form
->origin
= frame
->document().url();
1109 form
->action
= frame
->document().completeURL(form_element
.action());
1110 form
->user_submitted
= form_element
.wasUserSubmitted();
1112 // If the completed URL is not valid, just use the action we get from
1114 if (!form
->action
.is_valid())
1115 form
->action
= GURL(form_element
.action());
1117 WebVector
<WebFormControlElement
> control_elements
;
1118 form_element
.getFormControlElements(control_elements
);
1120 std::vector
<blink::WebElement
> dummy_fieldset
;
1121 return FormOrFieldsetsToFormData(&form_element
, &form_control_element
,
1122 dummy_fieldset
, control_elements
,
1123 requirements
, extract_mask
, form
, field
);
1126 std::vector
<WebFormControlElement
>
1127 GetUnownedAutofillableFormFieldElements(
1128 const WebElementCollection
& elements
,
1129 std::vector
<WebElement
>* fieldsets
) {
1130 std::vector
<WebFormControlElement
> unowned_fieldset_children
;
1131 for (WebElement element
= elements
.firstItem();
1133 element
= elements
.nextItem()) {
1134 if (element
.isFormControlElement()) {
1135 WebFormControlElement control
= element
.to
<WebFormControlElement
>();
1136 if (control
.form().isNull())
1137 unowned_fieldset_children
.push_back(control
);
1140 if (fieldsets
&& element
.hasHTMLTagName("fieldset") &&
1141 !IsElementInsideFormOrFieldSet(element
)) {
1142 fieldsets
->push_back(element
);
1145 return ExtractAutofillableElementsFromSet(unowned_fieldset_children
,
1149 bool UnownedFormElementsAndFieldSetsToFormData(
1150 const std::vector
<blink::WebElement
>& fieldsets
,
1151 const std::vector
<blink::WebFormControlElement
>& control_elements
,
1152 const blink::WebFormControlElement
* element
,
1154 RequirementsMask requirements
,
1155 ExtractMask extract_mask
,
1157 FormFieldData
* field
) {
1158 form
->origin
= origin
;
1159 form
->user_submitted
= false;
1161 return FormOrFieldsetsToFormData(nullptr, element
, fieldsets
,
1162 control_elements
, requirements
, extract_mask
,
1166 bool FindFormAndFieldForFormControlElement(const WebFormControlElement
& element
,
1168 FormFieldData
* field
,
1169 RequirementsMask requirements
) {
1170 if (!IsAutofillableElement(element
))
1173 ExtractMask extract_mask
=
1174 static_cast<ExtractMask
>(EXTRACT_VALUE
| EXTRACT_OPTIONS
);
1175 const WebFormElement form_element
= element
.form();
1176 if (form_element
.isNull()) {
1177 // No associated form, try the synthetic form for unowned form elements.
1178 WebDocument document
= element
.document();
1179 std::vector
<WebElement
> fieldsets
;
1180 std::vector
<WebFormControlElement
> control_elements
=
1181 GetUnownedAutofillableFormFieldElements(document
.all(), &fieldsets
);
1182 return UnownedFormElementsAndFieldSetsToFormData(
1183 fieldsets
, control_elements
, &element
, document
.url(), requirements
,
1184 extract_mask
, form
, field
);
1187 return WebFormElementToFormData(form_element
,
1195 void FillForm(const FormData
& form
, const WebFormControlElement
& element
) {
1196 WebFormElement form_element
= element
.form();
1197 if (form_element
.isNull()) {
1198 ForEachMatchingUnownedFormField(element
,
1200 FILTER_ALL_NON_EDITABLE_ELEMENTS
,
1201 false, /* dont force override */
1206 ForEachMatchingFormField(form_element
,
1209 FILTER_ALL_NON_EDITABLE_ELEMENTS
,
1210 false, /* dont force override */
1214 void FillFormIncludingNonFocusableElements(const FormData
& form_data
,
1215 const WebFormElement
& form_element
) {
1216 if (form_element
.isNull()) {
1221 FieldFilterMask filter_mask
= static_cast<FieldFilterMask
>(
1222 FILTER_DISABLED_ELEMENTS
| FILTER_READONLY_ELEMENTS
);
1223 ForEachMatchingFormField(form_element
,
1227 true, /* force override */
1231 void PreviewForm(const FormData
& form
, const WebFormControlElement
& element
) {
1232 WebFormElement form_element
= element
.form();
1233 if (form_element
.isNull()) {
1234 ForEachMatchingUnownedFormField(element
,
1236 FILTER_ALL_NON_EDITABLE_ELEMENTS
,
1237 false, /* dont force override */
1242 ForEachMatchingFormField(form_element
,
1245 FILTER_ALL_NON_EDITABLE_ELEMENTS
,
1246 false, /* dont force override */
1250 bool ClearPreviewedFormWithElement(const WebFormControlElement
& element
,
1251 bool was_autofilled
) {
1252 WebFormElement form_element
= element
.form();
1253 std::vector
<WebFormControlElement
> control_elements
;
1254 if (form_element
.isNull()) {
1255 control_elements
= GetUnownedAutofillableFormFieldElements(
1256 element
.document().all(), nullptr);
1257 if (!IsElementInControlElementSet(element
, control_elements
))
1260 control_elements
= ExtractAutofillableElementsInForm(
1261 form_element
, ExtractionRequirements());
1264 for (size_t i
= 0; i
< control_elements
.size(); ++i
) {
1265 // There might be unrelated elements in this form which have already been
1266 // auto-filled. For example, the user might have already filled the address
1267 // part of a form and now be dealing with the credit card section. We only
1268 // want to reset the auto-filled status for fields that were previewed.
1269 WebFormControlElement control_element
= control_elements
[i
];
1271 // Only text input, textarea and select elements can be previewed.
1272 WebInputElement
* input_element
= toWebInputElement(&control_element
);
1273 if (!IsTextInput(input_element
) &&
1274 !IsMonthInput(input_element
) &&
1275 !IsTextAreaElement(control_element
) &&
1276 !IsSelectElement(control_element
))
1279 // If the element is not auto-filled, we did not preview it,
1280 // so there is nothing to reset.
1281 if (!control_element
.isAutofilled())
1284 if ((IsTextInput(input_element
) ||
1285 IsMonthInput(input_element
) ||
1286 IsTextAreaElement(control_element
) ||
1287 IsSelectElement(control_element
)) &&
1288 control_element
.suggestedValue().isEmpty())
1291 // Clear the suggested value. For the initiating node, also restore the
1293 if (IsTextInput(input_element
) || IsMonthInput(input_element
) ||
1294 IsTextAreaElement(control_element
)) {
1295 control_element
.setSuggestedValue(WebString());
1296 bool is_initiating_node
= (element
== control_element
);
1297 if (is_initiating_node
) {
1298 control_element
.setAutofilled(was_autofilled
);
1299 // Clearing the suggested value in the focused node (above) can cause
1300 // selection to be lost. We force selection range to restore the text
1302 int length
= control_element
.value().length();
1303 control_element
.setSelectionRange(length
, length
);
1305 control_element
.setAutofilled(false);
1307 } else if (IsSelectElement(control_element
)) {
1308 control_element
.setSuggestedValue(WebString());
1309 control_element
.setAutofilled(false);
1316 bool IsWebpageEmpty(const blink::WebFrame
* frame
) {
1317 blink::WebDocument document
= frame
->document();
1319 return IsWebElementEmpty(document
.head()) &&
1320 IsWebElementEmpty(document
.body());
1323 bool IsWebElementEmpty(const blink::WebElement
& element
) {
1324 // This array contains all tags which can be present in an empty page.
1325 const char* const kAllowedValue
[] = {
1330 const size_t kAllowedValueLength
= arraysize(kAllowedValue
);
1332 if (element
.isNull())
1334 // The childNodes method is not a const method. Therefore it cannot be called
1335 // on a const reference. Therefore we need a const cast.
1336 const blink::WebNodeList
& children
=
1337 const_cast<blink::WebElement
&>(element
).childNodes();
1338 for (size_t i
= 0; i
< children
.length(); ++i
) {
1339 const blink::WebNode
& item
= children
.item(i
);
1341 if (item
.isTextNode() &&
1342 !base::ContainsOnlyChars(item
.nodeValue().utf8(),
1343 base::kWhitespaceASCII
))
1346 // We ignore all other items with names which begin with
1347 // the character # because they are not html tags.
1348 if (item
.nodeName().utf8()[0] == '#')
1351 bool tag_is_allowed
= false;
1352 // Test if the item name is in the kAllowedValue array
1353 for (size_t allowed_value_index
= 0;
1354 allowed_value_index
< kAllowedValueLength
; ++allowed_value_index
) {
1355 if (HasTagName(item
,
1356 WebString::fromUTF8(kAllowedValue
[allowed_value_index
]))) {
1357 tag_is_allowed
= true;
1361 if (!tag_is_allowed
)
1367 gfx::RectF
GetScaledBoundingBox(float scale
, WebElement
* element
) {
1368 gfx::Rect
bounding_box(element
->boundsInViewportSpace());
1369 return gfx::RectF(bounding_box
.x() * scale
,
1370 bounding_box
.y() * scale
,
1371 bounding_box
.width() * scale
,
1372 bounding_box
.height() * scale
);
1375 } // namespace autofill