Plugin That Reads Code on a Webpage
In this article we will talk near Browser extensions – what they are, how they work, and how y'all can build your own.
Nosotros will finish by actually writing our ain extension (Super Fun!) which allows us to copy any lawmaking snippet to our clipboard with a click of a single button.
To continue with this article:
- Yous need to have a basic understanding of JavaScript.
- Yous need the Firefox browser (or any other browser will also work)
What is a Browser Extension?
A browser extension is something y'all add to your browser which enhances your browsing experience past extending the capacity of your browser.
Equally an instance, recall about an advertizement blocker which you might accept installed on your device. This makes your browsing feel ameliorate by blocking ads when you surf the web.
How to Write Your Own Basic Browser Extension
Now let's get-go by writing a very basic extension.
To begin, nosotros'll create a binder inside which we create a file named manifest.json.
What is a manifest file?
A manifest file is a must take file in whatsoever browser extension. This file contains basic data about our extension like proper name, version, so on.
At present within the manifest.json file copy the following snippet:
{ "manifest_version":two, "version":"1.0", "proper name":"Test", } How to load the extension file
For Firefox users, follow these steps:
In the address bar, search for this:
near:debugging#/runtime/this-firefox Y'all will see an option to Load Temporary Add-on. Click on that pick and choose the manifest.json file from the directory.
For Chrome users:
In the address bar search for this:
chrome://extensions. - Enable Developer Way 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 practice anything currently. Now allow'due south add some functionality to our extension. To do this, nosotros'll edit our manifest.json file like this:
{ "manifest_version":ii, "version":"1.0", "name":"Test", "content_scripts":[ { "matches":["<all_urls>"], "js":["main.js"] } ] } In the above code, nosotros added a content script to manifest.json. Content scripts tin can manipulate the Document Object Model of the web page. We can inject JS (and CSS) into a web page using a content script.
"matches" contains the listing of domains and subdomains where the content script should be added and js is an assortment of the JS files to be loaded.
Now inside the same directory create a main.js file and add together the following code:
alert("The test extension is up and running") Now reload the extension and when you visit any URLs yous will see an warning bulletin.
Don't forget to reload the extension anytime you edit the code.
How to Customize Your Browser Extension
At present let's take some more fun with our extension.
What we are going to practise now is create a web extension that changes all the images of a webpage we visit to an image we choose.
For this, just add together any prototype to the current directory and change the main.js file to:
console.log("The extension is upward and running"); var images = certificate.getElementsByTagName('img') for (elt of images){ elt.src = `${browser.runtime.getURL("pp.jpg")}` elt.alt = 'an alt text' } Let'due south see whats going on here:
var images = document.getElementsByTagName('img') This line of lawmaking selects all the elements in the web page with the img tag .
And then nosotros loop through the array images using a for loop where nosotros alter the src attribute of all the img elements to a URL with the help of the runtime.getURL office.
Here pp.jpg is the proper name of the prototype file in the current directory in my device.
We need to inform our content script about the pp.jpg file past editing the manifest.json file to:
{ "manifest_version":2, "version":"1.0", "proper name":"Test", "content_scripts":[ { "matches":["<all_urls>"], "js":["master.js"] } ], "web_accessible_resources": [ "pp.jpg" ] } Then just reload the extension and visit whatsoever URL you like. Now y'all should encounter all the images being changed to the image which is in your electric current working directory.
How to add icons to your extension
Add the post-obit code in the manifest.json file:
"icons": { "48": "icon-48.png", "96": "icon-96.png" } How to add a toolbar button to your extension
Now we'll add a button located in the toolbar of your browser. Users tin collaborate with the extension using this button.
To add a toolbar button, add together the following lines to the manifest.json file:
"browser_action":{ "default_icon":{ "xix":"icon-xix.png", "38":"icon-38.png" } } All the prototype files should be nowadays in your current directory.
Now, if nosotros reload the extension nosotros should encounter an icon for our extension in the toolbar of our browser.
How to add listening events for the toolbar button
Possibly we want to do something when a user clicks the button – permit'due south say we want to open a new tab every time the button is clicked.
For this, nosotros'll again add the following to the manifest.json file:
"background":{ "scripts":["groundwork.js"] }, "permissions":[ "tabs" ] Then nosotros'll create a new file named background.js in the current working directory and add together the post-obit lines in the file:
function openTab(){ var newTab = browser.tabs.create({ url:'https://twitter.com/abhilekh_gautam', active:truthful }) } browser.browserAction.onClicked.addListener(openTab) Now reload the extension!
Whenever someone clicks the push button, it calls the openTab function which opens a new tab with the URL that links to my twitter profile. Too, the agile key, when set up to true, makes the newly created tab the electric current tab.
Annotation that y'all tin use APIs provided by browsers in the groundwork script. For more than about APIs refer to the following commodity: Javacript APIs.
Now that we've learned some of the nuts of browser extensions, allow's create an extension that we every bit developers tin use in our daily lives.
Terminal Project
Alright, now we're going to write something that will exist useful for us in daily life. We'll create an extension that allows you to re-create code snippets from StackOverflow with a single click. So our extension will add a Copy push to the webpage which copies the lawmaking to our clipboard.
Demo
Showtime nosotros'll create a new folder/directory, inside which we'll add a manifest.json file.
Add the following lawmaking to the file:
{ "manifest_version":ii, "version":"1.0", "name":"copy code", "content_scripts":[ { "matches":["*://*.stackoverflow.com/*"], "js":["main.js"] } ] } Wait at the matches inside the content script – the extension will only work for StackOverflow's domain and subdomain.
Now create some other JavaScript file chosen chief.js in the same directory and add the following lines of code:
var arr =document.getElementsByClassName("southward-lawmaking-block") for(let i = 0 ; i < arr.length ; i++){ var btn = document.createElement("button") btn.classList.add together("copy_code_button") btn.appendChild(certificate.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.mode.left = `${arr[i].offsetWidth - lxx}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.fashion.left = `${arr[i].offsetWidth - 150}px` if(arr[i].scrollHeight === arr[i].offsetHeight) btn.style.bottom = `${arr[i].offsetHeight - 50}px` else btn.style.lesser = `${arr[i].scrollHeight - fifty}px` //end of styling the button console.log("Appended") } Commencement of all, I selected all the elements with the class proper name s-code-cake – but why? This is because when I inspected StackOverflow's site I establish that all the code snippets were kept in a class with that name.
And so we loop through all those elements and append a button in those elements. Finally, nosotros just position and style the push button properly (the styling's not perfect however – this is only a start).
When we load the extension using the process we went through above and visit StackOverflow, nosotros should see a copy button.
How to add functionality to the push button
Now, when the button is clicked nosotros want the entire snippet to be copied to our clip board. To do this, add the following line of code to the main.js file:
var button = document.querySelectorAll(".copy_code_button") button.forEach((elm)=>{ elm.addEventListener('click',(e)=>{ navigator.clipboard.writeText(elm.parentNode.childNodes[0].innerText) alert("Copied to Clipboard") }) }) First of all, we select all the buttons nosotros have added to the site using querySelectorAll. Then nosotros listen for the click effect whenever the button is clicked.
navigator.clipboard.writeText(elm.parentNode.childNodes[0].innerText) The in a higher place line of code copies the code to our clipboard. Whenever a snippet is copied we alert the user with the bulletin Copied to clipboard and we are done.
Final Words
Web Extensions can be useful in various mode and I hope with the aid of this article y'all volition exist able to write your own extensions.
All the code can be found in this GitHub repository. Don't forget to give a pull asking anytime you come with some good styling or a new feature like clipboard history and others.
Happy Coding!
Larn to code for free. freeCodeCamp's open source curriculum has helped more than twoscore,000 people get jobs equally developers. Get started
Source: https://www.freecodecamp.org/news/write-your-own-browser-extensions/
0 Response to "Plugin That Reads Code on a Webpage"
Postar um comentário