Skip to content

Instantly share code, notes, and snippets.

@sayhicoelho
Last active September 5, 2024 00:42
Show Gist options
  • Save sayhicoelho/04b7fa3289e3265c03f58849c914081c to your computer and use it in GitHub Desktop.
Save sayhicoelho/04b7fa3289e3265c03f58849c914081c to your computer and use it in GitHub Desktop.
Send messages to WhatsApp (web version only) programmatically.
function sendMessage(message){
const mainEl = document.querySelector('#main')
const textareaEl = mainEl.querySelector('div[contenteditable="true"]')
if(!textareaEl) {
throw new Error('There is no opened conversation')
}
textareaEl.focus()
document.execCommand('insertText', false, message)
textareaEl.dispatchEvent(new Event('change', { bubbles: true }))
setTimeout(() => {
(mainEl.querySelector('[data-testid="send"]') || mainEl.querySelector('[data-icon="send"]')).click()
}, 100)
}
@egyjs
Copy link

egyjs commented Dec 21, 2019

function sendMessage (message) {
  window.InputEvent = window.Event || window.InputEvent;

  var event = new InputEvent('input', {
    bubbles: true
  });

  var textbox = document.querySelector('div._3u328');

  textbox.textContent = message;
  textbox.dispatchEvent(event);

  document.querySelector("button._3M-N-").click();
}

@sayhicoelho
Copy link
Author

Thank you @el3zahaby! It's now fixed.

@gharia
Copy link

gharia commented Jul 1, 2021

Do you guys know internally (from whatsapp js) which function it calls?

@semihkeskindev
Copy link

there are unique values in the function ("div._3u328" and "button._3M-N-"). Whoever wanna use the function, has to update that. I did and I also upgraded that as an independent function from sessions

function sendMessage (message) {
  window.InputEvent = window.Event || window.InputEvent;

  var event = new InputEvent('input', {
    bubbles: true
  });

  var textbox = document.querySelector('[role="textbox"][data-tab="10"]');

  textbox.textContent = message;
  textbox.dispatchEvent(event);

  $('[data-testid="send"]').closest("button").click();
}

@sayhicoelho
Copy link
Author

Thanks @semihkeskindev ! I just fixed it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment