Interacting with a Web Page using the Browser Console: A Simple Example

Interacting with a Web Page using the Browser Console: A Simple Example

Daily short news for you
  • For a long time, I have been thinking about how to increase brand presence, as well as users for the blog. After much contemplation, it seems the only way is to share on social media or hope they seek it out, until...

    Wearing this shirt means no more worries about traffic jams, the more crowded it gets, the more fun it is because hundreds of eyes are watching 🤓

    (It really works, you know 🤭)

    » Read more
  • A cycle of developing many projects is quite interesting. Summarized in 3 steps: See something complex -> Simplify it -> Add features until it becomes complex again... -> Back to a new loop.

    Why is that? Let me give you 2 examples to illustrate.

    Markdown was created with the aim of producing a plain text format that is "easy to write, easy to read, and easy to convert into something like HTML." At that time, no one had the patience to sit and write while also adding formatting for how the text displayed on the web. Yet now, people are "stuffing" or creating variations based on markdown to add so many new formats that… they can’t even remember all the syntax.

    React is also an example. Since the time of PHP, there has been a desire to create something that clearly separates the user interface from the core logic processing of applications into two distinct parts for better readability and writing. The result is that UI/UX libraries have developed very robustly, providing excellent user interaction, while the application logic resides on a separate server. The duo of Front-end and Back-end emerged from this, with the indispensable REST API waiter. Yet now, React doesn’t look much different from PHP, leading to Vue, Svelte... all converging back to a single point.

    However, the loop is not bad; on the contrary, this loop is more about evolution than "regression." Sometimes, it creates something good from something old, and people rely on that goodness to continue the loop. In other words, it’s about distilling the essence little by little 😁

    » Read more
  • Alongside the official projects, I occasionally see "side" projects aimed at optimizing or improving the language in some aspects. For example, nature-lang/nature is a project focused on enhancing Go, introducing some changes to make using Go more user-friendly.

    Looking back, it resembles JavaScript quite a bit 😆

    » Read more

The Issue

You may already know that before React, Vue, etc., jQuery dominated the web platform for a long time. Almost every website had to use jQuery because it was a library with many powerful DOM interaction functions. Many libraries were built based on jQuery, and some even required jQuery before use. However, due to its heaviness and bulkiness, along with the excessive abuse of jQuery, it has become increasingly disliked. Coupled with the emergence of many modern web development tools, it is now on the "brink of death."

When accessing a website, every action you take, such as mouse movements, clicks, key presses, etc., reflects an interaction with the DOM. The DOM can be simply understood as the HTML components displayed on the webpage. Additionally, there are a few other things that can interact with the DOM, such as JavaScript. This means that JavaScript can be used to create interactions with the DOM instead of the user. From there, we can automate a series of actions without the need for human interaction.

Most modern browsers provide a feature called Console for writing JavaScript code directly on the website being accessed. That is also the content of today's article; I will take a specific example of how to use JavaScript to perform an action on a website. I hope that through this article, readers can create more practical applications in reality and apply them in their daily work.

DOM and JavaScript

Document Object Model (DOM) is a programming interface for web pages. It represents the webpage so that programs can change the structure, style, and content of the document. The DOM represents the web page (document) as nodes and objects. Thus, it allows some programming languages to interact with the page.

JavaScript can interact with the DOM. Imagine the DOM as a Web API that the browser provides for JavaScript to have full access and editing capabilities. Almost every great experience on the web today features JavaScript. Many frameworks and libraries have emerged based on JavaScript that enhance the ability to interact with the DOM, providing convenience and friendliness to developers.

The browser allows us to run JavaScript code directly on the webpage through Dev Tools. For example, in Chrome, after enabling Dev Tools and entering the Console window, you can write JavaScript code here and run it.

Browser Console

Taking advantage of this, many cyber attackers previously tried to trick users into pasting a snippet of code into Dev Tools to steal user data. For an average user who cannot fully understand the dangers of executing JavaScript code right on the website they are using, this can be risky. However, in this article, I will not delve into that topic; the goal is to help you visualize how to use JavaScript to interact with the DOM.

The theory may be a bit dry, so let's take a specific example of "Continuously Reacting to Messages on the Web Telegram."

Continuously Reacting to Messages on the Web Telegram

In addition to its cross-platform application, Telegram also allows access through the web. One thing I find interesting is the ability to react to messages with emoticons. I like it because often I don't need to reply but just want to drop an icon, or sometimes to let the sender know that I have read their message and how I feel after reading it.

I have a habit of frequently reacting to messages. Partly to let them know that I have read it, partly for "playfulness." My Telegram has a group of friends who often chat about various topics, and to alleviate boredom, I once wrote a piece of code to automatically react to every message that our group sends.

To write the code, we first need to spend some time researching how the reaction feature works.

First, whenever you hover over the timestamp, the icons appear, and clicking on any icon successfully reacts. Other messages are similar. Notice that the DOM containing the icon elements is always there; it is just hidden using CSS and only appears when you hover over.

How the reaction feature works

So the idea is to write a piece of code that retrieves all the DOM elements containing messages, iterates through each one, and clicks on the icon to successfully react.

First, the function to get all messages:

const getListMessage = () => {
  return (
    document.querySelectorAll(
      "div.message-content-wrapper.can-select-text > div"
    ) || []
  );
};

div.message-content-wrapper.can-select-text > div is the selector for each message.

The function checks if a message has been reacted to by checking if the .Reactions element exists.

const checkReactMessage = (elm) => {
  if (elm) {
    return !!elm.querySelector(".Reactions");
  }
  return false;
};

The function that reacts to a message by click:

const react = (elm) => {
  if (elm) {
    elm.click();
  }
};

A main processing function:

const main = () => {
  const listMessage = getListMessage();
  listMessage.forEach((elm) => {
    if (!checkReactMessage(elm)) {
      react(elm.querySelector('div.quick-reaction'));
    }
  });
};

Finally, call the main function and see the result. If you want it to continue reacting to new messages afterward, add the setInterval function to repeat the action periodically.

setInterval(main, 3000);

The result.

Result

Conclusion

The DOM is a programming interface for web documents. JavaScript can easily interact with the DOM. Particularly, the ability to run JavaScript directly from the Console in the browser allows you to comfortably create automated actions on behalf of the user. The above article is a specific example of how JavaScript can continuously react to messages on the web Telegram. Additionally, readers can do the same on other websites they desire. If you have any new ideas, please leave a comment for me and everyone to know. Thank you.

Premium
Hello

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (1)

Leave a comment...
Avatar
Anh Đức Trừ1 year ago

bài viết của mình về Google Chrome Developer Tools bạn đọc thử nhé. https://www.blogchemgio.com/2022/06/google-chrome-developer-tools.html

Reply
Avatar
Xuân Hoài Tống1 year ago

Cảm ơn bạn, một bài viết khá chi tiết về developer tools 😄