banner



What You Need To Learn To Build Browser Extension

How to Write Your Own Browser Extension [Example Project Included]

In this article we will talk nearly Browser extensions – what they are, how they work, and how you can build your ain.

We will cease by actually writing our own extension (Super Fun!) which allows usa to copy any lawmaking snippet to our clipboard with a click of a single push button.

To continue with this article:

  • You need to accept a bones understanding of JavaScript.
  • You lot need the Firefox browser (or any other browser will also work)

What is a Browser Extension?

A browser extension is something you add together to your browser which enhances your browsing experience by extending the chapters of your browser.

Every bit an example, think near an ad blocker which you lot might have installed on your device. This makes your browsing feel better past blocking ads when you surf the web.

How to Write Your Ain Basic Browser Extension

Now allow's start by writing a very bones extension.

To brainstorm, we'll create a folder inside which we create a file named manifest.json.

What is a manifest file?

A manifest file is a must have file in whatever browser extension. This file contains basic information nearly our extension similar proper name, version, so on.

Now within the manifest.json file copy the following snippet:

                {   "manifest_version":2,   "version":"1.0",   "name":"Test", }                              

How to load the extension file

For Firefox users, follow these steps:

In the accost bar, search for this:

                nigh:debugging#/runtime/this-firefox              

You lot will see an selection to Load Temporary Add-on. Click on that pick and cull the manifest.json file from the directory.

For Chrome users:

In the address bar search for this:

                chrome://extensions.              
  • Enable Programmer Mode and switch into it.
  • Click the Load unpacked button and select the extension directory.

Hurray! You've installed the extension successfully. But the extension doesn't do annihilation currently. Now permit's add some functionality to our extension. To do this, nosotros'll edit our manifest.json file like this:

                {   "manifest_version":2,   "version":"1.0",   "name":"Examination",   "content_scripts":[     {      "matches":["<all_urls>"],      "js":["master.js"]     }   ] }              

In the higher up lawmaking, we added a content script to manifest.json. Content scripts can manipulate the Document Object Model of the web page. Nosotros can inject JS (and CSS) into a web folio using a content script.

"matches" contains the list of domains and subdomains where the content script should be added and js is an assortment of the JS files to be loaded.

At present inside the same directory create a main.js file and add the following lawmaking:

                alert("The examination extension is upward and running")              

Now reload the extension and when you lot visit any URLs you will come across an alert message.

Don't forget to reload the extension anytime you lot edit the code.

How to Customize Your Browser Extension

Now let'southward have some more than fun with our extension.

What we are going to do now is create a web extension that changes all the images of a webpage we visit to an epitome we choose.

For this, but add together any image to the electric current directory and change the main.js file to:

                console.log("The extension is upwards and running");  var images = document.getElementsByTagName('img')  for (elt of images){    elt.src = `${browser.runtime.getURL("pp.jpg")}`    elt.alt = 'an alt text' }              

Let's see whats going on here:

                var images = document.getElementsByTagName('img')              

This line of code selects all the elements in the spider web folio with the img tag .

And then we loop through the assortment images using a for loop where we change the src attribute of all the img elements to a URL with the assist of the runtime.getURL function.

Here pp.jpg is the name of the image file in the current directory in my device.

We need to inform our content script about the pp.jpg file by editing the manifest.json file to:

                {   "manifest_version":2,   "version":"1.0",   "proper noun":"Test",   "content_scripts":[    {     "matches":["<all_urls>"],     "js":["principal.js"]    }   ],   "web_accessible_resources": [         "pp.jpg"   ] }                              

And so merely reload the extension and visit any URL you like. Now y'all should meet all the images being inverse to the prototype which is in your current working directory.

How to add together icons to your extension

Add the following code in the manifest.json file:

                "icons": {   "48": "icon-48.png",   "96": "icon-96.png" }                              

How to add a toolbar push button to your extension

Now nosotros'll add a button located in the toolbar of your browser. Users can interact with the extension using this button.

To add a toolbar push, add the post-obit lines to the manifest.json file:

                "browser_action":{    "default_icon":{      "19":"icon-19.png",      "38":"icon-38.png"    }   }              

All the image files should be present in your current directory.

Now, if we reload the extension we should meet an icon for our extension in the toolbar of our browser.

How to add listening events for the toolbar button

Maybe nosotros want to practise something when a user clicks the push button – permit'south say we want to open a new tab every fourth dimension the button is clicked.

