Sorting Cses Probleset Within Console/Extension[Tutorial]
Tags: javascript, webdev, programming, tutorial
Published: 2023-06-23 21:19:23


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rgzaxwl2dvzwfyaez9ue.png)

# Introduction:
Imagine you are a passionate problem solver visiting the CSES problemset list page, filled with intriguing challenges. However, the unsorted elements make it challenging to find the problems you're looking for. In this captivating journey, we will explore how we can overcome this obstacle by creating a Chrome extension that sorts the elements based on the content of the <span> element. Additionally, we'll uncover a small trick that you can use right away by running a simple code snippet in your browser console. Let's embark on this adventure together and transform your browsing experience!

## Step 1: Setting the Stage:
To begin our quest, we need to create a new directory to house our extension's development. This will serve as our workspace, where we bring our solution to life. Inside this directory, we must craft a special file called manifest.json. This file acts as the foundation, containing vital information such as the extension's name, version, description, icons, and permissions.

manifest.json

    {
      "manifest_version": 2,
      "name": "CSES Sort Extension",
      "version": "1.0",
      "description": "Sorts elements on CSES problemset list page",
      "icons": {
        "16": "icon16.png",
        "48": "icon48.png",
        "128": "icon128.png"
      },
      "permissions": ["activeTab"],
      "background": {
        "scripts": ["background.js"],
        "persistent": false
      },
      "page_action": {
        "default_popup": "popup.html",
        "default_icon": {
          "16": "icon16.png",
          "48": "icon48.png",
          "128": "icon128.png"
        }
      }
    }


## Step 2: Unveiling the Background Script:
In our journey, we encounter the mysterious background script, represented by the background.js file. This script takes center stage, orchestrating the extension's actions. As we interact with the extension's button, the background script listens attentively, awaiting the signal to execute the content script. The stage is set for our grand performance.

background.js

    chrome.pageAction.onClicked.addListener(function (tab) {
      chrome.tabs.executeScript(tab.id, { file: 'content.js' });
    });



## Step 3: The Enchanting Popup HTML:
In this magical realm, we craft the popup.html file, an enchanting piece of HTML that breathes life into our extension's interface. Inside this mystical realm, a button materializes. This button acts as a gateway, empowering us to trigger the sorting action and unveil the sorted elements on the CSES problemset list page.

popup.html

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>CSES Sort Extension</title>
        <script src="popup.js"></script>
      </head>
      <body>
        <button id="sortButton">Sort Elements</button>
      </body>
    </html>


## Step 4: The Spellbinding Popup Script:
The popup.js script casts its spell, bringing interactivity to our popup. As we click the button, a message is whispered into the content script's ear. Using the secret language of chrome.tabs.sendMessage(), our desires are conveyed, instructing the content script to perform its magic.

popup.js

    document.addEventListener('DOMContentLoaded', function () {
      var sortButton = document.getElementById('sortButton');
    
      sortButton.addEventListener('click', function () {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
          chrome.tabs.sendMessage(tabs[0].id, { action: 'sortElements' });
        });
      });
    });


### Step 5: The Mystical Content Script:
In the depths of the CSES problemset list page, our content.js script takes center stage. It possesses the arcane knowledge to transform the unsorted elements into a harmonious arrangement. With a stroke of genius, it locates the elements, extracts the captivating content of the <span> element, and conducts a mesmerizing sorting ritual. The page is then reborn with the sorted elements, delighting our senses.

content.js

    function sortElements() {
      const ulElements = document.querySelectorAll('ul.task-list');
    
      ulElements.forEach((ul) => {
        const liElements = Array.from(ul.querySelectorAll('li.task'));
    
        liElements.sort((a, b) => {
          const spanA = a.querySelector('span.detail');
          const spanB = b.querySelector('span.detail');
          const dataA = parseInt(spanA.textContent.trim().split(' / ')[0]);
          const dataB = parseInt(spanB.textContent.trim().split(' / ')[0]);
          return dataA - dataB;
        });
    
        liElements.forEach((li) => ul.appendChild(li));
      });
    }
    
    chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
      if (request.action === 'sortElements') {
        sortElements();
      }
    });


### Step 6: A Visual Marvel:
Our adventure wouldn't be complete without adding a touch of visual marvel. By customizing the extension's icons and embellishing the popup HTML with captivating styles, we ensure a captivating visual experience. The extension becomes an exquisite masterpiece that enchants our eyes and invigorates our browsing journey.

## Bonus Trick: 

### Sorting Elements with the Browser Console:
For those who can't wait to experience the magic of sorted elements, there's a small trick you can use right away by running a code snippet in your browser console. Visit the CSES problemset list page, open the browser console, and execute the following code:

    // Get the <div> element with the class name "content"
    const div = document.querySelector('div.content');
    
    // Get all the <ul> elements with the class name "task-list" inside the <div>
    const ulElements = div.querySelectorAll('ul.task-list');
    
    // Iterate over each <ul> element
    ulElements.forEach(ul => {
      const liElements = Array.from(ul.querySelectorAll('li.task'));
    
      // Sort the <li> elements based on the post data element
      liElements.sort((a, b) => {
        const spanA = a.querySelector('span.detail');
        const spanB = b.querySelector('span.detail');
        const dataA = parseInt(spanA.textContent.trim().split(' / ')[0]);
        const dataB = parseInt(spanB.textContent.trim().split(' / ')[0]);
        return dataA - dataB;
      });
    
      // Re-render the <ul> with the sorted <li> elements
      liElements.forEach(li => ul.appendChild(li));
    });


### Conclusion:
 With our Chrome extension in hand and the bonus trick at our disposal, we have embarked on a remarkable adventure. We have overcome the obstacle of unsorted elements on the CSES problemset list page, transforming it into a realm of organized enchantment. Each visit becomes a delightful experience, thanks to our creation. As we continue to explore new challenges, our extension accompanies us, simplifying our journey with sorted elements.

May your browsing adventures be filled with joy and success as you explore the CSES problemset list with your personalized Chrome extension and the handy browser console trick!