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
  • Since the Lunar New Year holiday has started, I won't be posting anymore. See you all after the holiday! 😁

    » Read more
  • Continuing about jj. I'm wondering if there are any GUI software made for it yet to make it easier to use. There are already so many similar to git that I can't count them all.

    Luckily, the author has compiled them all together in Community-built tools around Jujutsu 🥳

    » Read more
  • Turso announces that they are rewriting SQLite in Rust. This adds another piece of evidence supporting the notion that Rust is "redefining" many things.

    But the deeper reason is more interesting. Why are they doing this? Everyone knows that SQLite is open source, and anyone can create a fork to modify it as they wish. Does the Turso team dislike or distrust C—the language used to build SQLite?

    Let me share a bit of a story. Turso is a provider of database server services based on SQLite; they have made some customizations to a fork of SQLite to serve their purposes, calling it libSQL. They are "generous" in allowing the community to contribute freely.

    Returning to the point that SQLite is open source but not open contribution. There is only a small group of people behind the maintenance of this source code, and they do not accept pull requests from others. This means that any changes or features are created solely by this group. It seems that SQLite is very popular, but the community cannot do what they want, which is to contribute to its development.

    We know that most open source applications usually come with a "tests" directory that contains very strict tests. This makes collaboration in development much easier. If you want to modify or add a new feature, you first need to ensure that the changes pass all the tests. Many reports suggest that SQLite does not publicly share this testing suite. This inadvertently makes it difficult for those who want to modify the source code, as they are uncertain whether their new implementation is compatible with the existing features.

    tursodatabase/limbo is the project rewriting SQLite in Rust mentioned at the beginning of this article. They claim that it is fully compatible with SQLite and completely open source. Limbo is currently in the final stages of development. Let’s wait and see what the results will be in the future. For a detailed article, visit Introducing Limbo: A complete rewrite of SQLite in Rust.

    » Read more

The Problem

As you may know, before the emergence of React, Vue, etc., jQuery was the dominant force behind many websites. Almost every website used jQuery because it provided powerful DOM manipulation functions to change data. However, due to its bulkiness and complexity, along with the rise of modern web development tools, it is now on the "brink of death."

When accessing a web page, every action you take represents an interaction with the DOM. Besides users, there are other entities that can interact with the DOM, such as JavaScript. This means that you can use JavaScript to interact with the DOM just like a normal user would. From there, you can automate a series of repetitive actions without any user intervention.

Most modern browsers now provide a feature called the Console, which allows us to write and execute JavaScript code directly on the currently accessed web page. In today's article, I will present a concrete example of how to write JavaScript code to perform a repetitive action on a web page. Hopefully, through this article, readers can imagine more applications and apply them in their daily work.

DOM and JavaScript

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

JavaScript can interact with the DOM in a powerful way. Think of the DOM as a Web API provided by the browser, granting us full access and control. Almost every great web experience today involves JavaScript. With the development of the web, we have more dynamic websites that focus on user experience. Many frameworks and libraries based on JavaScript enhance the interaction with the DOM and contribute to creating feature-rich websites.

Browsers allow us to run JavaScript code directly on a web page through their Dev Tools. In Chrome, after opening the Dev Tools and going to the Console tab, you can write JS code and execute it.

Browser Console

Taking advantage of this feature, many hackers used to trick users into pasting a piece of code to steal their data. But in this article, I won't delve into that topic. The purpose is to help readers understand how to use JavaScript to interact with the DOM.

It may sound lengthy, so let's take a simple example like "constantly reacting with emojis in Telegram messages" to help readers visualize how JavaScript can be used to interact with the DOM.

Constantly Reacting with Emojis in Telegram Messages

Most OTT messaging services now provide web versions for users to use. One feature I find interesting is the ability to react to messages using emojis to express emotions. I like it because sometimes I don't need to reply, I just need to drop an emoji. Or sometimes I react to let the sender know that I've read their message and express how I feel about it.

I have a habit of reacting to messages. Partly because I want them to know that I've read their message, partly because of my "playfulness." On Telegram, I have a group of friends who talk about various topics, and to make it less boring whenever my hands are "free," I wrote a script to automatically drop emojis into their messages.

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

First, I notice that whenever I mouse over the time frame, emojis will appear, and when I click on an emoji, the reaction is successful. The same applies to other messages. Pay attention that the DOM of the emoji is always there, but it is hidden by CSS and only appears when we mouse over it.

How emoji reactions work

So the idea is to grab all the messages, loop through each one, and click on the emoji to perform the reaction.

First, let's create a function to get all the 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.

Next, let's create a function to check if a message has already been reacted to by checking for the .Reactions element:

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

Next, let's create a function to react to a message by clicking:

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

Finally, let's create the main function:

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

After that, you can call the main function and see the results. Or if you want it to keep reacting to new messages, you can add the setInterval function.

setInterval(main, 3000);

The result is:

Result

Conclusion

DOM is a programming interface for web documents. JavaScript can easily interact with the DOM. Especially, being able to run JavaScript directly in the Console of a browser allows you to comfortably perform user actions automatically on their behalf.

Premium
Hello

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member 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ừ11 months 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ống11 months ago
Cảm ơn bạn, một bài viết khá chi tiết về developer tools 😄
Scroll or click to go to the next page