Jump to content
Suebersson

Envio de imagem no WhatsApp Web via JS

Recommended Posts

Oi pessoal tudo bem, eu gostaria que alguém me ajudasse numa questão sobre a execução do código baixo.

O código funciona bem sem nenhum problema quando é inserido e executado dentro do console, mais quando tento executa-lo de dentro de um extensão do Chrome gerar erros.

O erro é gerado na linha: const id = _.uniqueId("fakeModule_");

Erro: Uncaught (in promise) ReferenceError: _ is not defined

 

O objetivo desse código enviar imagens no WhatsApp Web, mas só funciona no console.

 

Estou aberto também a outras formas de envios de imagem se alguém conhecer usando Js ou se alguém saber como fazer um upload de uma imagem em um input accept do tipo file via código.

 

Referência do código: https://gist.github.com/phpRajat/a6422922efae32914f4dbd1082f3f412

Código:

 

//$$$$$$$$$$$     Parâmetros     $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

var Destinatario = '5521965454193@c.us'; // número do destinatário (O chat do destinatário tem que esta ativo)

var Image_base64 = 'data:image/png;base64,iVBORw0KGgoAAA...';

var Legenda = 'Texto legenda';

//$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

 

var Store = {};

var createFromData_id = 0;

var prepareRawMedia_id = 0;

var store_id = 0;

var send_media;

var file = "";

var createFromDataClass;

var prepareRawMediaClass;

 

 

 

Set_modulos();

setTimeout(function(){init();},1000);

 

 

