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