DEV Community

Cover image for How ChatGPT wrote my first chrome extension
Victor Guzman
Victor Guzman

Posted on

How ChatGPT wrote my first chrome extension

As a developer, I've always been curious about building browser extensions. However, I never knew where to start. That was until I started using ChatGPT.

With ChatGPT being the trending topic lately, I decided to run an experiment and test its capabilities. So, I decided to let ChatGPT build my very first chrome extension. And this is the blogpost on how it went.

About the extension

ChatGPT taught me how to build my very first browser extension, CSS Highlight. It allows users to highlight HTML elements with a specific class or ID using CSS.

About the process

The first step in building this extension was creating the manifest.json file, which provides information about the extension, such as its name and version, and specifies which files it will use. ChatGPT helped me create the file by providing a template and explaining each section in detail.

{
  "name": "CSS-Highlight",
  "version": "1.0.0",
  "manifest_version": 3,
  "description": "Highlight HTML elements with a specific class or ID",
  "icons": {
  },
  "action": {
    "default_popup": "popup/popup.html",
    "default_title": "CSS-Highlight"
  },
  "background": {
    "service_worker": "background/background.js"
  },
  "content_scripts": [
    {
      "matches": [
        "http://*/*",
        "https://*/*",
        "<all_urls>"
      ],
      "js": [
        "content/content.js"
      ]
    }
  ],
  "permissions": [
    "activeTab"
  ]
}
Enter fullscreen mode Exit fullscreen mode

Once the manifest.json file was set up, ChatGPT helped me create the HTML, CSS, and JavaScript files for the extension. We started with the popup.html file, which contains the interface for the extension. ChatGPT guided me through the process of creating the layout and adding the necessary HTML elements.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>CSS-Highlight</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="popup.js"></script>
</head>
<body>
    <h1>CSS-Highlight</h1>
    <form>
    <h3>Search for:</h3>
    <select id="searchType">
      <option value="both" selected>All</option>
      <option value="class">Class</option>
      <option value="id">ID</option>
    </select>
    <input type="text" id="identifierInput" placeholder="e.g. my-class">
        <input type="color" id="colorInput" value="#ffdc00"/>
        <div class="buttons-container">
            <button id="highlightButton" class="btn">Highlight</button>
            <button id="resetButton" class="btn">Reset</button>
        </div>
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode
document.addEventListener('DOMContentLoaded', function() {
  document.getElementById('highlightButton').addEventListener('click', function(event) {
    event.preventDefault();

    var searchType = document.getElementById('searchType').value;
    var identifier = document.getElementById('identifierInput').value;
    var color = document.getElementById('colorInput').value;

    if (identifier !== '') {
      chrome.runtime.sendMessage({
        name: 'highlight',
        searchType: searchType,
        identifier: identifier,
        color: color
      });
    }
  });

  document.getElementById('resetButton').addEventListener('click', function(event) {
    event.preventDefault();
    document.getElementById('searchType').value = 'both'
    document.getElementById('identifierInput').value = ''
    document.getElementById('colorInput').value = '#ffdc00'
    chrome.runtime.sendMessage({
      name: 'reset',
    });
  });
});
Enter fullscreen mode Exit fullscreen mode

Next, we moved on to the content.js file, which is responsible for highlighting the HTML elements. ChatGPT helped me write the JavaScript code for the extension and explained how to use the Document Object Model (DOM) to manipulate the HTML elements on a web page.

let originalElements = [];

chrome.runtime.onMessage.addListener(function(message) {
  if(message.name === 'highlight') {
    highlight(message.searchType, message.identifier, message.color);
  }
  if(message.name === 'reset') {
    reset();
  }
});

function highlight(type, identifier, color) {
  if (type === 'class') {
    elements = document.getElementsByClassName(identifier);
  } else if (type === 'id') {
    var element = document.getElementById(identifier);
    elements = element ? [element] : [];
  } else {
    elements = document.querySelectorAll(`.${identifier},#${identifier}`);
  }

  for (var i = 0; i < elements.length; i++) {
    let element = elements[i];
    originalElements.push({object: element, color: element.style.backgroundColor});
    element.style.backgroundColor = color;
  }
}

function reset() {
  for (var i = 0; i < originalElements.length; i++) {
    let element = originalElements[i];
    if (element.object) {
      element.object.style.backgroundColor = element.color;
    }
  }
  originalElements = [];
}
Enter fullscreen mode Exit fullscreen mode

With the help of ChatGPT, we were able to implement this background script using the WebExtensions API provided by the browser. The script listens for messages from the popup and content scripts, and relays those messages as needed. This allows for seamless communication between the different parts of the extension, making it work smoothly and efficiently for the user.

chrome.runtime.onMessage.addListener(function(message) {
  switch(message.name) {
    case 'highlight':
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, message);
      });
      break;
    case 'reset':
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {name: 'reset'});
      });
      break;
  }
});
Enter fullscreen mode Exit fullscreen mode

Final thoughts

Throughout the process, ChatGPT was patient, clear, and knowledgeable. As a language model trained on a vast amount of data, it was able to provide me with accurate and relevant information and guide me through the development process in a way that was easy to understand.

Building my first browser extension with ChatGPT was a fantastic experience. It was a great way to learn new skills, and I'm excited to see where this knowledge will take me in the future.


Real final thoughts

You've probably figured it out by now, but I also asked ChatGPT to generate this blogpost based on the entire conversation. So everything you just read was written by ChatGPT.

These are some of my conclusions (don't worry, these are written by me):

  • The first and most obvious are the limitations it has. Starting with the outdated and limited data. For example, the manifest.json originally created was in version 2 which is deprecated and I had to make manual changes to bring it up to version 3.
  • Generating the correct prompt to get the desired response is not an easy task. On many occasions I had to rethink it or even start over.
  • ChatGPT does not have all the answers. There was a specific error that took me a long time to figure out and after multiple attempts to get ChatGPT to give me the solution, I couldn't. To be fair, the error wasn't very well documented on google either.
  • The time that ChatGPT saves us is enormous. I was able to create the extension in one night, with no prior experience. And best of all, I now have a much better understanding of the basics of a Chrome extension thanks to ChatGPT's explanations. So I coded and learned faster than ever before.
  • I used GTP-3, and now I'm interested on seeing what GTP-4 would have done.

So, what's next? I'm planning to continue building the extension for fun and learning purposes, and obviously publish it on the store.


Bonus thoughts

I asked ChatGPT to write about its own limitations while doing this experiment:

  • ChatGPT is a language model and is limited by the quality and quantity of the data it was trained on.
  • ChatGPT does not have the ability to interact with the browser environment directly, so it was unable to test the extension code in the context of the browser.
  • The extension was built with a limited set of functionality, so it may not be suitable for more complex use cases.
  • The extension was not tested across a wide range of browsers and operating systems, so there may be compatibility issues with certain configurations.
  • ChatGPT is a language model and is not a substitute for an experienced developer who has a deep understanding of web development best practices and browser-specific quirks.

Top comments (1)

Collapse
 
degraft_frimpong profile image
Degraft Frimpong

that great am hopping on to this extension development with GPT