Category: Developer

Github

Check Out Atom, GitHub’s New Development Editor

It’s been awhile since we’ve seen any updates in the editor space. The last big splash was made by Sublime Text which took the web development community by storm, especially once Package Control came around to serve as the package manager for the editor.

(more...)

Developer-icon

Useful Sites for Learning How to Code

Computer programming has always maintained an air of mystery, seen by many as a complicated language, understandable to only a select few. However, perceptions are beginning to change, and coding is fast becoming a highly-desirable skill in the job market. As a result, many sites have sprung up on the web, offering tutorials and guides […]

(more...)

Google Chrome

Developing Google Chrome Extensions

It’s no secret that my favorite browser is Google Chrome. I like it because it’s fast, reliable, it doesn’t crash (very often), and it looks good. There’s also something else which I find even more valuable. It’s the fact that you can build an extension for it using only HTML, CSS, and JavaScript. I always support such products, products that are open to the community and Chrome happens to be one of these products. If you need something and it is not yet implemented, you are free to develop it yourself.

So at the end of this article you will find a working Chrome extension which uses most of the techniques explained below. You can download the final example using the download source code button at the top of this page.


Why You Should Write Your Own Extension

I always encourage people to use better tools to speed up their workflow. The software which we use should help us, we should not have to fight with it. Developing extensions/plugins for your favorite editor or browser helps not only you, but also other programmers, who sooner or later will be in the same situation. If something is missing, you can build it yourself and with Chrome this is really easy. Modeling your environment around your needs is key to being highly productive.


Developing & Testing Out Your Extensions

Thankfully there is a way to test your extension without having to upload it to Chrome’s web store. In your browser’s address bar, just type in:

chrome://extensions

Make sure that you check Developer mode and click the Load unpacked extension… button. Then simply select the folder from your hard disk which contains the extension’s files.

extensionspanel

Architecture

Here’s a diagram of the architecture for a Chrome extension:

architecture

And now let’s take a closer look at each element within the architecture.

Manifest

The entry point of your extension is the manifest.json file. It should contain a valid JSON object. For example:

{ "name": "BrowserActionExtension", "version": "0.0.1", "manifest_version": 2, "browser_action": { "default_title": "That's the tool tip", "default_popup": "popup.html" }
}

The required properties are name, version, and manifest_version. The version can be anywhere from one to four, dot-separated integers. It’s something which is used by Google’s autoupdate system. That’s how it knows when to update your extension. The value of the manifest_version should be the integer 2.

The manifest could contain other properties depending on what kind of extension you need, but I’ll describe only those which I find to be more interesting.

Background Pages

Every extension has an invisible background page which is run by the browser. There are two types – persistent background pages and event pages. The first one is active, all of the time. The second is active only when it is needed. Google encourages developers to use event pages, because this saves memory and improves the overall performance of the browser. However, it’s good to know that this is also where you should put your main logic and initialization. Normally the background page/script plays the role of a bridge between the other parts of the extension.

Here is how you should describe it in the manifest:

"background": { "scripts": ["background.js"], "persistent": false/true
}

As you may have guessed, if the persistent property is false then you are using event pages. Otherwise, you are working with a persistent background page.

Content Script

If you need access to the current page’s DOM, then you have to use a content script. The code is run within the context of the current web page, which means that it will be executed with every refresh. To add such a script, use the following syntax.

"content_scripts": [ { "matches": ["http://*/*", "https://*/*"], "js": ["content.js"] }
]

Keep in mind that the value of matches determines for which pages your script will be used. Read more about matches patterns here.

User Interface

There are several ways to build the UI of your extension. Here are the four most popular.

Browser Action

Most developers use the browser_action property to build their plugins. Once you set it, an icon representing your extension will be placed on the right side of the address bar. Users can then click the icon and open a pop-up which is actually HTML content controlled by you.

browseraction

The manifest files should contain the following data:

"browser_action": { "default_icon": { "19": "icons/19x19.png", "38": "icons/38x38.png" }, "default_title": "That's the tool tip", "default_popup": "popup.html"
}

The default_title is a little tool tip which is shown when the user mouses over your icon. default_popup is actually the HTML file which is loaded inside the pop-up. There is also a badge which you can place over your icon. You can do that inside of your background script. For example:

chrome.browserAction.setBadgeText({text: "yeah"});

This was the code which I used to produce the image above.

Page Action

The page_action property is similar to the browser action, but the icon is shown inside the address bar:

pageaction

The interesting thing here is that your icon is hidden initially, so you should decide when to show it. For example, in the image above, the RSS icon will be shown only if the current page contains a link to the RSS feed. If you need to see your icon all the time, it is good to use browser_action directly.

To add the page action, type the following code inside your manifest:

"page_action": { "default_icon": { "19": "images/icon19.png", "38": "images/icon38.png" }, "default_title": "Google Mail", "default_popup": "popup.html"
}

Unlike the browser action’s icon, the page action’s icon doesn’t have badges.

DeveloperTools

I use DeveloperTools a lot and it’s nice that Chrome offers a method for adding new tabs to these tools. The first thing you should do is add an HTML page which will be loaded when the panel is opened:

"devtools_page": "devtools.html"

There’s no need to put any HTML inside the page, except for linking in a JavaScript file, which will create the tab:

<script src="devtools.js"></script>;

And then include the following code inside the devtools.js file:

chrome.devtools.panels.create( "TheNameOfYourExtension", "img/icon16.png", "index.html", function() { }
);

Now the above code will add a new tab with a name of TheNameOfYourExtension and once you click on it the browser will load index.html inside the DeveloperTools.

Omnibox

The omnibox is the keyword which is shown inside Chrome’s address bar. For example, if you add the following property into your manifest:

"omnibox": { "keyword" : "yeah" }

And then add the code below, inside your background script:

chrome.omnibox.onInputChanged.addListener(function(text, suggest) { suggest([ {content: text + " one", description: "the first one"}, {content: text + " number two", description: "the second entry"} ]);
});
chrome.omnibox.onInputEntered.addListener(function(text) { alert('You just typed "' + text + '"');
});

You should be able to type yeah inside the address bar. Then you should see something like this:

omnibox

Pressing tab will produce the following screen:

omnibox2

Of course using the chrome.omnibox API, you could catch the user’s input and react to that input.

APIs

There are bunch of different things which you can do in your extension. For example, you can get access to the user’s bookmarks or history. You can move, create tabs or even resize the main window. I strongly recommend to check out the documentation to get a better idea of how to accomplish these tasks.

What you should know is that not all APIs are available in every part of your extension. For example, your content script can’t access chrome.devtools.panels or the script in your DeveloperTools tab can’t read the page’s DOM. So, if you’re wondering why something is not working, this could be why.

Messaging

As I mentioned above, you don’t always have access to the API that you want to use. If that’s the case, then you should use message passing. There are two types of messaging – one-time requests and long-lived connections.

One-Time Requests

This type of communication happens only once. I.e. you send a message and wait for an answer. For example, you could place the following code in your background script:

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { switch(request.type) { case "dom-loaded": alert(request.data.myProperty); break; } return true;
});

Then use the code from below in your content script:

window.addEventListener("load", function() { chrome.extension.sendMessage({ type: "dom-loaded", data: { myProperty: "value" } });
}, true);

And this is how you can get information about the current page’s DOM and use it inside your background script, which normally doesn’t have access to this data.

Long-Lived Connections

Use this type of messaging if you need a persistent communication channel. Inside your content script place the following code:

var port = chrome.runtime.connect({name: "my-channel"});
port.postMessage({myProperty: "value"});
port.onMessage.addListener(function(msg) { // do some stuff here
});

And then in the background script, use this:

chrome.runtime.onConnect.addListener(function(port) { if(port.name == "my-channel"){ port.onMessage.addListener(function(msg) { // do some stuff here }); }
});

Override Pages

Overriding pages is a nice way to customize your browser. You’re also able to substitute some of the default pages in Chrome. For example you can create your own history page. To do that, add in the following code snippet:

"chrome_url_overrides" : { "<page to override>;": "custom.html"
}

The possible values of <page to override> are bookmarks, history, and newtab. It’s kinda cool to have a fresh new tab page.


An Example Extension

To wrap up this article I decided to include a simple example, so you can get a better understanding of the whole picture. This example extension uses most of the things that I described above to simply set a #F00 background color for all of the divs in the current page. Feel free to download the source code using the button at the top of this article.

The Manifest File

Of course I started with the manifest file:

{ "name": "BrowserExtension", "version": "0.0.1", "manifest_version": 2, "description" : "Description ...", "icons": { "16": "icons/16x16.png", "48": "icons/48x48.png", "128": "icons/128x128.png" }, "omnibox": { "keyword" : "yeah" }, "browser_action": { "default_icon": { "19": "icons/19x19.png", "38": "icons/38x38.png" }, "default_title": "That's the tool tip", "default_popup": "browseraction/popup.html" }, "background": { "scripts": ["background.js"], "persistent": false }, "chrome_url_overrides" : { "newtab": "newtab/newtab.html" }, "content_scripts": [{ "matches": ["http://*/*", "https://*/*"], "js": ["content.js"] }], "devtools_page": "devtools/devtools.html"
}

Keep in mind that you can organize your files into folders. Also, pay attention to the version property. You should update this property every time you want to upload your extension into the web store.

Background Script

// omnibox
chrome.omnibox.onInputChanged.addListener(function(text, suggest) { suggest([ {content: "color-divs", description: "Make everything red"} ]);
});
chrome.omnibox.onInputEntered.addListener(function(text) { if(text == "color-divs") colorDivs();
}); // listening for an event / one-time requests
// coming from the popup
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) { switch(request.type) { case "color-divs": colorDivs(); break; } return true;
}); // listening for an event / long-lived connections
// coming from devtools
chrome.extension.onConnect.addListener(function (port) { port.onMessage.addListener(function (message) { switch(port.name) { case "color-divs-port": colorDivs(); break; } });
}); // send a message to the content script
var colorDivs = function() { chrome.tabs.getSelected(null, function(tab){ chrome.tabs.sendMessage(tab.id, {type: "colors-div", color: "#F00"}); // setting a badge chrome.browserAction.setBadgeText({text: "red!"}); });
}

The first few lines get the user’s action from the omnibox. After that, I set a one-time request listener, which will accept the message from the browser action icon.

The next snippet is a long-lived connection with the devtools tab (it’s not absolutely necessary to use a long-lived connection for this, I did it just for educational purposes). Using these listeners, I’m able to get the input from the user and send it to the content script, which has access to the DOM elements. The key point here was to first select the tab which I wanted to manipulate and then send a message to it. Lastly, I put a badge on the extensions icon.

Browser Action

We start with our popup.html file:

// popup.html
<script type="text/javascript" src="popup.js"></script>
<div style="width:200px"> <button id="button">Color all the divs</button>
</div>

Then we create the popup.js file:

// popup.js
window.onload = function() { document.getElementById("button").onclick = function() { chrome.extension.sendMessage({ type: "color-divs" }); }
}

The pop-up contains a single button and once the user clicks it, it sends a message to the background script.

DeveloperTools

window.onload = function() { var port = chrome.extension.connect({ name: "color-divs-port" }); document.getElementById("button").onclick = function() { port.postMessage({ type: "color-divs"}); }
}

For the DeveloperTools, we’re doing almost the same thing here as we did in the pop-up, the only difference is that I used a long-lived connection.

Content Script

chrome.extension.onMessage.addListener(function(message, sender, sendResponse) { switch(message.type) { case "colors-div": var divs = document.querySelectorAll("div"); if(divs.length === 0) { alert("There are no any divs in the page."); } else { for(var i=0; i&lt;divs.length; i++) { divs[i].style.backgroundColor = message.color; } } break; }
});

The content script listens for a message, selects all the divs on the current page, and changes their background color. Pay attention to the object which I attached the listener to. In the content script that’s chrome.extension.onMessage.

Customizing the New Tab Page

The last thing that this extension does is customize the new tab page. We can do that easily just by pointing the newtab property to the newtab/newtab.html file:

"chrome_url_overrides" : { "newtab": "newtab/newtab.html"
}

Keep in mind that you can’t create a replica of the default new tab page. The idea of this feature is to add in a completely different functionality. Here is what Google says:

Don’t try to emulate the default New Tab page. The APIs necessary to create a slightly modified version of the default New Tab page — with top pages, recently closed pages, tips, a theme background image, and so on — don’t exist yet. Until they do, you’re better off trying to make something completely different.


Debugging

Writing an extension for Google Chrome is not always an easy task and you’ll likely run into some problems. The good thing is that you can still use the console to output your variables to help with debugging. Feel free to add console.log into your background or content scripts. However this will not work in scripts which are run in the context of the developer tools, in that case you might consider using the alert method, as it works everywhere.


Conclusion

In my opinion, Chrome is one of the best browsers available. The developers at Google make creating extensions relatively easy by giving us the power to create them in HTML, CSS, and JavaScript.

Yes, there are some tricky parts, but generally we’re able to produce valuable plugins. Keep in mind that this article doesn’t cover everything related to developing Chrome extensions. There are some other useful things like context menus, options pages, and notifications. For the topics I did not cover, please refer to the documentation for more detailed information.

(more...)

1369686755_Chrome

Chrome’s Request Autocomplete()

Another Google I/O, and another raft of awesome products. One announced API that I’m particularly excited about is requestAutocomplete(), a feature which is landing in Chrome Canary for Windows and Mobile (with OSX support coming shortly). What this API does, in a nutshell, is give you programatic access to autocomplete […]

(more...)

tech

10 Tips for Learning a New Technology

We live in a very exciting time. Never before has education been so cheaply available to the masses (if not free). The medium, itself, has made tectonic shifts from a classroom setting, to blogs, screencasts and complete university classes, as a set of videos and interactive forums. Given these resources, there’s absolutely no excuse not to dive in and learn. However, with such a wealth of resources, filtering through the options can often become overwhelming. In this article, I will outline a simple process to kick-start your education.

Although my suggestions will primarily pertain to software development, these principles are certainly applicable to other fields.


1. Overcoming Inertia

Inertia

Learning something new always begins by first overcoming the inertia to make the first move. This is the same inertia you feel when you want to change the TV channel, but the remote isn't nearby! Thankfully, there are some simple techniques to get excited and motivated. One that has worked really well for me is the concept of Tiny Habits. Rather than becoming overwhelmed by the task at hand, take a tiny step and do something to get started. Using the "get the TV remote" example, start by wiggling your toes, then bend forward, then push yourself away from the couch. Next, try to fall off onto the floor, and finally get up. By following a series of tiny steps, you will overcome your inertia and the task won't seem as overwhelming. This same idea can be applied to learning new skills. It’s all about tiny steps.


2 – Watch the Pros

Pro

The first step, when picking up a new skill, is to determine what to learn. This could be anything you feel passionate about, and have a genuine interest in exploring further. It’s important to have this strong inclination, as it will provide you with the necessary fuel, during those low times. Once you decide what to learn, be it a new programming language, an application framework, or a tool, research inspiring work done by their respective communities. You may find it on YouTube, Vimeo, HackerNews, blogs or even from one of your Twitter friends. Reviewing what others have done will give you confidence that you, too, can do it!


3 – Let the Information Flow Begin

Information Flow

Once you cross the stage of convincing yourself about the thing you want to learn, it’s time that become a sponge, and start absorbing knowledge. Begin with some Google searching on "beginner tutorials" related to your topic. As you know, Nettuts+ offers hundreds upon hundreds of tutorials. Check here as well. StackOverflow is one place where you will surely find links to a plethora of resources. Alternatively, Quora is an excellent place to search for answers. Once you sift through these links, you may wish to take a more concentrated dose by looking for the best books on the topic. Personally I refer to Amazon for hunting down highly rated books.


4 – Listen and Watch

Watch

As you delve deeper into the pool of knowledge, you will want to add other forms of information – namely, podcasts and screencasts. I encourage you to browse through iTunesU, which offers complete classes on a variety of topics from some of the best institutions in the world. This is particularly helpful for those who prefer an academic setting.

These days, there are a handful of websites that offers online education. Look no further than our very own Tuts+ Premium. Hoping to learn PHP or JavaScript? There’s no better resource on the web. Alternatively, you might consider:

You can also watch conference presentations, such as Google IO on YouTube, or Confreaks for free!


5 – Time for Action

Action

The best way to learn is by doing.

Okay, you’ve read countless tutorials, watched videos, and have a better understanding of the technology that you’ve been hoping to learn. What now? Well, it’s time to put your knowledge to the test. Ultimately, the best way to learn is by doing.

Pick a personal project that you can build using this new technology. Design some simple features and implement them. You will most definitely hit some stumbling blocks. When this happens, research the solution on StackOverflow or Google. You are now on a journey to become an expert in that technology. The more failures and road blocks you encounter, the wiser you will be. There is a saying that "the experts are ones who have made the most mistakes." It means they’ve tried crazy things and pushed the limits of a technology. As a result, they’ve acquired an intimate understanding of how it works. With such insight, they are able to bend the tech to their will and wield Jedi powers (for good, of course).

These powers are also within your reach.


6 – Blogging

Blogging

As you embark on your journey, it’s helpful to chronicle the steps (or missteps) you took along the way. Blogs are easily the most popular form of expression in the tech community. It’s part of our DNA. When you put a pen to your learnings, you’re forcing yourself to become more cohesive in your thoughts, bringing some structure into the dispersed pieces of knowledge that you have accumulated. Who knows, in the process, you just might be educating someone else on the Internet. Pay it forward when you can.

If you’d like to take things a step further (as writers do every day here on Nettuts+), can take this a step further and create screencasts, which is preferred by most visual learners. Overall, blogging helps you build your communication skills, which is as important as the technology you are learning.


7 – Feel the Pulse

Pulse

Technology matures when people do crazy and sometimes unthinkable things.

Social Networks have become a universal way of staying in touch and discovering new things. Twitter and Facebook are the primary suspects for information, but there are more focused websites, like the previously mentioned Quora, that have a wide-ranging set of topics, which people may vote and comment on. It’s a great place to find answers and opinions from well-known individuals with real-life experiences. In fact, a quick search on Quora for other perspectives on learning, reveals an interesting set of results.

Scanning the ever-growing set of questions on StackOverflow can also be a fun way to review the way in which others are pushing the limits of a particular technology. In fact, technology matures when people do crazy and sometimes unthinkable things with it.

If you want to feel the pulse of a technology, and determine whether it’s worth learning, try a search on StackOverflow to see the breadth and depth of the community. The Most Voted, Featured questions are excellent candidates for this sort of exploration. You can also carry out a similar exploration on GitHub.


8 – Meetups and Conferences

Meetup

Although social networks are great, nothing can substitute real human connection. It is quite likely that you have a Meetup group in a place near you, where you’ll find several like-minded folks. You will learn about interesting projects that others are working on, while also getting some of your tricky problems solved!. On a related note, conferences, too, are a great place to share experiences and enrich your already growing skill-set.


9 – GitHub

Octocat

GitHub is the iconic landmark for the world of open-source projects. It’s a treasure trove of knowledge and creativity, expressed in the form of code. Once you feel comfortable with a particular technology, your next step should be to explore GitHub to find interesting projects. Read the source code. Read as much as you can. In doing so, you can learn a variety of things, such as:

  • How to organize large projects
  • Interesting libraries that projects are using
  • Code patterns and overall design
  • Documentation style
  • Testing patterns
  • Solutions to odd issues, pointed out in the Issues section of the project

All of this knowledge is just waiting to be devoured. Interestingly, and to your benefit, it only comes with a simple price tag: curiosity.


10 – Concentrated Learning

Dose

If you worry that the process outlined above is too slow, you might also try a fast-track approach. You may have heard about the "Learn X in 24 hours", but that is not what I am referring to. A more pragmatic time-line is probably a few weeks. If that seems reasonable, you can try something like Seven Languages in Seven Weeks or Seven Databases in Seven Weeks. Although these books refer to languages and databases, you could do the same with other technologies.

A slightly different style would be to learn things the "hard way". The idea here is to accept upfront that nobody can master a skill unless it is practiced daily. So to gain expertise, you practice by working through countless exercises. In a similar vein, you also have Katas and Koans, that encourage solving problems in the language of your choice. These will introduce you to concepts and techniques that may initially be alien to you. That’s the point! If you really want to displace yourself from your comfort zone, give them a shot!


Learn an Orthogonal Skill

Your right-brain processes information in a very different fashion.

Programming is primarily a left-brain activity. It leverages the analytical part of the brain that looks for a step-by-step approach to solving problems. To appreciate the power of the right-brain, take up a creative activity, such as painting, 3D-modeling, origami, playing an instrument, or even building photo books out of your family albums. In fact, programming requires a great deal of creativity. You might have already experienced this, if you’ve ever found solutions to obtuse problems in your sleep. This is because your right-brain processes information in a very different fashion, and can compile ideas from all over the place. Andy Hunt, from the pragmatic bookshelf, wrote a book on this topic: Pragmatic Thinking and Learning: Refactor Your Wetware. If you want to be firing on all synapses, pick up a skill orthogonal to what you already do.


Summary

Acquiring a new skill is always exciting. It’s the start of a new experience that will shape your thinking. But first, you must overcome your inertia. Once you do, your journey to absorb knowledge from every facet of the web begins. I hope that the process outlined above has given you some ideas for approaching this long road.

If you have a different approach to learning, I’d love to learn more about it. Feel free to leave a comment, while I leave you with these inspiring links:

(more...)