I use that social network for several reasons, one of which is the ability to exchange text messages (some of my friends don’t use messengers on principle, they have to adjust). I used to constantly update the page to find out about new messages, not so long ago, Vkontakte had an instant messaging service, but I didn’t immediately like it and decided to automate the process.
In this topic, I will talk about my implementation of the My Messages indicator update mechanism without reloading the page. Want to know more? Welcome under the cut!
Theory
The script is implemented using
jQuery and connects to the site using
Greasemonkey .
To begin with, I will tell the principle of action on the fingers:
- At a certain interval (for myself, I set 20 seconds) load the page with messages using AJAX
- Find the number of unread messages
- If the result of point 2 is zero, then change the text of the link to "My Messages"
- If the re-result is non-zero, then change the text to “My Messages ( N )”
Practice
In order to embed the script on the page, I, as a Firefox user, used the Greasemonkey plugin. As far as I know, there is a version of Greasemonkey for Google Chrome, Opera itself is able to execute custom scripts, which is called “out of the box”. I think that adapting my script for Opera and Chromium is a short and simple affair.
')
In order for Greasemonkey to accept our script, it must meet two criteria:
- The name of the script should be of the form script_name .user.js
- Before the script body, you need to write a heading, if you still do not know how it should be formed, first read this topic.
Headline for our script:
// ==UserScript== // @name DynamicVK // @namespace vk.com/stryaponoff // @description Makes VK dynamic // @author stryaponoff // @include *vk.com/* // @include *vkontakte.ru/* // @require http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js // ==/UserScript==
Then we specify the time interval for checking messages (in milliseconds):
var RefreshInterval = 20000;
For the first time since I became acquainted with JavaScript, I needed to find the number of occurrences of a substring in a string. What was my surprise when I did not find the corresponding function in JS. As a result, the following code was born:
function SubStrCount(source, string) { var pos = 0; var count = 0; var offset = -1; var len = 0; while ((offset = source.indexOf(string, offset + 1)) != -1) { if (len > 0 && (offset + string.length) > len) { return false; } else { count++; } } return count; }
The principle of operation is as follows - we simply find the character that starts the first occurrence of the substring
string in the string
source . Increment counter Then we repeat the same thing, only for the beginning of the search we take not the first character of the
source string, but the next immediately after the occurrence found. And so on until we go through the whole line.
Further the most interesting begins - we write the main function of our script:
function CheckMail() { // var mail_href = $('#l_msg a').attr('href'); // AJAX $.get(mail_href, function(data) { // var NewMessagesCount = SubStrCount(data, 'read=\\"0\\"'); // , if (NewMessagesCount != 0) { // " (N)" $('#l_msg a').html(' (<b>' + NewMessagesCount + '</b>)'); // ... } else { // " " $('#l_msg a').html(' '); } }); }
The code that comes in response to an AJAX request contains escaped quotes (in particular, the HTML attribute of interest
read="0"
turns into
read=\"0\"
). Therefore, to find this text, we need to look for it along with slashes, for which we need, in fact, to “screen screening” :) We
read=\\"0\\"
.
And finally, we need to call our function at the right moment. After the page loads, we perform it once and set the call repetition interval (let me remind you, in our case - 20 seconds):
$(document).ready(function() { CheckMail(); setInterval(function() { CheckMail() }, RefreshInterval); });
Too often, refreshing the page should not be done either, even if you are not concerned about the moral side of the issue (if updating too often, you create additional load on the server — a kind of mini-
DoS attack ). If you exceed a certain limit of too frequent requests, requests from you will simply be temporarily blocked.
Full script code
// ==UserScript== // @name DynamicVK // @namespace vk.com/stryaponoff // @description Makes VK dynamic // @author stryaponoff // @include *vk.com/* // @include *vkontakte.ru/* // @require http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js // ==/UserScript== var RefreshInterval = 20000; function SubStrCount(source, string) { var pos = 0; var count = 0; var offset = 0; var len = 0; while ((offset = source.indexOf(string, offset + 1)) != -1) { if (len > 0 && (offset + string.length) > len) { return false; } else { count++; } } return count; } function CheckMail() { var mail_href = $('#l_msg a').attr('href'); $.get(mail_href, function(data) { var NewMessagesCount = SubStrCount(data, 'read=\\"0\\"'); if (NewMessagesCount != 0) { $('#l_msg a').html(' (<b>' + NewMessagesCount + '</b>)'); } else { $('#l_msg a').html(' '); } }); } $(document).ready(function() { CheckMail(); setInterval(function() { CheckMail() }, RefreshInterval); });
Option script without using jQuery
(preferred option, because it fixed a lot of errors)
// ==UserScript== // @name DynamicVK // @namespace vk.com/stryaponoff // @description Makes VK dynamic // @author stryaponoff // @include *vk.com/* // @include *vkontakte.ru/* // ==/UserScript== var RefreshInterval = 20000; function CheckMail() { // AJAX- var XmlHttp = new XMLHttpRequest(); // var MsgCount = 0; // XmlHttp.onreadystatechange = function() { // ... if (XmlHttp.readyState == 4) { // , ... if (XmlHttp.status == 200) { // var RegEx = /messages{count=(.*?)}/; MsgCount = RegEx.exec(XmlHttp.responseText)[1]; // // // var sidebar; if (document.getElementById('side_bar') == null) { sidebar = document.getElementById('sideBar'); } else { sidebar = document.getElementById('side_bar'); } for (i = 0; i < sidebar.getElementsByTagName('a').length; i++) { if (sidebar.getElementsByTagName('a')[i].href.indexOf('mail.php') != -1) { // - , ... if (MsgCount != 0) { // " (MsgCount)" sidebar.getElementsByTagName('a')[i].innerHTML = ' <span>(<b>' + MsgCount + '</b>)</span>'; } else { // " " sidebar.getElementsByTagName('a')[i].innerHTML = ' '; } return; } } } } } // XmlHttp.open('GET', '/feed.php', true); XmlHttp.send(''); } CheckMail(); setInterval(function() { CheckMail() }, RefreshInterval);
Using
In order to use the script in the browser, simply drag the script file (
dynamicvk.user.js ) into the browser window, the following window should appear:

All that is required of you is to click
“Install” . You can start to use :)
Conclusion
I hope this topic will be useful to someone other than me. In principle, the wall, invitations to friends and other pages can be updated in the same way, I just described the principle of operation. I will be glad to hear constructive criticism and comments about this post, so as not to repeat mistakes in the following publications. I also thank everyone who raised my karma and made the publication of this post possible.
Thank!If someone has any questions or problems - write, try to figure it out. Thanks for attention!