For this, we'll again add the following to the manifest.json file:

                "background":{         "scripts":["groundwork.js"]   },   "permissions":[       "tabs"   ]                              

And so nosotros'll create a new file named background.js in the current working directory and add the following lines in the file:

                function openTab(){          var newTab = browser.tabs.create({         url:'https://twitter.com/abhilekh_gautam',         active:true     }) }  browser.browserAction.onClicked.addListener(openTab)                              

At present reload the extension!

Whenever someone clicks the button, it calls the openTab function which opens a new tab with the URL that links to my twitter profile. Besides, the agile key, when set to truthful, makes the newly created tab the current tab.

Note that you tin can use APIs provided by browsers in the background script. For more than almost APIs refer to the following article: Javacript APIs.

Now that nosotros've learned some of the basics of browser extensions, let'south create an extension that we as developers can employ in our daily lives.

Last Project

Alright, now we're going to write something that volition be useful for us in daily life. We'll create an extension that allows y'all to re-create code snippets from StackOverflow with a unmarried click. So our extension volition add a Copy push button to the webpage which copies the code to our clipboard.

Demo

demo

First nosotros'll create a new folder/directory, inside which we'll add a manifest.json file.

Add the post-obit lawmaking to the file:

                {   "manifest_version":2,   "version":"i.0",   "proper name":"copy code",   "content_scripts":[     {      "matches":["*://*.stackoverflow.com/*"],      "js":["main.js"]     }   ] }              

Look at the matches inside the content script – the extension will merely piece of work for StackOverflow'southward domain and subdomain.

Now create another JavaScript file chosen main.js in the same directory and add the following lines of code:

                var arr =document.getElementsByClassName("s-code-block")  for(allow i = 0 ; i < arr.length ; i++){  var btn = certificate.createElement("button")  btn.classList.add together("copy_code_button")  btn.appendChild(document.createTextNode("Copy"))  arr[i].appendChild(btn)  //styling the push  btn.style.position = "relative"    if(arr[i].scrollWidth === arr[i].offsetWidth && arr[i].scrollHeight === arr[i].offsetHeight)   btn.way.left = `${arr[i].offsetWidth - 70}px`    else if(arr[i].scrollWidth != arr[i].offsetWidth && arr[i].scrollHeight === arr[i].offsetWidth)    btn.fashion.left = `${arr[i].offsetWidth - 200}px`  else     btn.manner.left = `${arr[i].offsetWidth - 150}px`     if(arr[i].scrollHeight === arr[i].offsetHeight)    btn.way.bottom = `${arr[i].offsetHeight - 50}px`      else    btn.way.bottom = `${arr[i].scrollHeight - fifty}px`  //end of styling the push        console.log("Appended") }              

Showtime of all, I selected all the elements with the form name s-code-block – only why? This is because when I inspected StackOverflow's site I institute that all the code snippets were kept in a grade with that proper name.

And then we loop through all those elements and append a button in those elements. Finally, nosotros only position and style the push properly (the styling'due south non perfect nonetheless – this is merely a outset).

When we load the extension using the procedure we went through to a higher place and visit StackOverflow, nosotros should see a copy button.

How to add functionality to the button

Now, when the button is clicked we want the entire snippet to exist copied to our prune board. To practise this, add together the following line of code to the master.js file:

                var button = certificate.querySelectorAll(".copy_code_button")  button.forEach((elm)=>{   elm.addEventListener('click',(e)=>{     navigator.clipboard.writeText(elm.parentNode.childNodes[0].innerText)     warning("Copied to Clipboard")   })  })              

First of all, we select all the buttons we take added to the site using querySelectorAll. Then nosotros heed for the click upshot whenever the button is clicked.

                navigator.clipboard.writeText(elm.parentNode.childNodes[0].innerText)                              

The above line of code copies the code to our clipboard. Whenever a snippet is copied we alert the user with the message Copied to clipboard and we are washed.

Terminal Words

Spider web Extensions can be useful in various way and I promise with the help of this article you will be able to write your own extensions.

All the code can be found in this GitHub repository. Don't forget to give a pull request anytime you come upwards with some skillful styling or a new characteristic similar clipboard history and others.

Happy Coding!



Acquire to lawmaking for free. freeCodeCamp'southward open source curriculum has helped more than than 40,000 people get jobs as developers. Get started

Source: https://www.freecodecamp.org/news/write-your-own-browser-extensions/

Posted by: grahamthein2000.blogspot.com

0 Response to "What You Need To Learn To Build Browser Extension"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel