A Walk Through on Chrome Extensions

What are extensions?

Extensions are small software programs that customize the browsing experience. They enable  users to tailor Chrome functionality and behavior to individual needs or preferences. They are built on web technologies such as HTML, JavaScript, and CSS.

An extension must fulfill a single purpose that is narrowly defined and easy to understand. A single extension can include multiple components and a range of functionality, as long as everything contributes towards a common purpose.

User interfaces should be minimal and have intent. They can range from simple icon, such as the Google Mail Checker Extension shown on the right, to overriding an entire page.

Extension files are zipped into a single .crx package that the user downloads and installs. This means extensions do not depend on content from the web, unlike ordinary web apps.

Extensions are distributed through the and Chrome Developer Dashboard published to the Chrome Web Store. For more information, see the store developer documentation.

Install and manage extensions

You can customize Chrome and add features and functionality by adding extensions from the Chrome Web Store.

Install an extension

  1. Open the Chrome Web Store.
  2. Find and select the extension you want.
  3. Click Add to Chrome.
  4. Some extensions will let you know if they need certain permissions or data. To approve, click Add extension.

To use the extension, click the icon to the right of the address bar.

If you’re using a computer through your work or school, your organization might block some extensions.

Uninstall an extension

To the right of your address bar, look for the extension’s icon. Right-click the icon and select Remove from Chrome.

If you don’t see the extension’s icon:

  1. On your computer, open Chrome.
  2. At the top right, click More Moreand thenMoretoolsand thenExtensions.
  3. On to the extension you want to remove, click Remove.
  4. Confirm by clicking Remove.

Manage your extensions

  1. On your computer, open Chrome.
  2. At the top right, click More Moreand thenMoretoolsand thenExtensions.
  3. Make your changes:
    • Turn on/off: Turn the extension on or off.
    • Allow incognito: On the extension, click Details. Turn on Allow in incognito.
    • Fix corruptions: Find a corrupted extension and click Repair. Confirm by clicking Repair extension.

Getting Started Tutorial

Extensions are made of different, but cohesive, components. Components can include background scripts, content scripts, an options page, UI elements and various logic files. Extension components are created with web development technologies: HTML, CSS, and JavaScript. An extension’s components will depend on its functionality and may not require every option.

This tutorial will build an extension that allows the user to change the background color of any page on developer.chrome.com.  It will use many core components to give an introductory demonstration of their relationships.

To start, create a new directory to hold the extension’s files.

Extensions start with their manifest.  Create a file called manifest.json and include the following code,

{
    "name": "Getting Started Example",
    "version": "1.0",
    "description": "Build an Extension!",
    "manifest_version": 2
  }

The directory holding the manifest file can be added as an extension in developer mode in its current state.

  1. Open the Extension Management page by navigating to chrome://extensions.
    • The Extension Management page can also be opened by clicking on the Chrome menu, hovering over More Tools then selecting Extensions.
  2. Enable Developer Mode by clicking the toggle switch next to Developer mode.
  3. Click the LOAD UNPACKED button and select the extension directory.

Load Extension

Ta-da! The extension has been successfully installed. Because no icons were included in the manifest, a generic toolbar icon will be created for the extension.

Although the extension has been installed, it has no instruction. Introduce a background script  by creating a file titled background.js, and placing it inside the extension directory.

Background scripts, and many other important components, must be registered in the manifest. Registering a background script in the manifest tells the extension which file to reference, and how that file should behave.

{
    "name": "Getting Started Example",
    "version": "1.0",
    "description": "Build an Extension!","background": {"scripts": ["background.js"],"persistent": false},"manifest_version": 2
  }

The extension is now aware that it includes a non-persistent background script and will scan the registered file for important events it needs to listen for.

This extension will need information from a persistent variable as soon as its installed. Start by including a listening event for runtime.onInstalled in the background script. Inside the onInstalled listener, the extension will set a value using the storage  API. This will allow multiple extension components to access that value and update it.

  chrome.runtime.onInstalled.addListener(function() {
    chrome.storage.sync.set({color: '#3aa757'}, function() {
      console.log("The color is green.");
    });
  });

Most APIs, including the storage API, must be registered under the "permissions" field in the manifest for the extension to use them.

{
    "name": "Getting Started Example",
    "version": "1.0",
    "description": "Build an Extension!","permissions": ["storage"],"background": {
      "scripts": ["background.js"],
      "persistent": false
    },
    "manifest_version": 2
  }

Navigate back to the extension management page and click the Reload link. A new field, Inspect views, becomes available with a blue link, background page.

