Posts tagged Chrome

Cómo crear una extensión de Chrome

Les comparto una presentación de cómo hacer una extensión para Chrome. Esta presentación la usé para un taller que di originalmente en el Día ISC del Tec CEM el 7 de abril de 2010 y luego de nuevo en FLISoL Toluca el 24 de abril de 2010.

Puedes descargar los assets del taller, incluyendo la versión PPTX de la presentación y todo el código separado en versiones. El producto final del taller, una extensión de lista de tareas, lo puedes encontrar en la Galería de Extensiones. El código del taller está bajo el GPLv2.

Presentación: Extensiones de Chrome

Aquí está la presentación que di este sábado en la reunión del Google Technology Users Group (GTUG) de México.

New versions of Postponer and ChromeMilk released

screen-gmailI’ve released new versions of my Chrome extensions Postponer and ChromeMilk.

Postponer 0.4 add a one-click add mode to Adder and customizable popup size to Manager, as well as a few bug fixes.

ChromeMilk 0.9.6 features a brand new icon as well as numerous bug fixes.

As always, you can get them from the Chrome extensions gallery:

Postponer Adder

Postponer Manager

ChromeMilk

Thanks to everyone that reported bugs, and a special thanks to Camila González for the new icon in ChromeMilk.

Please let me know of any bugs, issues, feature requests or just general comments you may have. Enjoy the extensions!

What is a browser?

I just remembered this video today. It’s a great look at what people think a browser is. It’s incredible how many people confuse a browser with a search engine.

Now that the browser ballot has come into effect in the EU, will this lead people to be more educated about what a browser is? The browser ballot page has no information as to what a browser is and what it is for. As the video shows, many people are ignorant on the subject. Choosing a good browser is not something easy for those that have no idea what this is.

What would you do to increase awareness on web browsers and other important Internet technologies most users ignore?

My Opera Rant

image

Oh, Opera… You are the browser that standardized tabbed browsing, new tab pages, browser synching, and so many more innovative features. You are one of the fastest and most standards-compliant browsers. You are the browser that pushes development of other browsers forward. Yet you can barely break 2% market adoption. Why is that? Why, for a browser first launched 8 years before Firefox and only one year after Internet Explorer?

Opera, you don’t need to sue Microsoft to gain market share. Firefox, a browser just 6 years old, has reached 20+%. Chrome, which is less than two years old, is pushing on 6%. You might say, “But Google has funds for marketing!” But what about Mozilla? Firefox is the second largest browser, and it is made and managed by a company a third of the size of Opera Software.

Opera, your desktop business model doesn’t work. If you need the EU to force users into changing browsers so you can gain market share, you’re doing it wrong. You need to expand your user base not only by creating great new features, which you do all the time, but also by advertising them. Your main weakness, Opera, is that nobody knows about you.

On its launch day, Firefox posted a full-page ad in the New York Times. Both Chrome and Firefox have launched TV and viral ad campaigns like Spread Firefox and Firefox Flicks. Google has advertised Chrome in its most prominent products like YouTube.

Firefox arrived at a time when everybody was starting to get sick of IE. You never took advantage of that. Chrome arrived at a time when everybody was starting to get sick of Firefox. You didn’t take advantage of that either. Yet, when the EU says that Microsoft has to do advertising for you, you quickly whip up a shiny new version and thank the EU for tripling your downloads.

I’m disappointed, Opera, that such a good browser has such a little market share because you refuse to do real advertising. Let’s hope this new surge is market share the browser ballot might bring will change the way you look at the market and your users.

New version of Postponer, now with Google Reader integration!

PostponerAdderGreaderScreen

I’ve released a new version of Postponer, my Google Chrome extensions for managing your Read It Later reading list. The best new feature is Google Reader integration. Now an icon will appear next to article titles so you can add the article directly to your reading list, similar to the official Firefox extension.

The Google Reader icon is fully customizable and you can modify its behavior in the new Postponer Adder options page.

You can get Postponer at its project page. As always, feedback is well received; if you find a bug or want a new feature, please report it.

image

Help me translate ChromeMilk and Postponer

Internationalization

 Image by Beekman

Google has sent me an email asking me to translate my extensions using the new Chrome Extensions i18n API. I’m only fluent in English and Spanish, but I want the whole world to enjoy my extensions. If you know any of the languages supported by Chrome and would like to help me translate, please let me know. You can read the documentation and take a look at the source code for ChromeMilk and Postponer. I’ll be providing two translations (English and Spanish) soon.

Update

