How to Capture Span Content by Javascript

Asked

Viewed 1,457 times

4

On Whatsapp Web, each 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 box "Send a message":

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); 

inserir a descrição da imagem aqui

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

I tried it this way, 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 on the same Console, when I click F12 on Whatsapp Web.

  • It would be better to post in the question the HTML code of span. There are many ways to capture this, but you need to know what is in this span.

  • Ready. As the image, I need to capture the content of that line in blue (always the last message of Whatsapp in that conversation).

1 answer

0


You can do it 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 class .message-in refers to incoming messages. In this case, just count how many there are and pick up the text of the last one, decreasing the amount by 1 (the index of the collection begins with 0, therefore the index of the last element is always the quantity minus 1).

Testing on Whatsapp Web

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

els=document.querySelectorAll('.message-in span.copyable-text');conta=els.length;texto=els[conta-1].textContent;
  • The following message appears: "VM64:3 Uncaught Typeerror: Cannot read Property 'textContent' of Undefined at <Anonymous>:3:26"

  • The same error happened... VM66:1 Uncaught Typeerror: Cannot read Property 'textContent' of Undefined at <Anonymous>:1:101

  • @lucaswmolin Here it worked. It has talk in the window?

  • Oops, I gave F5 and tried again. It worked, yeah. Thanks.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.