Inspect Views

Click the link to view the background script’s console log, “The color is green.

Extensions can have many forms of a user interface, but this one will use a popup. Create and add a file titled popup.html to the directory. This extension uses a button to change the background color.

<!DOCTYPE html>
  <html>
    <head>
      <style>
        button {
          height: 30px;
          width: 30px;
          outline: none;
        }
      </style>
    </head>
    <body><button id="changeColor"></button></body>
  </html>

Like the background script, this file needs to be designated as a popup in the manifest under page_action.

{
    "name": "Getting Started Example",
    "version": "1.0",
    "description": "Build an Extension!",
    "permissions": ["storage"],
    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },"page_action": {"default_popup": "popup.html",},"manifest_version": 2
  }

Designation for toolbar icons is also included under page_action in the default_icons field. Download the images folder here, unzip it, and place it in the extension’s directory. Update the manifest so the extension knows how to use the images.

{
    "name": "Getting Started Example",
    "version": "1.0",
    "description": "Build an Extension!",
    "permissions": ["storage"],
    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },
    "page_action": {
      "default_popup": "popup.html","default_icon": {"16": "images/get_started16.png","32": "images/get_started32.png","48": "images/get_started48.png","128": "images/get_started128.png"}},
    "manifest_version": 2
  }

Extensions also display images on the extension management page, the permissions warning, and favicon. These images are designated in the manifest under icons.

{
    "name": "Getting Started Example",
    "version": "1.0",
    "description": "Build an Extension!",
    "permissions": ["storage"],
    "background": {
      "scripts": ["background.js"],
      "persistent": false
    },
    "page_action": {
      "default_popup": "popup.html",
      "default_icon": {
        "16": "images/get_started16.png",
        "32": "images/get_started32.png",
        "48": "images/get_started48.png",
        "128": "images/get_started128.png"
      }
    },"icons": {"16": "images/get_started16.png","32": "images/get_started32.png","48": "images/get_started48.png","128": "images/get_started128.png"},"manifest_version": 2
  }

If the extension is reloaded at this stage, it will include a grey-scale icon, but will not contain any functionality differences. Because page_action is declared in the manifest, it is up to the extension to tell the browser when the user can interact with popup.html.

Add declared rules to the background script with the declarativeContent API within theruntime.onInstalled listener event.

  chrome.runtime.onInstalled.addListener(function() {
    chrome.storage.sync.set({color: '#3aa757'}, function() {
      console.log('The color is green.');
    });chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {chrome.declarativeContent.onPageChanged.addRules([{conditions: [new chrome.declarativeContent.PageStateMatcher({pageUrl: {hostEquals: 'developer.chrome.com'},})],actions: [new chrome.declarativeContent.ShowPageAction()]}]);});});

The extension will need permission to access the declarativeContent API in its manifest.

{
    "name": "Getting Started Example",
  ...
    "permissions": ["declarativeContent", "storage"],
  ...
  }

Popup

The browser will now show a full-color page action icon in the browser toolbar when users navigate to a URL that contains "developer.chrome.com". When the icon is full-color, users can click it to view popup.html.

The last step for the popup UI is adding color to the button. Create and add a file called popup.jswith the following code to the extension directory, or downloaded here.

  let changeColor = document.getElementById('changeColor');

  chrome.storage.sync.get('color', function(data) {
    changeColor.style.backgroundColor = data.color;
    changeColor.setAttribute('value', data.color);
  });

This code grabs the button from popup.html and requests the color value from storage. It then applies the color as the background of the button. Include a script tag to popup.js in popup.html.

<!DOCTYPE html>
<html>
...
  <body>
    <button id="changeColor"></button><script src="popup.js"></script></body>
</html>

Reload the extension to view the green button.

The extension now knows the popup should be available to users on developer.chrome.com and displays a colored button, but needs logic for further user interaction. Update popup.js to include the following code.

  let changeColor = document.getElementById('changeColor');
  ...changeColor.onclick = function(element) {let color = element.target.value;chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {chrome.tabs.executeScript(tabs[0].id,{code: 'document.body.style.backgroundColor = "' + color + '";'});});};

The updated code adds an onclick event the button, which triggers a programatically injected content script. This turns the background color of the page the same color as the button. Using programmatic injection allows for user-invoked content scripts, instead of auto inserting unwanted code into web pages.

The manifest will need the activeTab permission to allow the extension temporary access to the tabs API. This enables the extension to call tabs.executeScript.

{
    "name": "Getting Started Example",
  ...
    "permissions": ["activeTab", "declarativeContent", "storage"],
  ...
  }

