Sunday, November 17, 2024
Google search engine
HomeLanguagesShare WhatsApp Web without Scanning QR code using Python

Share WhatsApp Web without Scanning QR code using Python

Prerequisite: Selenium, Browser Automation Using Selenium

In this article, we are going to see how to share your Web-WhatsApp with anyone over the Internet without Scanning a QR code.

Web-Whatsapp store sessions

Web Whatsapp stores sessions in IndexedDB with the name wawc and syncs those key-value pairs to local storage. IndexedDB stores the data inside the user’s browser and allows to create web application that can query from this indexedDB with or without a network connection. 

How to get a session:

We can figure it out by trying the following. We will take help of chrome dev tool.

Steps:

  1. Clear cookies and refresh the page: It will remain login.
  2. Clear localStorage and refresh the page: It will restore the local Storage and remain logged in.
  3. Clear IndexedDB and refresh the page: It will restore the IndexedDB and remain logged in.
  4. Now clear both localStorage and IndexedDB: It will log out.

Steps demonstration:

Extract sessions from IndexedDB:

We can extract sessions from IndexedDB by using the following javascript. 

Javascript




function getResultFromRequest(request) {
    return new Promise((resolve, reject) => {
        request.onsuccess = function (event) {
            resolve(request.result);
        };
    });
}
  
async function getDB() {
    var request = window.indexedDB.open("wawc");
    return await getResultFromRequest(request);
}
  
async function readAllKeyValuePairs() {
    var db = await getDB();
    var objectStore = db.transaction("user").objectStore("user");
    var request = objectStore.getAll();
       return await getResultFromRequest(request);
}
  
session = await readAllKeyValuePairs();
console.log(session);


We can try to execute the above code in the browser’s console or tab where we had opened Web-Whatsapp and we will see the output as follows containing session key-value pairs.
 

Now we get those key-value pairs as text by running the following line of code.

Javascript




JSON.stringify(session);


Now let’s copy that text to a file to save a session and clear both localStorage and IndexedDB to log out. Now we can run the following code to inject a session by assigning the value of the session string we just copied to a file to variable SESSION_STRING. Then refresh the page and we will log in again without scanning the QR code. 

Javascript




function getResultFromRequest(request) {
    return new Promise((resolve, reject) => {
        request.onsuccess = function(event) {
            resolve(request.result);
        };
    })
}
  
async function getDB() {
    var request = window.indexedDB.open("wawc");
    return await getResultFromRequest(request);
}
  
async function injectSession(SESSION_STRING) {
    var session = JSON.parse(SESSION_STRING);
    var db = await getDB();
    var objectStore = db.transaction("user", "readwrite").objectStore("user");
    for(var keyValue of session) {
        var request = objectStore.put(keyValue);
        await getResultFromRequest(request);
    }
}
  
var SESSION_STRING = "";
await injectSession(SESSION_STRING);


 

Automating the process of generating a session file and injecting a session:

We can automate the process of generating a session file that contains our session key-value pairs and also reading session key-value pairs from that generated session file to inject a session into the browser to open web-WhatsApp without scanning QR code

We can automate as follows:

Take the session file path as a command-line argument.

Generating session file:

  • Open Chrome browser. 
  • Open Web Whatsapp.
  • Ask the user to scan the QR code.
  • Wait for the QR code to be scanned.
  • Execute javascript in the browser and extract the session.
  • Save the file with a session text file with the custom file extension “.wa”.
  • Close the browser.

Opening session file:

  • Verify that the session file exists.
  • Read the given file into the “session” variable. 
  • Open Chrome browser.
  • Open Web Whatsapp.
  • Wait for Web Whatsapp to be loaded properly.
  • Execute javascript in browser to inject session by using variable “session”.
  • Refresh the page.
  • Ask for the user to press enter key to close the browser.

Below is the implementation:

Note: Please download chormedrive before running the code.

By using selenium’s WebDriverWait, we can wait for some elements to be present on the browser as following:

Python3




def _wait_for_presence_of_an_element(browser, selector):
    element = None
     
    try:
        element = WebDriverWait(browser, DEFAULT_WAIT).until(
            EC.presence_of_element_located(selector)
        )
    except:
        pass
    finally:
        return element


Generating session file:

Python3




def sessionGenerator(sessionFilePath):
 
    # 1.1 Open Chrome browser
    browser = webdriver.Chrome()
 
    # 1.2 Open Web Whatsapp
    browser.get("https://web.whatsapp.com/")
 
    # 1.3 Ask user to scan QR code
    print("Waiting for QR code scan...")
 
    # 1.4 Wait for QR code to be scanned
    _wait_for_presence_of_an_element(
      browser, MAIN_SEARCH_BAR__SEARCH_ICON)
 
    # 1.5 Execute javascript in browser and
    # extract the session text
    session = browser.execute_script(EXTRACT_SESSION)
 
    # 1.6 Save file with session text file with
    # custom file extension ".wa"
    with open(sessionFilePath, "w", encoding="utf-8") as sessionFile:
        sessionFile.write(str(session))
 
    print("Your session file is saved to: " + sessionFilePath)
 
    # 1.7 Close the browser
    browser.close()


Use the above methods for Generating session file:

Python3




from session import *
import sys
 
# Take session file path as command line
# argument and passed to following method
sessionFilePath = sys.argv[1]
 
sessionGenerator(sessionFilePath)


Opening session file:

Python3




def sessionOpener(sessionFilePath):
 
    # 2.1 Verify that session file is exist
    if sessionFilePath == "":
        raise IOError('"' + sessionFilePath + '" is not exist.')
 
    # 2.2 Read the given file into "session" variable
    with open(sessionFilePath, "r", encoding="utf-8") as sessionFile:
        session = sessionFile.read()
 
    # 2.3 Open Chrome browser
    browser = webdriver.Chrome()
 
    # 2.4 Open Web Whatsapp
    browser.get("https://web.whatsapp.com/")
 
    # 2.5 Wait for Web Whatsapp to be loaded properly
    _wait_for_presence_of_an_element(browser, QR_CODE)
 
    # 2.6 Execute javascript in browser to inject
    # session by using variable "session"
    print("Injecting session...")
    browser.execute_script(INJECT_SESSION, session)
 
    # 2.7 Refresh the page
    browser.refresh()
 
    # 2.8 Ask for user to enter any key to close browser
    input("Press enter to close browser.")


Use the above methods for Opening session file:

Python3




from session import *
import sys
 
# Take session file path as command line
# argument and passed to following method
sessionFilePath = sys.argv[1]
 
sessionOpener(sessionFilePath)


We can generate a session file by using the following command:

For Generating session file:

python session_generator.py session.wa

After generating the session file then share it with someone and put that session file in the same folder where session_opener.py is located and run the following command to open the Web Whatsapp without scanning the QR code

For Opening session file:

python session_opener.py session.wa

OR open PowerShell normally without going to the folder and give absolute paths as following

For Generating session file:

python E:\share-web-whatsapp\session_generator.py E:\share-web-whatsapp\session.wa

For Opening session file:

python E:\share-web-whatsapp\session_opener.py E:\share-web-whatsapp\session.wa

RELATED ARTICLES

Most Popular

Recent Comments