Sunday, September 8, 2024

The right way to Create a Chrome Extension in 10 Minutes Flat — SitePoint

Must read


Have you ever ever thought of constructing your personal Chrome extension however thought the method is perhaps too advanced? 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 additionally information you thru 5 simple steps to craft your personal.

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 Recordsdata
  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 latest occasions, we’ve witnessed an explosion in AI capabilities. And whereas our new cyber companions provide 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 most of the time, my fingers are sooner than my mind. So, to forestall potential slip-ups, we’re going to construct a “molly-guard” for ChatGPT.

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

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

The code for this tutorial is out there 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 shopping expertise. Extensions are developed utilizing customary net applied sciences — HTML, JavaScript, and CSS — and so they can vary from easy instruments, like coloration pickers, to extra intricate ones, like password managers. Many of those extensions can be found for obtain on the Chrome Internet Retailer.

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

It’s price noting that Google Chrome extensions can take numerous 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 give attention to an extension kind that makes use of a content material script. This script will permit us to work together and manipulate the DOM of a particular web page – in our case, the ChatGPT interface.

Step 1: Create the Extension Recordsdata

To kick issues off, we have to arrange the fundamental construction for our Chrome extension. Our extension, named chatgpt-mollyguard, will probably be organized in a devoted folder. This extension listing will include all the required 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 guts and soul of our extension. This file incorporates metadata concerning the extension, corresponding 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 incorporates the content material script. This script has direct entry to the online 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 consumer specifies. We’ve separated this to make it straightforward for customers to customise their checklist 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 major aim 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 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 have to 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 necessary fields, specifically: manifest_version, title and model. Every little thing else is optionally available.

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. 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 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 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, provide 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 will view and manipulate the DOM of the web page they’re working on, enabling them to switch each the online 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);
  };
};

perform containsForbiddenWords(worth) {
  return forbiddenWords.some(phrase => worth.toLowerCase().contains(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 prime of the file we declare a debounce perform. We’ll use this to make sure that we don’t test for forbidden phrases each time the consumer presses a key. That will be a number of checks! As an alternative, 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 may try his put up for an evidence 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 incorporates 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 consumer.

The script lastly registers two occasion listeners:

  • The primary is about 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. Due to our debounce perform, this received’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 awaiting the Enter keypress, which, if pressed whereas a forbidden phrase is within the textual content space, will stop the the browser’s default motion (on this case a kind 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 observe that we’re utilizing occasion delegation, because the ChatGPT interface is an SPA. In SPAs, segments of the consumer interface are dynamically changed primarily based on consumer interactions, which may inadvertently detach any occasion listeners sure to those parts. By anchoring our occasion listeners to the broader DOM and selectively concentrating on particular parts, we will circumvent this difficulty.

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 consumer expertise.

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

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

This provides a outstanding pink border and a delicate pink background to the enter space at any time when 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 will simply flip this on and off.

The !vital flag can be price noting. When coping with net 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 appropriately, the !vital flag overrides any potential conflicts as a consequence of current types’ specificity.

Step 5: Take a look at the Extension

There’s one final step: populating the checklist 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 every thing is working as meant.

  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 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 take a look at typing in your restricted phrases to see if the extension behaves as anticipated.

If all has gone in line with plan, it’s best to see one thing like the image under.

The extension working having identified a forbidden word

In case you make any modifications to your extension code — corresponding to 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. It will 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 all the time room for enchancment. In case you’re desperate to refine the extension additional and develop its capabilities, there are some ideas under.

1. Consumer Interface for Phrase Checklist Modifying

Presently, our extension depends on a predefined checklist of restricted phrases. Implementing a user-friendly interface would permit 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 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). It will make sure that, whether or not info is typed or pasted, the filter stays strong.

3. Contextual Override

Blocking sure phrases is usually a bit too generic. For instance, I would wish to block mentions of “Jim” (my title) however don’t have any points referencing “Jim Carey”. To handle this, think about introducing a characteristic which might disable the molly-guard till the subsequent submit occasion happens.

You too can try the Firefox model of this extension, the place this performance has been applied.

Conclusion

As we’ve found, constructing your personal 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 desperate to dive deeper, Google’s official Chrome Extension documentation is a wonderful beginning place. Moreover, the Chrome Extension migration information provides insights on the transition to Manifest V3, which is essential given the approaching 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.





Supply hyperlink

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article