in whatsapp web if you inspect you can see that contact name resides in div with class '.chat'.
you can add listener to contacts in left side in whatsapp web by executing the following script in your whatsapp_login function. Following is the whatsapp_login function:
def whatsapp-login(request):
global driver
profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
driver = webdriver.Firefox(firefox_profile=profile)
driver.get('https://web.whatsapp.com/')
script_path = os.path.dirname(os.path.abspath(__file__))
script = open(os.path.join(script_path, "add_eventlistener.js"), "r").read()
driver.execute_script(script)
following is the add_listener script which uses MutationObserver:
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(mutation.attributeName === 'class') {
var attributeValue = $(mutation.target).prop(mutation.attributeName);
console.log("attributeValue: "+attributeValue);
if(attributeValue.indexOf('hover') > -1) {
var user = $(mutation.target).find('.chat-title').find('span').attr('title');
console.log('Class attribute changed to:', attributeValue);
$.ajax({
url: 'url of change active chat function',
type: "POST",
data: {"user": user},
headers: {"Access-Control-Allow-Origin": "*"},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
}
}
});
});
Array.prototype.forEach.call(document.querySelectorAll('.chat'), function(element, index) {
console.log(element);
observer.observe(element, {
attributes: true
});
});
inside your change active chat function you can do the following to change active chat. Here you will get the user from ajax call and iterate through the contact list:
def change_active_chat(user):
recentList = driver.find_elements_by_xpath("//span[@class='emojitext ellipsify']")
for head in recentList:
if head.text == user:
head.click()
head.click() will change the active chat.