How to capture span content by JavaScript

4

In the WhatsApp Web, every message sent is stored in a span . I need to assign the value of the last message sent by the caller to a variable, as I do with the contents of the "Send a message" box:

var textbox = document.querySelector('#main > footer > div.block-compose > div.input-container > div.pluggable-input.pluggable-input-compose > div.pluggable-input-body.copyable-text.selectable-text');
alert(textbox.textContent); 

I imagine that I need to get the contents of the last white span (blue line in the image above), but I'm not getting it.

I tried the following, but the return is null :

var ultima = document.querySelector('#main > div.pane-body.pane-chat-tile-container > div.copyable-area > div.pane-chat-msgs.pane-chat-body.lastTabIndex > div._9tCEa > div.msg.msg-group > div.message.message-chat.message-in.tail.message-chat > div.bubble.bubble-text.has-author.copyable-text > div._3zb-j.ZhF0n > span.emojitext.selectable-text.invisible-space.copyable-text');
alert(ultima);

I'm running the script in the same Console when I click F12 on WhatsApp Web.

    
asked by anonymous 20.12.2017 / 17:27

1 answer

1

You can do this with the following selector:

var els = document.querySelectorAll('.message-in span.copyable-text'); // seleciono todas
var conta = els.length; // conto a quantidade
var texto = els[conta-1].textContent; // pego o texto da última

The .message-in class refers to incoming messages. In this case, just count how many there are and get the text of the last one by decreasing the quantity by 1 ( index of the collection starts with 0, so the index of the last element is always the quantity minus 1). >

Test in the WhatsApp Web

If you want to test the WA Web page, open the console (F12) in a conversation and execute the line below:

els=document.querySelectorAll('.message-in span.copyable-text');conta=els.length;texto=els[conta-1].textContent;
    
20.12.2017 / 18:09