David
David

Reputation: 3821

Get GMail's "To" Field in a Chrome Extension

I am writing a Google Chrome Extension that needs to capture addresses in the "To" field of a new GMail e-mail. This is what I currently am working with (jQuery 2.0.2 is being used):

$('textarea[name="to"]').bind("enterKey",function(e){
        alert($('textarea[name="to"]').val()); // this is definitely the "To" field
});
$('textarea').keyup(function(e){
        if(e.keyCode == 13) {
        $(this).trigger("enterKey");
}
});

Each time I press Enter in the To field with the code above, an empty alert() box fires. However, if I change the alert() to display an arbitrary value, like alert('david'); the message david is inside the alert box.

My question is, why is there an empty string coming off of the "To" field's .val() when I press Enter?

Thanks!

Upvotes: 0

Views: 343

Answers (1)

Okan Kocyigit
Okan Kocyigit

Reputation: 13421

Gmail's to Field doesn't work like a textarea, It takes the email from text and creates a div for each email before the text area.

You should inspect DOM to see what is going on there.

Here is the related part of code.

<div class="vR">
  <span class="vN vQ" email="[email protected]">
    <div class="vT">email1</div>
    <div class="vM"></div>
  </span>
  <input name="to" type="hidden" value="email1">
</div>
<div class="vR">
  <span class="vN vQ" email="[email protected]">
    <div class="vT">email2</div>
    <div class="vM"></div>
  </span>
  <input name="to" type="hidden" value="email2">
</div>
<textarea rows="1" id=":2y" class="vO" name="to" spellcheck="false" autocomplete="false" tabindex="1" dir="ltr" aria-haspopup="true" style="width: 950px;"></textarea>

So you can get the emails like this,

$('textarea[name="to"]').bind("enterKey", function(e){
    var emails = [];
    $(this).siblings("div.vR").find("span.vN").each(function() {
      emails.push($(this).attr("email"));
    })
    alert(emails.join(", "));
});

Upvotes: 4

Related Questions