Automating Repetitive Clicks with a Small Browser Script: A Worked Example
Published:
Many web applications make you repeat the same small action again and again. A typical case is a document inbox: every item has to be opened and then closed with a button before it leaves the list. One item takes five seconds. Three hundred items take an afternoon.
When a task is exactly the same every time, it is a good candidate for a small script. This post walks through one such script as a worked example. The goal is not the script itself but the way of thinking behind it, so that you can write your own for a different page.
The method in five steps
Every browser automation, from a ten-line console script to a large testing framework, follows the same pattern.
- Observe the manual task. Do it by hand a few times and write the steps down: click the first item, wait for it to open, press the close button, confirm, wait, repeat.
- Inspect the page. Open the developer tools (F12), choose the element picker and click the things you click by hand. Note how each one can be found: its tag, its text, its
idor its class name. - Act on the elements. In JavaScript,
document.querySelectorfinds an element andelement.click()presses it, exactly as a mouse would. - Wait. A page needs time to react to a click. The script must pause (
setTimeout) before it looks for the next element, or it will look too early and find nothing. - Repeat and report. Wrap the steps in a function that calls itself again, and write each step to the console so you can see what is happening.
The example
In the example page, each item in the list has a heading that starts with the word for “subject”. Clicking it opens a preview with a close button. The close button sometimes asks for a confirmation, and after closing, a small “operation successful” pop-up appears. When an item is closed, it leaves the list, so the next item moves to the top.
The script below follows the five steps above. The labels it searches for are written in the language of that page (Konu:, Evrak Kapat), so they are the first thing you would change for another application.
(function() {
var DELAY = 1000; // pause between two items (ms)
var PREVIEW_WAIT = 1000; // time given to the preview to load (ms)
var currentIndex = 0;
// Step 2 in code: every heading that starts with "Konu:" (subject) is one item in the list
function getMessages() {
return Array.from(document.querySelectorAll('h3')).filter(function(h) {
return h.innerText.trim().startsWith('Konu:');
});
}
// Remove the "operation successful" pop-up so it does not cover the list
function dismissNotification() {
var notify = document.querySelector('.lobibox-notify-msg');
if (notify) {
// Find the element that wraps the pop-up and remove it
var parent = notify.closest('.lobibox-notify, .lobibox, [class*="lobibox"]');
if (parent) parent.remove();
else notify.closest('div[style*="display"]') && notify.parentElement.remove();
console.log('🔔 Notification closed.');
}
}
// Find the close button: a modalButton whose text is "Evrak Kapat" (close document)
function clickEvrakKapat(callback) {
var buttons = Array.from(document.querySelectorAll('button.modalButton'));
var kapatBtn = buttons.find(function(btn) {
return btn.innerText.trim() === 'Evrak Kapat';
});
if (kapatBtn) {
console.log('📂 Clicking the close button: ' + kapatBtn.id);
kapatBtn.click();
setTimeout(function() {
// If a confirmation button appears, click it too
var onayBtn = document.getElementById('mainPreviewForm:onaysizKapatId');
if (onayBtn) {
console.log('✅ Clicking the confirmation button.');
onayBtn.click();
setTimeout(function() {
dismissNotification();
setTimeout(callback, 800);
}, 800);
} else {
dismissNotification();
setTimeout(callback, 500);
}
}, 800);
} else {
console.log('⚠️ Close button not found, moving on...');
callback();
}
}
// Go to the next page of the list (the link labelled "N")
function goToNextPage() {
var nextBtn = Array.from(document.querySelectorAll('a')).find(function(a) {
return a.innerText.trim() === 'N';
});
if (nextBtn) {
console.log('📄 Going to the next page...');
nextBtn.click();
setTimeout(function() {
currentIndex = 0;
processNext();
}, 3000);
} else {
console.log('🏁 All pages are done!');
}
}
// Step 5: open the first item, close it, wait, repeat
function processNext() {
// Close a leftover pop-up first, if there is one
dismissNotification();
var messages = getMessages();
// The list is empty (or still loading): check again in 3 seconds
if (messages.length === 0) {
setTimeout(processNext, 3000);
return;
}
if (currentIndex === 0) {
console.log('📬 Found ' + messages.length + ' items on this page.');
}
if (currentIndex >= messages.length) {
console.log('✅ Page finished! Going to the next page...');
goToNextPage();
return;
}
console.log('📧 ' + (currentIndex + 1) + '/' + messages.length + ': ' +
messages[currentIndex].innerText.trim().substring(0, 55));
messages[currentIndex].click();
// The index is not increased on purpose: a closed item leaves the list,
// so the next item moves to the top
// currentIndex++;
setTimeout(function() {
dismissNotification(); // close a pop-up shown when the preview opens
clickEvrakKapat(function() {
setTimeout(processNext, DELAY);
});
}, PREVIEW_WAIT);
}
processNext();
})();
Reading the code
- The outer
(function() { ... })();keeps every variable inside the script, so nothing leaks into the page or clashes with its own code. getMessagesis step 2 turned into code. It does not rely on anidor a class for the items, because those are often generated and change between visits. It relies on visible text instead, which is more stable.clickEvrakKapatshows how to handle a step that happens only sometimes. After clicking the close button it waits, then checks whether a confirmation button exists before clicking it. Always check that an element is there; never assume it.- Callbacks and
setTimeoutare how the script waits. Each function finishes by scheduling the next one. This is the same idea asawait, written in an older style that works everywhere. currentIndexstays 0. Because a closed item disappears, the first item in the list is always the next one to process. Watching what the page does after each action, and not only what you expect it to do, is what makes this choice possible.console.loglines are not decoration. Without them you could not tell a slow page from a stuck script.
How to run it
- Open the page in a desktop browser and go to the list you want to process.
- Press F12 and switch to the Console tab.
- Copy the script with the button above, paste it into the console and press Enter. Chrome may first ask you to type
allow pasting; this is a safety check for exactly this kind of code. - Watch the console. Each item is reported as
📧 1/20: ...while it is processed. - To stop, refresh the page (F5). The script lives only in that tab and disappears with it.
Start small. Let it process two or three items, refresh the page, and check that the result is what you expected. Only then let it run on the rest.
Why this approach is useful
- It saves real time. A list that takes an hour of clicking is done in minutes.
- Nothing to install. No extension and no program. It runs in your own logged-in session and does only what you could do by hand.
- It is short and readable. About a hundred lines, so you can read every line before you run it.
- It is easy to adapt. The delays are two numbers at the top, and the labels are plain strings.
- It teaches the core of automation. Find, act, wait and repeat is how every browser automation tool works, here without any library.
Limits and risks
A script does not read. It clicks what you told it to click. If an item in the list needed your attention, the script closes it anyway, and the record shows that you closed it. Run it only on lists whose items you know you do not need to read.
- There is no stop button. The only way to stop it is to refresh the page.
- It does not finish on its own. When the list is empty it keeps checking every three seconds. Because the index is never increased, the “next page” step is reached only in unusual cases.
- It hides pop-ups. It removes the notification box after each action. If an error appears in the same kind of box, it disappears too. Keep an eye on the console.
- It depends on the page layout. It finds things by their text and class names. When the application is updated, the script may stop working or, worse, click the wrong thing. Test it again after every update.
- Rules may apply. In some workplaces an action done in bulk is not acceptable even if it is technically possible. Check before you automate anything that is recorded in your name.
- Never paste code you do not understand. The console runs whatever you give it with your full access. The same trick that saves clicks can be used to steal a session, which is why browsers warn you.
Exercises
If you want to practise, improve the script step by step:
- Add a stop switch: check a global variable such as
window.stopAutoat the start ofprocessNextand return when it istrue. - Stop cleanly when the list is empty instead of checking forever, and only then call
goToNextPage. - Add a limit, for example “process at most 20 items”, so a first run can never go too far.
- Collect the subjects of the processed items in an array and print them as a table with
console.tableat the end. - Rewrite the waiting with
async/awaitand a smallsleepfunction, and compare how readable the two versions are.
Closing
Small scripts like this are one of the most practical things programming gives you. You notice a boring, repeated task, you read how the page is built, and a short while later the computer does the boring part. The second habit matters just as much: understand what the code does before you let it act in your name, and keep the decisions that need a person with a person.