I’ve set up wiki pages for ChromeMilk and Postponer with the links to the people who have volunteered to translate.

How to build a Chrome extension, Part 4: Background pages and scheduling requests

One of the most common uses for an extension is as a notifier. For example, the Google Gmail Checker, an official Google extension and the most popular one in the gallery, constantly checks your Gmail inbox for new unread mail.

This functionality is easy to add into your own extension. You need to add a background page, which is easily added by adding the background_page option to your manifest.json:

{
	"name": "My Extension",
	...
	"background_page": "background.html",
	...
}

Like almost every other component in a Chrome extension, background.html is a standard HTML file. However, it can also do things most web pages cannot, such as cross-origin requests if permissions are correctly added to the manifest. For example, if your extension is a Gmail checker, it would need permissions to http://www.google.com and https://www.google.com. To add these permissions, the manifest.json would be edited to:

{
	"name": "My Extension",
	...
	"background_page": "background.html",
	"permissions": ["http://www.google.com/", "https://www.google.com/"],
	...
}

A background page runs at all times when the extension is enabled. You cannot see it, but it can modify other aspects of the extension, like setting the browser action badge. For example, the following example would set the icon badge to the number of unread items in a hypothetical service:

function getUnreadItems(callback) {
	$.ajax(..., function(data) {
		process(data);
		callback(data);
	});
}

function updateBadge() {
	getUnreadItems(function(data) {
		chrome.browserAction.setBadgeText({text:data.unreadItems});
	});
}

So now you can make a request, but how can you schedule it so the data is retrieved and processed regularly? Luckily, JavaScript has a method called window.setTimeout to do just that:

var pollInterval = 1000 * 60; // 1 minute, in milliseconds

function startRequest() {
	updateBadge();
	window.setTimeout(startRequest, pollInterval);
}

That was easy! Now just slap a

onload='startRequest()'

on the background page’s body tag and that should do it!

But what if you want to stop the request? That can easily be done as well, by chaging the startRequest function a little and adding a stopRequest function:

var pollInterval = 1000 * 60; // 1 minute, in milliseconds
var timerId;

function startRequest() {
	updateBadge();
	timerId = window.setTimeout(startRequest, pollInterval);
}

function stopRequest() {
	window.clearTimeout(timerId);
}

And that’s about it on building background pages that can schedule requests. Now go! Make an awesome notifier! You can even make things like a timer with this (Facebook addiction control, anyone?). Just remember to leave a comment telling everyone of your awesomeness.

How to build a Chrome extension, Part 3: Loading any web page in a popup

Chrome allows extensions that use its page action or browser action API to show popups when clicked. To add this popup, you’d add a popup.html file to your extension and the following to the manifest.json for browser actions:

{
	"name": "My Extension",
	...
	"browser_action": {
		"default_icon": "myicon.png",
		"popup": "popup.html"
	}
	...
}

Or for page actions:

{
	"name": "My Extension",
	...
	"page_action": {
		"default_icon": "myicon.png",
		"popup": "popup.html"
	}
	...
}

However, the popup page is static and cannot be changed while the extension is running. Also, only a local extension page can be put into a popup; you can’t load an external page.

So how can you fix this? Using a relatively old web technique called an iframe. Inline frame, or iframe, is an HTML element that can load any web page inside another in a type of box. So, even though you can’t load an external web page as your popup, you can load it within it.

A simple example for a Bing search extension would be:

<html>
<head>
	<style type="text/css">
	body {width:200; height:300;}
	</style>
</head>
<body>
	<iframe src="http://m.bing.com" width="100%" height="100%" frameborder="0">
	</iframe>
</body>
</html>

As you can see, I have loaded the mobile version of Bing, http://m.bing.com. Because of the small amount of screen real estate available on the popups, loading mobile versions of a page is a good idea as they are minimalistic and require less space.

I’ve also explicitly declared the size of the page (200 by 300) and the iframe (100% of the page). You can change this to what fits your extension best.

(Yeah, I know it is ironic to build a Chrome extension centered on Bing, but I couldn’t get Google’s mobile search to load correctly in an iframe.)

On Chrome, the Bing search extension would look like this:

image

You can download the completed Bing extension from the Chrome Extensions Gallery and the source code (under the GPLv2) from Mediafire.

Now, what if you want to load a different page depending on an extension option? You can easily do this by constructing the iframe element dynamically when the page loads, like this code excerpt from ChromeMilk:

$(document).ready(function() {
	var popup = localStorage.popup || 'igoogle';

	var frame = document.createElement('iframe');

	frame.setAttribute('width', '100%');
	frame.setAttribute('height', '100%');
	frame.setAttribute('frameborder', '0');
	frame.setAttribute('id', 'rtmframe');

	if (popup == 'gmail') {
		// open gmail gadget
		$('body').height(300).width(200);
		frame.setAttribute('src', 'http://www.rememberthemilk.com/services/modules/gmail/');
	}
	else if (popup == 'iphone') {
		// open iphone web app
		$('body').height(480).width(320);
		frame.setAttribute('src', 'http://i.rememberthemilk.com/');
	}
	else if (popup == 'mobile') {
		// open mobile web app
		$('body').height(300).width(200);
		frame.setAttribute('src', 'http://m.rememberthemilk.com/');
	}
	else {
		// igoogle and default
		$('body').height(400).width(400);
		frame.setAttribute('src', 'http://www.rememberthemilk.com/services/modules/googleig/');
	}

	document.body.appendChild(frame);
});

This way, the extension sets the popup size and the iframe location based on a setting saved by the user.

There are a few limitations of this method. Most importantly, you can’t manipulate the iframe once it is loaded, as this is cross-side scripting and is prevented by the browser for security reasons.

That’s about it on loading external web sites in popups. You can use this for a number of things. I’ve mentioned mobile sites, but things like iGoogle widgets also work well.

Do you have any tips on building Chrome extensions based on popups? Or are you having trouble building your extension? Leave a comment!

How to build a Chrome extension, Part 2: Options and localStorage

An important aspect of almost all extensions is being able to save user settings. This can be achieved in Chrome easily by using the localStorage object and Chrome’s extension API options page.

Adding an options page

To add an options page to your extension, make an options.html file in your extension’s folder and add the “options_page” line to your manifest.json like so:

{
  "name": "My Extension",
  ...
  "options_page": "options.html"
  ...
}

localStorage

localStorage is an HTML5 object used for storing web page data locally using JavaScript. Chrome gives extensions the option of using localStorage to save options and data.

Saving options

To save a string to localStorage, use the following code, replacing mysetting and myvalue with your own:

localStorage["mysetting"] = "myvalue";

Or, equivalently:

localStorage.mysetting = "myvalue";

Loading options

To load an option, just access the setting member in the localstorage object:

myvar = localStorage["mysetting"];

Or, equivalently:

myvar = localStorage.mysetting;

It’s always a good idea to make sure you’ve loaded a valid setting. For example, the following code loads a favorite color, but if the current color is not valid, it loads the default value:

var defaultColor = "blue";

function loadFavColor() {
	var favColor = localStorage["favColor"];

	// valid colors are red, blue, green and yellow
	if (favColor == undefined || (favColor != "red" && favColor != "blue" && favColor != "green" && favColor != "yellow")) {
		favColor = defaultColor;
	}

	return favColor;
}

Erasing options

You can erase an option by removing it from the localstorage object, like so:

localStorage.removeItem("mysetting");

Building an options page

Continuing with the favorite color example, lets now build a complete options page for our color-choosing extension. The options.html page would look like this:

<html>
<head>
	<title>Options for Color Chooser</title>
	<script type="text/javascript" src="options.js"></script>
</head>
<body onload="loadOptions()">
	<h1>Favorite Color</h1>
	<select id="color">
		<option value="blue">Blue</option>
		<option value="red">Red</option>
		<option value="green">Green</option>
		<option value="yellow">Yellow</option>
	</select>
	<br />
	<button onclick="saveOptions()">Save</button>
	<br />
	<button onclick="eraseOptions()">Restore default</button>
</body>
</html>

For the behavior of the page, options.js would look like this:

var defaultColor = "blue";

function loadOptions() {
	var favColor = localStorage["favColor"];

	// valid colors are red, blue, green and yellow
	if (favColor == undefined || (favColor != "red" && favColor != "blue" && favColor != "green" && favColor != "yellow")) {
		favColor = defaultColor;
	}

	var select = document.getElementById("color");
	for (var i = 0; i < select.children.length; i++) {
		var child = select.children[i];
			if (child.value == favColor) {
			child.selected = "true";
			break;
		}
	}
}

function saveOptions() {
	var select = document.getElementById("color");
	var color = select.children[select.selectedIndex].value;
	localStorage["favColor"] = color;
}

function eraseOptions() {
	localStorage.removeItem("favColor");
	location.reload();
}

And that’s about it! You can also save and load localStorage data elsewhere in your extension, as the data is shared between all your extension’s files.

Any question, remark, or addition? Please leave a comment!