The extension is now fully functional! Reload the extension, refresh this page, open the popup and click the button to turn it green! However, some users may want to change the background to a different color.

The extension currently only allows users to change the background to green. Including an options page gives users more control over the extension’s functionality, further customizing their browsing experience.

Start by creating a file in the directory called options.html and include the following code.

<!DOCTYPE html>
  <html>
    <head>
      <style>
        button {
          height: 30px;
          width: 30px;
          outline: none;
          margin: 10px;
        }
      </style>
    </head>
    <body>
      <div id="buttonDiv">
      </div>
      <div>
        <p>Choose a different background color!</p>
      </div>
    </body>
    <script src="options.js"></script>
  </html>

Then register the options page in the manifest,

{
    "name": "Getting Started Example",
    ..."options_page": "options.html",...
    "manifest_version": 2
  }

Reload the extension and click DETAILS.

Inspect Views

Scroll down the details page and select Extension options to view the options page, although it will currently appear blank.

Inspect Views

Last step is to add the options logic. Create a file called options.js in the extension directory with the following code.

  let page = document.getElementById('buttonDiv');
  const kButtonColors = ['#3aa757', '#e8453c', '#f9bb2d', '#4688f1'];
  function constructOptions(kButtonColors) {
    for (let item of kButtonColors) {
      let button = document.createElement('button');
      button.style.backgroundColor = item;
      button.addEventListener('click', function() {
        chrome.storage.sync.set({color: item}, function() {
          console.log('color is ' + item);
        })
      });
      page.appendChild(button);
    }
  }
  constructOptions(kButtonColors);

Four color options are provided then generated as buttons on the options page with onclick event listeners. When the user clicks a button, it updates the color value in the extension’s global storage. Since all of the extension’s files pull the color information from global storage no other values need to be updated.

Congratulations! The directory now holds a fully-functional, albeit simplistic, Chrome extension.

What’s next?

  • The Chrome Extension Overview backs up a bit, and fills in a lot of detail about the Extensions architecture in general, and some specific concepts developers will want to be familiar with.
  • Learn about the options available for debugging Extensions in the debugging tutorial.
  • Chrome Extensions have access to powerful APIs above and beyond what’s available on the open web. The chrome.* APIs documentation walk through each API.
  • The developer’s guide  has dozens of additional links to pieces of documentation relevant to advanced extension creation.

Web Store Hosting and Updating

Most extensions are hosted in the Chrome Web Store to best protect users from malicious extensions.

All extensions are distributed to users as a special ZIP file with a .crx suffix. Extensions hosted in the Chrome Web Store are uploaded through the Developer Dashboard as .zip files. The publishing process automatically converts the .zip into a .crx file.

There are three exceptions to the Chrome Web Store hosting rule:

  1. Extensions that are distributed through the enterprise policy.
  2. Unpacked extension directories from a local machine while in developer mode.
  3. Linux Installation.

The Chrome Browser periodically checks for new versions of installed extensions and updates them without user intervention.

To release an update to an extension, increase the number in the “version” field of the manifest.

{
    ..."version": "1.5",...
    }
  }
{
    ..."version": "1.6",...
    }
  }

Convert the updated extension directory into a ZIP file and locate the old version in the Developer Dashboard. Select Edit, upload the new package, and hit Publish. The browser will will automatically update the extension for users after the new version is published.

The snapshots below gives the overview of DC-Extractinator extension:

 

