Have you ever ever thought-about constructing your individual Chrome extension however thought the method is perhaps too complicated? Properly, you’re in for a shock! Within the subsequent jiffy, we’ll not solely lay out the fundamentals of what a Chrome extension is, but in addition information you thru 5 easy steps to craft your individual.

Curious to see how? Let’s dive in!

Desk of Contents
  1. What Are We Going To Build?
  2. What Is a Google Chrome Extension?
  3. Step 1: Create the Extension Files
  4. Step 2: Create the Manifest File
  5. Step 3: Create the Content Script
  6. Step 4: Adding Some Styling
  7. Step 5: Test the Extension
  8. Taking it Further
  9. Conclusion

What Are We Going To Construct?

In current occasions, we’ve witnessed an explosion in AI capabilities. And whereas our new cyber companions supply unprecedented ranges of help, additionally they include a reminder: don’t share delicate info with them.

I don’t find out about you, however as a rule, my fingers are quicker than my mind. So, to forestall potential slip-ups, we’re going to construct a “molly-guard” for ChatGPT.

In the event you’re scratching your head questioning what a molly-guard is, it initially referred to a protect put over a button or swap to forestall unintended activation. In our context, it’s a digital guardian making certain we don’t overshare.

Customers can specify an inventory of phrases or phrases they deem delicate. Ought to we try and submit a message to ChatGPT containing any of these phrases, the extension will bounce into motion, disabling the submit button and saving us from a possible oversight.

ChatGPT warning on login: Don't share sensitive info

To observe together with this tutorial, you’ll want a ChatGPT account. Don’t have one? You’ll be able to sign up for free here.

The code for this tutorial is available on GitHub.

What Is a Google Chrome Extension?

Earlier than we get began, let’s make clear what a Chrome extension is. A Chrome extension is a small piece of software program designed to reinforce or modify the Chrome looking expertise. Extensions are developed utilizing commonplace net applied sciences — HTML, JavaScript, and CSS — they usually can vary from easy instruments, like colour pickers, to extra intricate ones, like password managers. Many of those extensions can be found for obtain on the Chrome Web Store.

Word: for these eager on a deeper understanding of Chrome extensions, Google’s official documentation is a useful useful resource.

It’s value noting that Google Chrome extensions can take varied types primarily based on their meant perform. Some have a browser motion, visibly represented by an icon subsequent to the deal with bar, offering fast entry to their options. Others would possibly run silently within the background, throughout all net pages or solely on particular ones, relying on their design.

For our tutorial, we’ll deal with an extension kind that makes use of a content material script. This script will enable us to work together and manipulate the DOM of a selected web page – in our case, the ChatGPT interface.

Step 1: Create the Extension Information

To kick issues off, we have to arrange the fundamental construction for our Chrome extension. Our extension, named chatgpt-mollyguard, shall be organized in a devoted folder. This extension listing will include all the mandatory recordsdata to make our molly-guard perform easily.

Right here’s a breakdown:

  • Folder: chatgpt-molly-guard. That is the basis listing of our extension. All our recordsdata will reside on this folder.
  • File: manifest.json. The center and soul of our extension. This file comprises metadata concerning the extension, resembling its title, model, and permissions it requires. Most significantly, it specifies which scripts to run and on which web sites.
  • File: contentScript.js. As its title suggests, this JavaScript file comprises the content material script. This script has direct entry to the net web page’s content material, permitting us to scan for delicate phrases and modify the web page as wanted.
  • File: wordsList.js. A JavaScript file devoted to containing the checklist of delicate phrases or phrases the person specifies. We’ve separated this to make it simple for customers to customise their checklist with out diving into the core performance in contentScript.js.
  • File: kinds.css. A stylesheet so as to add some aptitude to our extension. Whereas our main objective is performance, there’s no hurt in making our warnings or prompts look good!

To get began:

  1. Create a brand new folder in your laptop named chatgpt-molly-guard.
  2. Inside this folder, create the 4 recordsdata listed above.
  3. With the recordsdata in place, we’re prepared to begin filling within the particulars.

The files necessary to create our Google Chrome extension: manifest.json, contentScript.js, wordList.js & styles.css

Within the subsequent sections, we’ll dive deeper into every file and description its particular function within the extension.

Step 2: Create the Manifest File

The manifest file is a JSON file that gives the browser with important particulars about your extension. This file have to be positioned within the extension’s root listing.

Right here’s our manifest construction. Copy this code into manifest.json:

{
  "manifest_version": 3,
  "title": "ChatGPT Molly-guard",
  "model": "1.0",
  "description": "Prevents submission if particular phrases are typed into chat window",
  "content_scripts": [
    {
      "matches": ["https://chat.openai.com/*"],
      "css": ["styles.css"],
      "js": ["wordsList.js", "contentScript.js"]
    }
  ]
}

The manifest file has three obligatory fields, particularly: manifest_version, title and model. All the pieces else is non-compulsory.

Key Manifest Parts

  • manifest_version: an integer specifying the model of the manifest file format. We’re utilizing Manifest V3, the most recent model obtainable. Remember that Google is actively phasing out Manifest V2 extensions in 2023.
  • title: a brief, plain textual content string (max 45 characters) that identifies the extension.
  • model: one to 4 dot-separated integers figuring out the model of the extension.
  • description: a plain textual content string (no HTML, max 132 characters) that describes the extension.
  • content_scripts: this key specifies statically loaded JavaScript or CSS recordsdata for use each time a web page is opened that matches a URL sample (specified by the matches key). Right here, we’re saying that our script ought to run on any URL beginning with https://chat.openai.com/.

Of the above fields, Google will use the title, model and description when displaying your extension on Chrome’s extension administration web page () and within the Chrome Net Retailer.

Although our manifest is streamlined for our wants, many different fields can add depth and performance to your extensions. Fields such motion, default_locale, icons, and so forth, supply customization choices, UI management, and internationalization help.

For a complete overview of what’s obtainable within the manifest.json file, please seek the advice of Google’s official documentation.

Step 3: Create the Content material Script

Content material scripts in a Chrome extension are JavaScript recordsdata that run within the context of net pages. They’ll view and manipulate the DOM of the web page they’re working on, enabling them to change each the net web page’s content material and conduct.

That is our content material script. Copy the next code into the contentScript.js file:

const debounce = (callback, wait) => {
  let timeoutId = null;
  return (...args) => {
    window.clearTimeout(timeoutId);
    timeoutId = window.setTimeout(() => {
      callback.apply(null, args);
    }, wait);
  };
};

perform containsForbiddenWords(worth) {
  return forbiddenWords.some(phrase => worth.toLowerCase().consists of(phrase.toLowerCase()));
}

perform updateUI(goal) {
  const containsForbiddenWord = containsForbiddenWords(goal.worth);
  const sendButton = goal.nextElementSibling;
  const parentDiv = goal.parentElement;

  if (containsForbiddenWord) {
    sendButton.disabled = true;
    parentDiv.classList.add('forbidden-div');
  } else {
    sendButton.disabled = false;
    parentDiv.classList.take away('forbidden-div');
  }
}

doc.physique.addEventListener('keyup', debounce((occasion) => {
  if (occasion.goal.id === 'prompt-textarea') updateUI(occasion.goal);
}, 300));

doc.addEventListener('keydown', (e) => {
  if (e.goal.id === 'prompt-textarea' && e.key === 'Enter') {
    if (containsForbiddenWords(e.goal.worth)) {
      e.stopPropagation();
      e.preventDefault();
    }
  }
}, true);

Let’s break this down, step-by-step.

On the high of the file we declare a debounce perform. We’ll use this to make sure that we don’t examine for forbidden phrases each time the person presses a key. That might be plenty of checks! As a substitute, we’ll wait till the person cease typing earlier than doing something. I’ve taken this snippet from Josh W. Comeau’s site, so you’ll be able to try his submit for a proof of the way it works.

Subsequent comes a containsForbiddenWords perform. Because the title implies, this perform returns true if the textual content handed to it comprises any of our forbidden phrases. We’re lower-casing each values to make sure that the comparability is case-insensitive.

The updateUI perform determines if any forbidden phrases are current within the chat field. If they’re, it disables the ship button and provides a CSS class (forbidden-div) to the chat field’s dad or mum div. We’ll leverage this within the subsequent step to supply a visible cue to the person.

The script lastly registers two occasion listeners:

  • The primary is ready to set off on a keyup occasion. It checks if the modified aspect is our goal (the chat window) after which calls the updateUI perform. Because of our debounce perform, this received’t run repeatedly, however solely after a short pause in typing.
  • The second occasion listener is listening for a keydown occasion on our goal. Particularly, it’s looking ahead to the Enter keypress, which, if pressed whereas a forbidden phrase is within the textual content space, will forestall the the browser’s default motion (on this case a type submission).

This successfully stops messages with forbidden phrases from being despatched, each by disabling the ship button and by intercepting and halting the Enter keypress.

