Home Programming How you can Create a Chrome Extension in 10 Minutes Flat — SitePoint

How you can Create a Chrome Extension in 10 Minutes Flat — SitePoint

0
How you can Create a Chrome Extension in 10 Minutes Flat — SitePoint

[ad_1]

Have you ever ever thought-about constructing your personal Chrome extension however thought the method could be too advanced? Properly, you’re in for a shock! Within the subsequent couple of minutes, 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 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 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 data 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.

For those who’re scratching your head questioning what a molly-guard is, it initially referred to a protect 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 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 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 looking expertise. Extensions are developed utilizing normal net applied sciences — HTML, JavaScript, and CSS — they usually 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.

Be aware: 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 numerous kinds 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 concentrate on 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 likely be organized in a devoted folder. This extension listing will comprise all the mandatory information to make our molly-guard perform easily.

Right here’s a breakdown:

  • Folder: chatgpt-molly-guard. That is the foundation listing of our extension. All our information will reside on this folder.
  • File: manifest.json. The guts and soul of our extension. This file accommodates metadata in regards to the extension, equivalent 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 checklist of delicate phrases or phrases the person 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: kinds.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 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 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 should 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 elective.

Key Manifest Parts

  • manifest_version: an integer specifying the model of the manifest file format. We’re utilizing Manifest V3, the newest 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 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 net pages. They will view and manipulate the DOM of the web page they’re operating 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().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 high of the file we declare a debounce perform. We’ll use this to make sure that we don’t verify for forbidden phrases each time the person presses a key. That will be quite a lot of checks! As an alternative, we’ll wait till the person cease typing earlier than doing something. I’ve taken this snippet from Josh W. Comeau’s web site, so you may take a look at 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 accommodates 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 factor is our goal (the chat window) after which calls the updateUI perform. Because of our debounce perform, this gained’t run constantly, however solely after a quick pause in typing.
  • The second occasion listener is listening for a keydown occasion on our goal. Particularly, it’s anticipating 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 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 observe that we’re utilizing occasion 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 sure to those parts. By anchoring our occasion listeners to the broader DOM and selectively concentrating on particular parts, we are able to circumvent this difficulty.

Step 4: Including Some Styling

Whereas the core performance of our extension is to forestall sure submissions, it’s necessary 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 crimson !necessary;
  background-color: #ffe6e6 !necessary;
}

This provides a distinguished crimson border and a refined crimson background to the enter space each 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 !necessary flag can be value noting. When coping with net pages that you just don’t personal — like on this case with ChatGPT — the present kinds may be very particular. To make sure our kinds take priority and are utilized accurately, the !necessary flag overrides any potential conflicts because of current kinds’ 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 will 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 pieces 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 line with plan, you must see one thing like the image beneath.

The extension working having identified a forbidden word

For those who make any modifications to your extension code — equivalent to updating the glossary — make sure to hit the round arrow within the backside right-hand nook on the extension’s card on the extension web page. This may reload the extension. You’ll then have to 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 objective, however there’s all the time room for enchancment. For those who’re wanting to refine the extension additional and broaden its capabilities, there are some options beneath.

1. Person Interface for Phrase Checklist Modifying

At present, 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 have to persist the phrases to storage.

2. Dealing with Mouse Paste Occasions

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

3. Contextual Override

Blocking sure phrases is usually 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, take into account introducing a function which might disable the molly-guard till the subsequent submit occasion happens.

You can even take a look at 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 data 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 wanting to dive deeper, Google’s official Chrome Extension documentation is a superb beginning place. Moreover, the Chrome Extension migration information presents insights on the transition to Manifest V3, which is essential given the approaching phase-out of Manifest V2 in 2023.

Now that you just’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.



[ad_2]

Supply hyperlink

LEAVE A REPLY

Please enter your comment!
Please enter your name here