Note: Some of the extensions like Email Extractor charge $9.99 a month for 5000 Email Id’s of extraction, which has successfully been realized in our project DC-YoHo. [PROOF link https://www.email-extractor.io/extension/autosave/token/30de58a772e55c8bf92bec5d589b5084372e5a1b3933aa9ea077fb206686cf48 ].

 

 

 

 

 

 

Git working with branches

List all branches:

git branch -a

Create a local branch

git checkout -b dc-server-modification

switch to master after creating branch

git checkout master

switch to branch

git checkout dc-server-modification

Create a remote branch under origin/master

git branch -t dc-server-modification origin/master

Checkout locally remote branch

git checkout -b dc-server-modification

Push to remote branch

How do you merge your changes performed on the branch with the master, while you are there on the branch?
git branch -a : “check the branch on which you are on”
git checkout dc-server-bug-fixes : “checkout the branch”
//Make changes
git add -A && git commit -m “bug fixes”
git status : “check up to date”
git rebase master : Rebase on master happens
git checkout master
git merge dc-server-bug-fixes: “merges all changes master”
git push -u origin master

The following steps might help anyone who are new to git rebase and wanted to do it without hassle

Step 1: Assuming that there are no commits and changes to be made on YourBranch at this point. We are visiting YourBranch.

git checkout YourBranch
git pull –rebase
What happened? Pulls all changes made by other developers working on your branch and rebases your changes on top of it.

Step 2: Resolve any conflicts that presents.

Step 3:

git checkout master
git pull –rebase
What happened? Pulls all the latest changes from master and rebases master on latest master.

Step 4: Resolve any conflicts that presents.

Step 5:

git checkout YourBranch
git rebase master
What happened? Rebase on master happens

Step 6: Resolve any conflicts, if there are conflicts. Use git rebase –continue to continue rebase after adding the resolved conflicts. At any time you can use git rebase –abort to abort the rebase.

Step 7:

git push –force-with-lease
What happened? Pushing changes to your remote YourBranch. –force-with-lease will make sure whether there are any other incoming changes for YourBranch from other developers while you rebasing. This is super useful rather than force push. In case any incoming changes then fetch them to update your local YourBranch before pushing changes.

Why do I need to push changes? To rewrite the commit message in remote YourBranch after proper rebase or If there are any conflicts resolved? Then you need to push the changes you resolved in local repo to the remote repo of YourBranch

Yahoooo…! You are succesfully done with rebasing.

You might also be looking into doing:

git checkout master
git merge YourBranch : “merges the branch with your master”
git push -u origin master : “pushes to master”

The 92% chunk asset optimisation problem nodejs Angular5

At times running Angular Application on an environment which is fresh can be daunting. We may end up with errors which are not in alignment towards the development. One such of a case is the 92% chunk asset optimization problem when running a build of the Angular application.

On AWS hooked up an ec2-instance with Ubuntu 16.04, every thing works fine until you run the command npm run build.

We are stuck in an exception, 92% chunk asset optimisation and the dist directory is not created. Though we end up looking information on the development stack, but at times it could also be related to the Operating System SWAP space.

If the SWAP space on the OS if short or not available, this error shows up and to go around the error follow the instructions to check and allocate swap space on ubuntu. Hopefully this should help in getting around the problem.

One of the easiest way of increasing the responsiveness of your server and guarding against out of memory errors in your applications is to add some swap space. Swap is an area on a hard drive that has been designated as a place where the operating system can temporarily store data that it can no longer hold in RAM.

Basically, this gives you the ability to increase the amount of information that your server can keep in its working “memory”, with some caveats. The space on the hard drive will be used mainly when space in RAM is no longer sufficient for data.

The information written to disk will be slower than information kept in RAM, but the operating system will prefer to keep running application data in memory and use swap for the older data. Overall, having swap space as a fall back for when your system’s RAM is depleted is a good safety net.

sudo swapon -s

Another command for the same thing

free -m

Before we do this, we should be aware of our current disk usage. We can get this information by typing:

df -h

Although there are many opinions about the appropriate size of a swap space, it really depends on your personal preferences and your application requirements. Generally, an amount equal to or double the amount of RAM on your system is a good starting point.

Since my system has 4 Gigabytes of RAM, and doubling that would take a significant chunk of my disk space that I’m not willing to part with, I will create a swap space of 4 Gigabytes to match my system’s RAM.

Creating SWAP File
sudo fallocate -l 4G /swapfile
Check by running the following command that the SWAP file was created and space was reserved
ls -lh /swapfile
Enable SWAP Fiile
sudo mkswap /swapfile
Verfiy Permissions are set correctly
ls -lh /swapfile
Now that our file is more secure, we can tell our system to set up the swap space by typing:
sudo swapon /swapfile

We can verify that the procedure was successful by checking whether our system reports swap space now:

sudo swapon -s
Filename                Type        Size    Used    Priority
/swapfile               file        4194300 0       -1

We have a new swap file here. We can use the free utility again to corroborate our findings:

free -m

https://www.digitalocean.com/community/tutorials/how-to-add-swap-on-ubuntu-14-04

———————Setting up Angular Environment Using NVM———————-

Requirements:
1.nodejs.
2.@angular/cli.

Procedure:
1.Install NVM (Node Version Manager):
By far the easiest way to install node.
run commad :
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh | bash

-This installs NVM, use command ‘nvm -v’ to check if it is installed.

Note: Re-open Terminal after install ‘nvm'(if ‘nvm -v’ doesn’t work).

2.run command:
nvm install node

-This installs the latest version of node

To install a specific version of node use:
nvm install <version>
ex:
nvm install 6.11.5
(Installs version 6.11.5)

3.Install Angular CLI(Command Line Interface)
run:
npm install -g @angular/cli

To check run:
ng

Install pm2 (For running on Server. Skip this step if you are doing local setup):

npm install pm2 -g

—–AND YOU ARE GOOD TO GO

git fails with command: Failed to connect to xxx-xxx-xx-xx port xxxx: Connection refused

 

user@Sys154:~/projects/hipl$ git clone https://gitlab.com/test/test-server.git
Cloning into ‘test-server’…
fatal: unable to access ‘https://gitlab.com/test/test-server.git/’: Failed to connect to 163.172.110.218 port 2465: Connection refused

This happens because a proxy is configured in git.

Since it’s https proxy (and not http) git config http.proxy and git config --global http.proxy can’t help.

1 : take a look at your git configuration

git config --global -l

If you have nothing related to https proxy like https_proxy=... the problem is not here.

If you have something related to https proxy then remove it from the file ~/.gitconfig and try again

2 : if it still doesn’t work, unset environment variables

Check your environment variables :

env|grep -i proxy  

You should have one or several lines with https_proxy=...

Unset one by one with : unset https_proxy (or HTTPS_PROXY depending of the name of the variable)

3 : check environment variables again

env|grep -i proxy

If it shows nothing you should be good.

Note : This solution can applies to http and https proxy problems. just the variables name changes from https to http

Postfix Logging

Thanks to http://david.schweikert.ch/, a small but powerful utility to give insights on your postfix mail server

Mailgraph is postfix logging tool. Install mailgraph

For ubuntu follow the steps

sudo apt-get install rrdtool mailgraph

dpkg-reconfigure mailgraph

During the installation, the system startup links for Mailgraph are created automatically, and Mailgraph also gets started automatically, so we don’t need to start it manually.

Mailgraph is now accessible trough the hostname or IP of your server. Open a web Browser and enter the URL http://192.168.1.100/cgi-bin/mailgraph.cgi or http://server1.example.com/cgi-bin/mailgraph.cgi, and you should see some graphs. Of course, there must be some emails going through your system before you see the first results, so be patient.

 

On Centos 7

yum install rrdtool mailgraph

yum –enablerepo=epel -y install mailgraph
edit the mailgraph configuration
vi /etc/httpd/conf.d/mailgraph.conf
Alias /mailgraph /usr/share/mailgraph
AddHandler cgi-script .cgi
<Directory /usr/share/mailgraph/>
AllowOverride None
Options +ExecCGI
DirectoryIndex mailgraph.cgi
   Order Deny,Allow
Deny from all
Allow from all

# add IP address you permit to access

</Directory>

Start mailgraph
/etc/rc.d/init.d/mailgraph start

 

restart httpd service
/etc/rc.d/init.d/httpd restart

mailgraph

mailgraph

Where are packages installed in Ubuntu : Debian Derivatives

Ubuntu, which is a Debian derivative, follows a very precise structure when installing packages. In other words, all software installed through the packaging tools, such as apt-get or synaptic, will put the stuff in the same locations. If you become familiar with these locations, you’ll always know where to find your stuff.

As a short cut, you can always open a tool like synaptic, find the installed package, and inspect the “properties”. Under properties, you’ll see a list of all installed files. Again, you can expect these to always follow the Debian/Ubuntu conventions; these are highly ordered Linux distributions. IN short, binaries will be in /usr/bin, or some other location on your path ( try ‘echo $PATH’ on the command line to see the possible locations ). Configuration is always in a subdirectory of /etc. And the “home” is typically in /usr/lib or /usr/share.

For instance installing maven,

sudo apt-get install maven

The Apt-get installation will install all the required files in the following folder structure

/usr/bin/mvn

/usr/share/maven2/

/etc/maven2

P.S The Maven configuration is store in /etc/maven2

Note, it’s not just apt-get that will do this, it’s any .deb package installer.

How does Play Framework manage hot reloading?

It’s not really Play managing the hot reloading but rather the Play SBT plugin.

A Play application’s main method is in play.core.server.NettyServer. The method receives a reloader of type SBTLink and each time a request hits the server, the application delegates the task of checking if there have been any code changes to the reloader.

If there has been a code change then the existing classloader is removed and replaced with a new one which includes the updated bytecode. The application is restarted but, of course, the JVM is not.

Play is not designed to provision dynamic swapping of Jars at runtime. For this, you would need to look at things like OSGi (which I would not personally recommend after a few years of working with it).