You’ll additionally notice that we’re utilizing event delegation, because the ChatGPT interface is an SPA. In SPAs, segments of the person interface are dynamically changed primarily based on person interactions, which may inadvertently detach any occasion listeners certain to those components. By anchoring our occasion listeners to the broader DOM and selectively focusing on particular components, we are able to circumvent this subject.

Step 4: Including Some Styling

Whereas the core performance of our extension is to forestall sure submissions, it’s vital for customers to immediately acknowledge why their motion is being blocked. Let’s add some styling to supply a visible cue and improve the person expertise.

Right here’s the rule we’re utilizing. Add it to the kinds.css file:

.forbidden-div {
  border: 2px stable purple !vital;
  background-color: #ffe6e6 !vital;
}

This provides a distinguished purple border and a delicate purple background to the enter space every time forbidden phrases are detected. It instantly attracts consideration and signifies that one thing isn’t proper. By toggling a category on a dad or mum div, we are able to simply flip this on and off.

The !vital flag can be value noting. When coping with net pages that you just don’t personal — like on this case with ChatGPT — the prevailing kinds could be very particular. To make sure our kinds take priority and are utilized appropriately, the !vital flag overrides any potential conflicts as a consequence of current kinds’ specificity.

Step 5: Check the Extension

There’s one final step: populating the checklist of forbidden phrases that our extension ought to monitor for. We will add these in forbiddenWords.js:

const forbiddenWords = [
  "my-company.com",
  "Pylogix",
  "Jim",
];

Now that our customized Google Chrome extension is all arrange, it’s time to check its performance and guarantee all the things is working as meant.

  1. Open Chrome and navigate to within the deal with bar.
  2. Activate the Developer mode toggle, positioned on the high proper nook.
  3. Click on on the Load unpacked button, which can now be seen.
  4. Navigate to and choose the listing of your extension (chatgpt-molly-guard in our case) and click on Choose. Our extension ought to now seem within the checklist of put in extensions.

Custom extension is loaded into the Google Chrome browser

Now, to check out the performance, navigate to ChatGPT, refresh the web page and check out typing in your restricted phrases to see if the extension behaves as anticipated.

If all has gone in keeping with plan, it is best to see one thing like the image beneath.

The extension working having identified a forbidden word

In the event you make any adjustments to your extension code — resembling updating the glossary — remember to hit the round arrow within the backside right-hand nook on the extension’s card on the extension web page. This can reload the extension. You’ll then must reload the web page that your extension is focusing on.

Click the circle to reload the Chrome extension

Taking it Additional

Our present fundamental Chrome extension serves its function, however there’s at all times room for enchancment. In the event you’re wanting to refine the extension additional and increase its capabilities, there are some solutions beneath.

1. Person Interface for Phrase Listing Enhancing

At the moment, our extension depends on a predefined checklist of restricted phrases. Implementing a user-friendly interface would enable customers to dynamically add, take away, or modify phrases on the go. This may be executed utilizing a popup UI (browser motion) that opens when the extension icon is clicked, the place customers can handle their checklist. You’ll additionally must persist the phrases to storage.

2. Dealing with Mouse Paste Occasions

Whereas our extension detects keypresses, customers can bypass this by pasting delicate info utilizing the mouse’s right-click menu. To plug this loophole, we may add an occasion listener for the paste occasion (or consolidate each to pay attention for enter). This can be certain that, whether or not info is typed or pasted, the filter stays strong.

3. Contextual Override

Blocking sure phrases generally is a bit too generic. For instance, I would need to block mentions of “Jim” (my title) however haven’t any points referencing “Jim Carey”. To deal with this, contemplate introducing a characteristic which might disable the molly-guard till the following submit occasion happens.

You too can try the Firefox version of this extension, the place this performance has been carried out.

Conclusion

As we’ve found, constructing your individual Google Chrome extension isn’t an insurmountable problem. We began with a transparent goal: to create a protecting layer for ChatGPT, making certain that delicate info stays confidential. All through this tutorial, we’ve seen how a handful of recordsdata and a little bit of code may end up in a practical and helpful browser extension.

For these wanting to dive deeper, Google’s official Chrome Extension documentation is a wonderful beginning place. Moreover, the Chrome Extension migration guide presents insights on the transition to Manifest V3, which is essential given the upcoming phase-out of Manifest V2 in 2023.

Now that you just’ve seen the way it’s executed, I encourage you to refine, improve, and adapt the extension to fit your wants. You’re welcome to hit me up on Twitter and let me find out about any enhancements you’ve made.