1// Copyright (c) 2011 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.
4
5// The background page is asking us to find an address on the page.
6if (window == top) {
7  chrome.extension.onRequest.addListener(function(req, sender, sendResponse) {
8    sendResponse(findAddress());
9  });
10}
11
12// Search the text nodes for a US-style mailing address.
13// Return null if none is found.
14var findAddress = function() {
15  var found;
16  var re = /(\d+\s+[':.,\s\w]*,\s*[A-Za-z]+\s*\d{5}(-\d{4})?)/m;
17  var node = document.body;
18  var done = false;
19  while (!done) {
20    done = true;
21    for (var i = 0; i < node.childNodes.length; ++i) {
22      var child = node.childNodes[i];
23      if (child.textContent.match(re)) {
24        node = child;
25        found = node;
26        done = false;
27        break;
28      }
29    }
30  }
31  if (found) {
32    var text = "";
33    if (found.childNodes.length) {
34      for (var i = 0; i < found.childNodes.length; ++i) {
35        text += found.childNodes[i].textContent + " ";
36      }
37    } else {
38      text = found.textContent;
39    }
40    var match = re.exec(text);
41    if (match && match.length) {
42      console.log("found: " + match[0]);
43      var trim = /\s{2,}/g;
44      return match[0].replace(trim, " ");
45    } else {
46      console.log("bad initial match: " + found.textContent);
47      console.log("no match in: " + text);
48    }
49  }
50  return null;
51}
52
53