function Set_modulos(){

 

                console.clear();

 

                var modules = getAllModules()._value;

 

                function getAllModules() {

 

                               return new Promise((resolve) => {

                                               const id = _.uniqueId("fakeModule_");

 

                                               window["webpackJsonp"](

                                                               [],

                                                               {

                                                                              [id]: function(module, exports, __webpack_require__) {

                                                                                              resolve(__webpack_require__.c);

                                                                              }

                                                               },

                                                               [id]

                                               );

                               });

                }

 

                for (var key in modules) {

 

                               if (modules[key].exports) {

                                               if (modules[key].exports.createFromData) {

                                                               createFromData_id = modules[key].id.replace(/"/g, '"');

                                               }

                                               if (modules[key].exports.prepRawMedia) {

                                                               prepareRawMedia_id = modules[key].id.replace(/"/g, '"');

                                               }

                                               if (modules[key].exports.default) {

                                                               if (modules[key].exports.default.Wap) {

                                                                              store_id = modules[key].id.replace(/"/g, '"');

                                                               }

                                               }

                               }

                }             

}

 

function _requireById(id) {

                return webpackJsonp([], null, [id]);

}

 

function fixBinary (bin) {

 

                var length = bin.length;

                var buf = new ArrayBuffer(length);

                var arr = new Uint8Array(buf);

                for (var i = 0; i < length; i++) {

                  arr = bin.charCodeAt(i);

                }

                return buf;

}

 

window.send_media = function(jid, link, caption, msg_id, content_type) {

 

                file = "";

                createFromDataClass = _requireById(createFromData_id)["default"];

                prepareRawMediaClass = _requireById(prepareRawMedia_id).prepRawMedia;

               

                window.Store.Chat.find(jid).then((chat) => {

                               chat.markComposing();

                              

                               var img_b64 = link;

                               var base64 = img_b64.split(',')[1];

                               var type = img_b64.split(',')[0];

                              

                               type = type.split(';')[0];

                               type = type.split(':')[1];

                              

                               var binary = fixBinary(atob(base64));

                               var blob = new Blob([binary], {type: type});

                               var random_name = Math.random().toString(36).substr(2, 5);

                              

                               file = new File([blob], random_name, {

                                               type: type,

                                               lastModified: Date.now()

                               });

                              

                               var temp = createFromDataClass.createFromData(file, file.type);

                               var rawMedia = prepareRawMediaClass(temp, {});

                              

                               var target = _.filter(window.Store.Msg.models, (msg) => {

                                               return msg.id.id === msg_id;

                               })[0];

                              

                               var textPortion = {

                                               caption: caption,

                                               mentionedJidList: [],

                                               quotedMsg: target

                               };

                              

                               rawMedia.sendToChat(chat, textPortion);

                              

                });

               

}

 

function init() {

                window.Store = _requireById(store_id).default;

                //console.log("Store is ready");

                //console.log(window.Store);

                window.send_media(Destinatario, Image_base64, Legenda, null, null);

}

git hub.png

Share this post


Link to post
Share on other sites

Hey Suebersson, did you find out how to work around this issue?

I am having the same problem here, if you have any alternative and could share it I would appreciate.

Regards,

Alex

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By tiagoban
      Estou testando o envio de mensagem para whatsapp via Python, queria testar enviar imagem tambem, porem nao sei qual o codigo usar, alguem sabe como proceder?
      Segue o codigo utilizado até o momento.
       
      from time import sleep from selenium.webdriver.common.by import By from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException from selenium.webdriver.support.ui import WebDriverWait import socket client = Client() message_text='Oi, esta é uma mensagem automatica criada.' # message no_of_message=1 # no. of time moblie_no_list=[554899999999] # list of phone number def element_presence(by,xpath,time): element_present = EC.presence_of_element_located((By.XPATH, xpath)) WebDriverWait(driver, time).until(element_present) def is_connected(): try: # connect to the host -- tells us if the host is actually # reachable socket.create_connection(("www.google.com", 80)) return True except : is_connected() driver = webdriver.Chrome(executable_path="chromedriver.exe") driver.get("http://web.whatsapp.com") sleep(10) #wait time to scan the code in second def send_whatsapp_msg(phone_no,text): driver.get("https://web.whatsapp.com/send?phone={}&source=&data=#".format(phone_no)) try: driver.switch_to_alert().accept() except Exception as e: pass try: element_presence(By.XPATH,'//*[@id="main"]/footer/div[1]/div[2]/div/div[2]',30) txt_box=driver.find_element(By.XPATH , '//*[@id="main"]/footer/div[1]/div[2]/div/div[2]') global no_of_message for x in range(no_of_message): txt_box.send_keys(text) txt_box.send_keys("\n") except Exception as e: print("invailid phone no :"+str(phone_no)) for moblie_no in moblie_no_list: try: send_whatsapp_msg(moblie_no,message_text) except Exception as e: sleep(10) is_connected()
    • By Motta
      WhatsApp urges users to update app after discovering spyware vulnerability
    • By Motta
      Facebook e Instagram e seus sites e aplicativos saem do ar no mundo todo
    • By Motta
      “Não temos consciência da quantidade de dados que damos ao celular mesmo sem tocá-lo”
       
       
      "Advogada Paloma Llaneza explica que apagar aplicativos como Facebook e WhatsApp é a única forma de evitar que eles colham nossos dados"
       
      O problema é que no trabalho se exige de certa forma o wsp, face estou quase largando.
    • By Trapé
      Bom Dia, preciso enviar do meu app uma mensagem para o whatsapp, mas para contatos não existentes no dispositivo.
      O usuário insere o número do celular no EditText e envia a mensagem para esse número.
      O problema é que como não é um número existente no meu dispositivo ele abre a lista de contatos do whats para selecionar um contato.
      Alguém sabe como faço para enviar para contatos não cadastrados?

      Segue meu código abaixo:
       
      Intent shareIntent =new Intent("android.intent.action.MAIN"); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, mensagem); shareIntent.putExtra(Intent.EXTRA_STREAM, arquivo); shareIntent.setType("image/*"); shareIntent.setPackage("com.whatsapp"); shareIntent.putExtra("jid", "55" + (telefone_envio) + "@s.whatsapp.net"); shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); try { startActivity(shareIntent); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(getBaseContext(), "WhatApp Não Instalado.", Toast.LENGTH_SHORT).show(); } Usando a url consigo enviar para contatos não cadastros, mas não consigo anexar arquivo:
      Intent shareIntent = new Intent(Intent.ACTION_VIEW); shareIntent.setData(Uri.parse("https://api.whatsapp.com/send?phone="+telefone_envio+"&text="+arquivo)); startActivity(shareIntent); Agradeço desde Já
      Carla
×

Important Information

Ao usar o fórum, você concorda com nossos Terms of Use.