Friday, September 15, 2023
HomeWeb DevelopmentCreate a Chrome Extension in 10 Minutes Flat — SitePoint

Create a Chrome Extension in 10 Minutes Flat — SitePoint


Have you ever ever thought of constructing your individual Chrome extension however thought the method could be too advanced? Effectively, 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 additionally 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 Construct?
  2. What Is a Google Chrome Extension?
  3. Step 1: Create the Extension Information
  4. Step 2: Create the Manifest File
  5. Step 3: Create the Content material Script
  6. Step 4: Including Some Styling
  7. Step 5: Take a look at the Extension
  8. Taking it Additional
  9. Conclusion

What Are We Going To Construct?

In current instances, we’ve witnessed an explosion in AI capabilities. And whereas our new cyber companions supply unprecedented ranges of help, in addition 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 sooner than my mind. So, to stop potential slip-ups, we’re going to construct a “molly-guard” for ChatGPT.

For those who’re scratching your head questioning what a molly-guard is, it initially referred to a defend put over a button or swap to stop unintentional 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 to submit a message to ChatGPT containing any of these phrases, the extension will leap into motion, disabling the submit button and saving us from a possible oversight.

ChatGPT warning on login: Don't share sensitive info

To comply with together with this tutorial, you’ll want a ChatGPT account. Don’t have one? You may join free right here.

The code for this tutorial is obtainable 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 boost or modify the Chrome shopping expertise. Extensions are developed utilizing commonplace internet 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 Internet Retailer.

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 varieties based mostly on their supposed operate. Some have a browser motion, visibly represented by an icon subsequent to the deal with bar, offering fast entry to their options. Others may run silently within the background, throughout all internet 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 particular web page – in our case, the ChatGPT interface.

Step 1: Create the Extension Information

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

Right here’s a breakdown:

  • Folder: chatgpt-molly-guard. That is the basis listing of our extension. All our information will reside on this folder.
  • File: manifest.json. The center and soul of our extension. This file accommodates metadata concerning the extension, akin to 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 accommodates 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 record of delicate phrases or phrases the consumer specifies. We’ve separated this to make it straightforward for customers to customise their record with out diving into the core performance in contentScript.js.
  • File: types.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 pc named chatgpt-molly-guard.
  2. Inside this folder, create the 4 information listed above.
  3. With the information in place, we’re prepared to start out 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 position 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 should be situated 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, specifically: manifest_version, title and model. All the things else is elective.

Key Manifest Components

  • manifest_version: an integer specifying the model of the manifest file format. We’re utilizing Manifest V3, the most recent model obtainable. Bear in mind 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 information 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 Internet 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 information that run within the context of internet pages. They will view and manipulate the DOM of the web page they’re operating on, enabling them to switch each the net web page’s content material and habits.

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);
  };
};

operate containsForbiddenWords(worth) {
  return forbiddenWords.some(phrase => worth.toLowerCase().contains(phrase.toLowerCase()));
}

operate 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 prime of the file we declare a debounce operate. We’ll use this to make sure that we don’t verify for forbidden phrases each time the consumer presses a key. That may be a variety of checks! As a substitute, we’ll wait till the consumer cease typing earlier than doing something. I’ve taken this snippet from Josh W. Comeau’s website, so you’ll be able to take a look at his publish for an evidence of the way it works.

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

The updateUI operate 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 guardian div. We’ll leverage this within the subsequent step to supply a visible cue to the consumer.

The script lastly registers two occasion listeners:

  • The primary is ready to set off on a keyup occasion. It checks if the modified component is our goal (the chat window) after which calls the updateUI operate. Due to our debounce operate, this gained’t run repeatedly, however solely after a quick 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 occasion delegation, because the ChatGPT interface is an SPA. In SPAs, segments of the consumer interface are dynamically changed based mostly on consumer interactions, which might inadvertently detach any occasion listeners sure to those components. By anchoring our occasion listeners to the broader DOM and selectively concentrating on particular components, we are able to circumvent this problem.

Step 4: Including Some Styling

Whereas the core performance of our extension is to stop 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 consumer expertise.

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

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

This provides a outstanding crimson border and a delicate crimson 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 guardian div, we are able to simply flip this on and off.

The !vital flag can also be value noting. When coping with internet pages that you simply don’t personal — like on this case with ChatGPT — the prevailing types might be very particular. To make sure our types take priority and are utilized accurately, the !vital flag overrides any potential conflicts attributable to current types’ specificity.

Step 5: Take a look at the Extension

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

const forbiddenWords = [
  "my-company.com",
  "SitePoint",
  "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 supposed.

  1. Open Chrome and navigate to within the deal with bar.
  2. Activate the Developer mode toggle, situated on the prime 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 record 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 take a look at typing in your restricted phrases to see if the extension behaves as anticipated.

If all has gone based on plan, it is best to see one thing like the image under.

The extension working having identified a forbidden word

For those who make any adjustments to your extension code — akin to updating the thesaurus — you’ll want 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 concentrating on.

Click the circle to reload the Chrome extension

Taking it Additional

Our present fundamental Chrome extension serves its goal, however there’s at all times room for enchancment. For those who’re desperate to refine the extension additional and broaden its capabilities, there are some options under.

1. Consumer Interface for Phrase Listing Enhancing

At present, our extension depends on a predefined record 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 finished utilizing a popup UI (browser motion) that opens when the extension icon is clicked, the place customers can handle their record. 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 hear for enter). This can be sure 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’d need to block mentions of “Jim” (my title) however don’t have any points referencing “Jim Carey”. To deal with this, take into account introducing a function which might disable the molly-guard till the following submit occasion happens.

You can too take a look at the Firefox model of this extension, the place this performance has been applied.

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 information and a little bit of code can lead to a purposeful and helpful browser extension.

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

Now that you simply’ve seen the way it’s finished, 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.



RELATED ARTICLES

Most Popular

Recent Comments