SlideShare a Scribd company logo
Chrome Extensions
        for Web Hackers
        Scandinavian Web Developer Conference 2010, Stockholm, Sweden
        Mark Wubben




A talk about Chrome Extensions, why they’re so great for web hackers and how to build
them.

Given at the Scandinavian Web Developer Conference on June 2nd, 2010 in Stockholm,
Sweden.

Licensed under Creative Commons Attribution-Share Alike 2.5
http://creativecommons.org/licenses/by-sa/2.5/dk/

Photo by Steve Peck, http://www.flickr.com/photos/stevepeck/4615314670/. CC-BY-2.0.
I’m a Web Hacker
I’m a Web Hacker. That might scare some people, but I don’t hack highway signs or break
into computers. I (try to) build cool shit.

I think you’re web hackers as well, otherwise, why would you be here? But if you’re a web
hacker, why limit yourself to building websites? Why not hack other systems? Build, say,
browser extensions?

Photo by James Kim, http://www.flickr.com/photos/underbiteman/2638246638/. CC-
BY-2.0.
Add-ons, Plugins, Extensions
My question to you is, have you ever build a browser extension? Did you try? Did you look
into it and got scared? That’s been my story—Firefox extension have always looked too
bewildering. You’d have to know about RDF, XUL, XPCOM. You had to restart your browser
every time you wanted to try something. Bah!

Now, this talk is about Google Chrome. And this time, it’s different.

Photo by Jon Fife, http://www.flickr.com/photos/good-karma/652486713/. CC-BY-SA-2.0.
Open Web Technology
See, Chrome’s Extension platform is based on Open Web Technology. It’s based on
JavaScript, mostly. But also HTML and CSS. And the cool new HTML5ish APIs like localStorage
or geo-location.

Let’s dive in.

Photo by Kevin Dooley, http://www.flickr.com/photos/pagedooley/4126491780/. CC-
BY-2.0.
This is the Extensions page in Chrome. It shows you which extensions you have installed. You
can disable or uninstall them, see their web page, allow them to run in Incognito mode.

At the bottom is a link to the Google Chrome Extensions Gallery. At the top is an option to
enable Developer mode.
Developer mode lets you load a new extension from your local file system. You can also
package extensions for release or force the installed extensions to be updated. Normally this
is done automatically when the browser is restarted.
So, what is an extension?!




Now the obvious question is, what *is* an extension?!
An extension is a folder
        with a manifest.json file




In essence, an extension isn’t much more than a folder that contains a manifest.json file.

Let’s try loading a few folders as an extension.
{
     "name": "SWDC For The Win!",
     "version": "1.0"
 }




manifest.json
And there’s the manifest for our very simple extension. These are the only two required
properties, a name for your extension and a version number.

Admittedly, this extension doesn’t do much.

For more about the manifest file, see http://code.google.com/chrome/extensions/
manifest.html.
Extensions can have
        content scripts.




One of the things a Chrome Extension can do is to run scripts on the pages you visit. These
are content scripts and should be familiar, because its a concept from the Firefox-based
Greasemonkey add-on.
Aaron Boodman / Greasemonkey
In fact, the guy who invented Greasemonkey, Aaron Boodman, has been at Google for a few
years now and is one of the guys behind the new Extensions platform. To put it differently,
Chrome Extensions is Greasemonkey on steroids.

Photo by Mark Wubben, http://www.flickr.com/photos/novemberborn/230693761/. CC-BY-
SA-2.0.
Fixing Twitter opening
         links in new windows




You might have noticed how external links on Twitter always open in a new window. I find
this annoying, so I figured I’d write an extension to fix it.
{
     "name": "Twitter Fixer",
     "version": "1.0",
     "description": "Fix the external links…",
     "content_scripts": [{
        "matches": ["http://*.twitter.com/*",
                    "https://*.twitter.com/*"],
        "js": ["dojo.js", "fixer.js"]
     }]
 }




manifest.json
The manifest for our new extension, dubbed Twitter Fixer.
{
     "name": "Twitter Fixer",
     "version": "1.0",
     "description": "Fix the external links…",
     "content_scripts": [{
        "matches": ["http://*.twitter.com/*",
                    "https://*.twitter.com/*"],
        "js": ["dojo.js", "fixer.js"]
     }]
 }




manifest.json
Note how I’ve added a description.
{
     "name": "Twitter Fixer",
     "version": "1.0",
     "description": "Fix the external links…",
     "content_scripts": [{
        "matches": ["http://*.twitter.com/*",
                    "https://*.twitter.com/*"],
        "js": ["dojo.js", "fixer.js"]
     }]
 }




manifest.json
You can specify multiple content scripts per extension.
{
     "name": "Twitter Fixer",
     "version": "1.0",
     "description": "Fix the external links…",
     "content_scripts": [{
        "matches": ["http://*.twitter.com/*",
                    "https://*.twitter.com/*"],
        "js": ["dojo.js", "fixer.js"]
     }]
 }




manifest.json
A content scripts needs to match a page. This is done through match patterns. Here we
specify our extension will run on any page or subdomain on twitter.com, over HTTP as well as
HTTPS.

Keep in mind that the user is warned about the sites you might match. The more restrictive
your match pattern, the better.

To learn more, see http://code.google.com/chrome/extensions/match_patterns.html.
{
     "name": "Twitter Fixer",
     "version": "1.0",
     "description": "Fix the external links…",
     "content_scripts": [{
        "matches": ["http://*.twitter.com/*",
                    "https://*.twitter.com/*"],
        "js": ["dojo.js", "fixer.js"]
     }]
 }




manifest.json
A content script itself can exist of any number of JavaScript files. They’re loaded in the same
order as you specify in the manifest. Here I load a version of the Dojo Toolkit and my own
code.

You can also specify CSS files that need to be added to the page your content script runs on.

To learn more, see http://code.google.com/chrome/extensions/content_scripts.html.
dojo.query("a[target=_blank]").attr("target", "");




fixer.js
A content script itself can exist of any number of JavaScript files. They’re loaded in the same
order as you specify in the manifest. Here I load a version of the Dojo Toolkit and my own
code.

You can also specify CSS files that need to be added to the page your content script runs on.

To learn more, see http://code.google.com/chrome/extensions/content_scripts.html.
Demo time
Isolated Worlds
Chrome has learned from the security problems that existed with Greasemonkey, and even
with Firefox add-ons as a whole. Each extension lives in a so-called “isolated world”,
meaning it’s isolated from other extensions save for a few tightly controlled communication
bridges.

Photo by F.H. Mira, http://www.flickr.com/photos/fhmira/3204656258/sizes/o/. CC-BY-
SA-2.0.
Content scripts run in
        separate contexts




For example, the JavaScript inside your content scripts is evaluated in a separate context
from the page JavaScript. This means your code won’t affect the page code, and vice versa.
You can’t directly call page code, and it can’t directly call your code.
Shared DOM




Luckily the page document is shared between the various content scripts that might be
running on it. That way, you can change it!
Communicating with page
        JavaScript




But with these isolated worlds, how can your content scripts talk to the page JavaScript? Well,
you’ve got access to the DOM, so you can insert your own JavaScript into the page! And, you
can use DOM events so the inserted JavaScript can talk back to you.
document.documentElement.addEventListener(
    "SWDCNotify",
    function(){ alert("Notified!"); },
    false
 );

 var s = document.createElement("script");
 s.textContent = 'function notifyContentScript(){
   var evt = document.createEvent("Event");
   evt.initEvent("SWDCNotify", false, false);
   document.documentElement.dispatchEvent(evt);
 }';
 document.body.appendChild(s);



communication.js
This sets up a content script that insert the `notifyContentScript` method into the page.
When this method is called, a custom DOM event is dispatched on the document element,
which is used to notify the content script.

While you can’t send data along with the event, you can store it in the DOM. The content
script can then look it up.
document.documentElement.addEventListener(
   "SWDCNotify",
   function(){ alert("Notified!"); },
   false
);

var s = document.createElement("script");
s.textContent = 'function notifyContentScript(){
  var evt = document.createEvent("Event");
  evt.initEvent("SWDCNotify", false, false);
  document.documentElement.dispatchEvent(evt);
}';
document.body.appendChild(s);



communication.js
document.documentElement.addEventListener(
   "SWDCNotify",
   function(){ alert("Notified!"); },
   false
);

var s = document.createElement("script");
s.textContent = 'function notifyContentScript(){
  var evt = document.createEvent("Event");
  evt.initEvent("SWDCNotify", false, false);
  document.documentElement.dispatchEvent(evt);
}';
document.body.appendChild(s);



communication.js
document.documentElement.addEventListener(
   "SWDCNotify",
   function(){ alert("Notified!"); },
   false
);

var s = document.createElement("script");
s.textContent = 'function notifyContentScript(){
  var evt = document.createEvent("Event");
  evt.initEvent("SWDCNotify", false, false);
  document.documentElement.dispatchEvent(evt);
}';
document.body.appendChild(s);



communication.js
Demo time
Content scripts are limited.
        Background pages!




Content scripts are fairly limited though. They exist only as long as the page they run on
exists. They don’t have access to any permanent storage, so you can’t configure them. Nor
can they talk to other websites, so you can’t look up anything through an API.

Luckily, Chrome Extensions let you build background pages. These are normal HTML pages,
except that they’re not rendered. They’re loaded when the browser starts, and won’t be
unloaded until it’s closed.

Let’s build a more complicated extension.
Expanding bit.ly URLs on
         Twitter




Due to character constraints URLs in Tweets are often shortened. But, I’d like to see where
I’m going! Let’s write Chrome Extension that can expand bit.ly URLs.
{
    "name": "Twitter Fixer",
    "version": "1.0",
    "description": "Expands shortened URLs…",
    "permissions": ["http://api.bit.ly/*"],
    "background_page": "background.html",
    "content_scripts": [{
       "run_at": "document_end",
       "matches": ["http://*.twitter.com/*",
                   "https://*.twitter.com/*"],
       "js": ["dojo.js", "fixer.js"]
    }]
}



manifest.json
{
     "name": "Twitter Fixer",
     "version": "1.0",
     "description": "Expands shortened URLs…",
     "permissions": ["http://api.bit.ly/*"],
     "background_page": "background.html",
     "content_scripts": [{
        "run_at": "document_end",
        "matches": ["http://*.twitter.com/*",
                    "https://*.twitter.com/*"],
        "js": ["dojo.js", "fixer.js"]
     }]
 }



manifest.json
I’ve made two major modifications to the manifest.json we used previously. First is loading
the background page, this is done using the background_page property whose value is the
relative path (from the manifest.json file) to the background page. By convention this is
named background.html, but you can name it whatever you like.

The other change is that I’m now requesting permission to talk to the Bit.ly API. Chrome
forces the extension developer to request permission for almost anything. When the user
installs your extension he’s made aware of what you’re extension will have permission to,
therefore making it harder for nefarious Extension developers to sneak bad stuff into their
extensions without the users knowing about it.
{
     "name": "Twitter Fixer",
     "version": "1.0",
     "description": "Expands shortened URLs…",
     "permissions": ["http://api.bit.ly/*"],
     "background_page": "background.html",
     "content_scripts": [{
        "run_at": "document_end",
        "matches": ["http://*.twitter.com/*",
                    "https://*.twitter.com/*"],
        "js": ["dojo.js", "fixer.js"]
     }]
 }



manifest.json
Another change I made is to specify the `run_at` property for the content script. This way I
can make sure it runs right after the page document has finished parsing, so we don’t have
to wait too long before we can expand the bit.ly URLs.
var parsed = parseUrls();
 chrome.extension.sendRequest(
    parsed.hashes,
    function(mapping){
      for(hash in mapping){
        parsed.links[hash].forEach(function(link){
          link.textContent = mapping[hash];
        });
      }
    }
 );




fixer.js
The code to find the URLs in the page isn’t terribly important so I’ve not put it in this slide.
Suffice to say, `parsed` contains a list of bit.ly hashes, and a mapping from a hash to one or
more link elements.
var parsed = parseUrls();
 chrome.extension.sendRequest(
    parsed.hashes,
    function(mapping){
      for(hash in mapping){
        parsed.links[hash].forEach(function(link){
          link.textContent = mapping[hash];
        });
      }
    }
 );




fixer.js
The content script needs to talk to the background page to expand the hashes. This is done
through the `chrome.extension.sendRequest` API.
var parsed = parseUrls();
 chrome.extension.sendRequest(
    parsed.hashes,
    function(mapping){
      for(hash in mapping){
        parsed.links[hash].forEach(function(link){
          link.textContent = mapping[hash];
        });
      }
    }
 );




fixer.js
Also note how I can use forEach on an array. Chrome has a fully up-to-date JavaScript engine
so native forEach is available.

Same for using textContent to set the link text value.
<!DOCTYPE html>

 <script src="dojo.js"></script>
 <script>
 chrome.extension.onRequest.addListener(
    function(hashes, sender, sendResponse){
      // …
      sendResponse(mapping);
    }
 );
 </script>




background.html
I won’t go into the specifics of how to talk to bit.ly and get the expanded URLs.
<!DOCTYPE html>

 <script src="dojo.js"></script>
 <script>
 chrome.extension.onRequest.addListener(
    function(hashes, sender, sendResponse){
      // …
      sendResponse(mapping);
    }
 );
 </script>




background.html
The important bit is how you register a handler for requests from the content script. You get
the request object, a reference to the tab from which the request was sent, and a callback
function to call once you have a response.

This communication mechanism is completely asynchronous.
Demo time
Debugging
        Web Inspector




You can easily debug your extension using the Web Inspector you would normally use to
debug your web pages. You can set break points or use the debugger keyword. An inspector
for the background page can be opened by clicking on the “background.html” link in the
Extensions page (if you have Developer mode enabled).

You may also notice how the background page is actually at “chrome-extension://some-
unique-identifier/background.html”. This is the domain it runs in, so the extension can
piggyback on the normal same-origin restrictions!
Extension configuration,
        persistent storage




When talking about the limitations of content scripts, I promised you permanent storage and
extension configuration. Let’s have a look how that’s done.
Combining the extensions,
         with options




Let’s combine the two extensions we’ve made into a single extension. Since not everybody
wants the external links on Twitter to be opened in a new window, we’ll add an options page
so this can be customized.
{
     "name": "Twitter Fixer",
     "version": "1.0",
     "description": "Fix the external links …",
     "permissions": ["http://api.bit.ly/*"],
     "background_page": "background.html",
     "options_page": "options.html",
     "content_scripts": [{
        "run_at": "document_end",
        "matches": ["http://*.twitter.com/*",
                    "https://*.twitter.com/*"],
        "js": ["dojo.js", "fixer.js"]
     }]
 }


manifest.json
Our new manifest.
{
     "name": "Twitter Fixer",
     "version": "1.0",
     "description": "Fix the external links …",
     "permissions": ["http://api.bit.ly/*"],
     "background_page": "background.html",
     "options_page": "options.html",
     "content_scripts": [{
        "run_at": "document_end",
        "matches": ["http://*.twitter.com/*",
                    "https://*.twitter.com/*"],
        "js": ["dojo.js", "fixer.js"]
     }]
 }


manifest.json
Chrome has special support for an Options page. It’ll show up under the extension name
when it’s listed in the Extension page, and simply is a HTML page you provide.

I won’t show the changes made to combine the extensions, but in general, the content script
now talks to the background page to see which feature is enabled. The background page
looks it up in localStorage, which is where the options page has saved the configuration.
Demo time
Chrome APIs




Chrome provides a ton of proprietary APIs for interacting with the user. A quick overview.
Page actions
        Browser actions
        Popups



You can add an action button to the browser Chrome. If the action button is specific to a
page, you can use a Page action. This can be controlled to only show up when it’s necessary.
Browser actions are always visible. An extension cannot specify both a page and a browser
action.

You can use an image as the action icon, or use output from the Canvas API. Browser actions
can have badges that communicate some information, say an unread messages count.

When the user clicks on a page/browser action, you can show a tooltip.
Chrome Extensions for Web Hackers
Chrome Extensions for Web Hackers
This is the Extensions page in Chrome. It shows you which extensions you have installed. You
can disable or uninstall them, see their web page, allow them to run in Incognito mode.

At the bottom is a link to the Google Chrome Extensions Gallery. At the top is an option to
enable Developer mode.
This is the Extensions page in Chrome. It shows you which extensions you have installed. You
can disable or uninstall them, see their web page, allow them to run in Incognito mode.

At the bottom is a link to the Google Chrome Extensions Gallery. At the top is an option to
enable Developer mode.
Desktop Notifications




You can show Desktop Notifications, provided you requested permission to do this.
This is the Extensions page in Chrome. It shows you which extensions you have installed. You
can disable or uninstall them, see their web page, allow them to run in Incognito mode.

At the bottom is a link to the Google Chrome Extensions Gallery. At the top is an option to
enable Developer mode.
History
        Bookmarks




You can also interact with the browser history and the user’s bookmarks. Plus, you can
override the History page to provide a better interface.
Tabs
        Windows




Chrome also lets you manipulate open tabs and windows. You can override the new tab page.

You can’t override the Extensions page though, for obvious reasons.
Publishing




But, aside from all these capabilities, perhaps the most important thing is having other
people use your extension!

So far we’ve loaded extensions from your local machine. Let’s see how we can package those
local files so that anybody can install your extension.
Demo time




You can pack your extension using the “Pack extension…” option on the Extensions page (in
Developer mode). This takes the path to your extension and a possible private key file.

The end result is a `.crx` file, which in essence is a signed ZIP file. You’ll also get a `.pem`
file which contains the private key for your extension. This is important, the private key is
used to sign the ZIP file, and Chrome will refuse to update your extension if the new
extension file was not signed with the same private key.
Gallery




Chrome also has a Gallery where you can distribute your extension. They manage packaging
and updating your extension, and will also keep track of the private key for you. This of
course is the best place for your extension, though you’re free to host it yourself.

In the latter case, you’ll have to set up some extra files on your server to support auto-
updating of your extension.
Questions?



        Mark Wubben

        supercollider.dk & novemberborn.net
        twitter.com/novemberborn

        Slides: 11born.net/swdc



                                               Licensed under Creative Commons Attribution-Share Alike 2.5
                                                        http://creativecommons.org/licenses/by-sa/2.5/dk/




And that concludes this talk. Thank you for your attention.
Steve Peck
   James Kim
   Jon Fife
   Kevin Dooley
   F H Mira
   Matt Jones
   Jeff Kubina



Many, many thanks to the wonderful people on Flickr who licensed their photos under
Creative Commons.

Photo by Jeff Kubina, http://flickr.com/photos/kubina/903033693/. CC-BY-SA 2.0.
Now, as Matt Jones would put it, GET EXCITED and MAKE THINGS!

Illustration by Matt Jones, CC-BY-SA-NC, http://www.flickr.com/photos/blackbeltjones/
3365682994/.

More Related Content

PDF
Advanced Chrome extension exploitation
ODP
More Browser Basics, Tips & Tricks 3 Draft 8
 
ODP
Web Browser Basics, Tips & Tricks Draft 17
 
ODP
More Browser Basics, Tips & Tricks 2 Draft 17
 
ODP
Running Android Apps on Chrome & ChromeOS
 
ODP
New or obscure web browsers 4x3 (rcsi draft 6)
 
POT
Browser extension
ODP
HTML5 e CSS3 (slides della sessione tenuta al DIMI di Udine)
Advanced Chrome extension exploitation
More Browser Basics, Tips & Tricks 3 Draft 8
 
Web Browser Basics, Tips & Tricks Draft 17
 
More Browser Basics, Tips & Tricks 2 Draft 17
 
Running Android Apps on Chrome & ChromeOS
 
New or obscure web browsers 4x3 (rcsi draft 6)
 
Browser extension
HTML5 e CSS3 (slides della sessione tenuta al DIMI di Udine)

What's hot (8)

PDF
05370705
DOCX
A Manual for Setting up a WordPress Website on the Local Linux Server with Va...
PDF
Chrome extension development
PDF
Html5: Something wicked this way comes (Hack in Paris)
PDF
Web Slices
PDF
Introduction to Google Chrome Extensions Development
PPTX
Google I/O 2012 - Protecting your user experience while integrating 3rd party...
PDF
Building a Client .NET for SugarCRM
05370705
A Manual for Setting up a WordPress Website on the Local Linux Server with Va...
Chrome extension development
Html5: Something wicked this way comes (Hack in Paris)
Web Slices
Introduction to Google Chrome Extensions Development
Google I/O 2012 - Protecting your user experience while integrating 3rd party...
Building a Client .NET for SugarCRM

Viewers also liked (14)

PDF
Mad scalability: Scaling when you are not Google
PDF
Bio 3A POSTER- The effect of ethanol on CO₂ production in mice Mus musculus
PDF
Tfa_N-methylation
PDF
Mary Ann Shaw Center for Public and Community Service Spring 2016 Newsletter
PPTX
Informatica y periodismo
PPTX
Biodegradable Materials, Biodegradable ink pens IDM10
PDF
Presentación Frumecar recicladores
PPTX
ET2016 Smart Japan Alliance Llilum 161118
ODP
Los musulmanes
PPTX
3. report writing
PDF
Storia dei rolex dal 1912
PPTX
Tipos de memoria
PPTX
Curso de Procesado de Fotografía Digital: 3. Selección avanzada en Photoshop
PPTX
How entrepreneurs can overcome depression
Mad scalability: Scaling when you are not Google
Bio 3A POSTER- The effect of ethanol on CO₂ production in mice Mus musculus
Tfa_N-methylation
Mary Ann Shaw Center for Public and Community Service Spring 2016 Newsletter
Informatica y periodismo
Biodegradable Materials, Biodegradable ink pens IDM10
Presentación Frumecar recicladores
ET2016 Smart Japan Alliance Llilum 161118
Los musulmanes
3. report writing
Storia dei rolex dal 1912
Tipos de memoria
Curso de Procesado de Fotografía Digital: 3. Selección avanzada en Photoshop
How entrepreneurs can overcome depression

Similar to Chrome Extensions for Web Hackers (20)

PDF
Browser Extensions for Web Hackers
PDF
Creating chrome-extension
PPTX
Google chrome extension
PPT
Chrome Extension Develop Starts
PPTX
CMS & Chrome Extension Development
PPTX
Web technologies part-2
PPTX
JavaScript Presentation Frameworks and Libraries
PDF
Chrome Extensions - Basic concepts powerpoint
DOCX
1 Web Page Foundations Overview This lab walk.docx
PDF
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
PPTX
JavaScript - Getting Started.pptx
PDF
JavaScript Mini FAQ 1st Edition by Danny Goodman ISBN
PPTX
Orange is the new blue: How to port Chrome Extension to Firefox Extension
PDF
JavaScript Mini FAQ 1st Edition by Danny Goodman ISBN
PPT
JavaScript Missing Manual, Ch. 1
PPTX
HTML5 introduction for beginners
PPTX
Chrome Extension Step by step Guide .pptx
PPTX
High-Speed HTML5
PDF
Shifting Gears
PPTX
TopicHero Descriptions Tutorial
Browser Extensions for Web Hackers
Creating chrome-extension
Google chrome extension
Chrome Extension Develop Starts
CMS & Chrome Extension Development
Web technologies part-2
JavaScript Presentation Frameworks and Libraries
Chrome Extensions - Basic concepts powerpoint
1 Web Page Foundations Overview This lab walk.docx
WordCamp Greenville 2018 - Beware the Dark Side, or an Intro to Development
JavaScript - Getting Started.pptx
JavaScript Mini FAQ 1st Edition by Danny Goodman ISBN
Orange is the new blue: How to port Chrome Extension to Firefox Extension
JavaScript Mini FAQ 1st Edition by Danny Goodman ISBN
JavaScript Missing Manual, Ch. 1
HTML5 introduction for beginners
Chrome Extension Step by step Guide .pptx
High-Speed HTML5
Shifting Gears
TopicHero Descriptions Tutorial

More from Mark Wubben (9)

PDF
Building Installations in Five Days (and a bit) at Ignite London 4
PDF
Theory from Practice: Stories and Takeaways from Hacker Camps
PDF
Building Installations in Five Days (and a bit) — Södertörn University
PDF
Homemade Ubicomp at Reboot 11
KEY
Web Typography with sIFR 3 at Drupalcamp Copenhagen
KEY
Geek Meet: Homemade Ubicomp
KEY
Geek Meet: Web Typography and sIFR 3
PDF
Bringing Typography to the Web with sIFR 3 at <head>
PDF
SHiFT 08 - Home Made Ubicomp
Building Installations in Five Days (and a bit) at Ignite London 4
Theory from Practice: Stories and Takeaways from Hacker Camps
Building Installations in Five Days (and a bit) — Södertörn University
Homemade Ubicomp at Reboot 11
Web Typography with sIFR 3 at Drupalcamp Copenhagen
Geek Meet: Homemade Ubicomp
Geek Meet: Web Typography and sIFR 3
Bringing Typography to the Web with sIFR 3 at <head>
SHiFT 08 - Home Made Ubicomp

Recently uploaded (20)

PPTX
UNIVERSAL HUMAN VALUES for NEP student .pptx
PPT
proper hygiene for teenagers for secondary students .ppt
PDF
technical writing on emotional quotient ppt
PDF
Top 10 Visionary Entrepreneurs to Watch in 2025
PPTX
How to Deal with Imposter Syndrome for Personality Development?
PDF
My 'novel' Account of Human Possibility pdf.pdf
PPT
cypt-cht-healthy-relationships-part1-presentation-v1.1en.ppt
PPTX
Personal Development - By Knowing Oneself?
PDF
SEX-GENDER-AND-SEXUALITY-LESSON-1-M (2).pdf
PPTX
Learn how to use Portable Grinders Safely
PPTX
The Hidden Link Between Self-Talk and Self-Worth.pptx
PPTX
show1- motivational ispiring positive thinking
PPTX
Identity Development in Adolescence.pptx
PPTX
Emotional Intelligence- Importance and Applicability
PDF
Quiet Wins: Why the Silent Fish Survives.pdf
PPTX
Commmunication in Todays world- Principles and Barriers
PPTX
Learn how to prevent Workplace Incidents?
PPTX
Travel mania in india needs to change the world
PDF
Red Light Wali Muskurahat – A Heart-touching Hindi Story
PPTX
THEORIES-PSYCH-3.pptx theory of Abraham Maslow
UNIVERSAL HUMAN VALUES for NEP student .pptx
proper hygiene for teenagers for secondary students .ppt
technical writing on emotional quotient ppt
Top 10 Visionary Entrepreneurs to Watch in 2025
How to Deal with Imposter Syndrome for Personality Development?
My 'novel' Account of Human Possibility pdf.pdf
cypt-cht-healthy-relationships-part1-presentation-v1.1en.ppt
Personal Development - By Knowing Oneself?
SEX-GENDER-AND-SEXUALITY-LESSON-1-M (2).pdf
Learn how to use Portable Grinders Safely
The Hidden Link Between Self-Talk and Self-Worth.pptx
show1- motivational ispiring positive thinking
Identity Development in Adolescence.pptx
Emotional Intelligence- Importance and Applicability
Quiet Wins: Why the Silent Fish Survives.pdf
Commmunication in Todays world- Principles and Barriers
Learn how to prevent Workplace Incidents?
Travel mania in india needs to change the world
Red Light Wali Muskurahat – A Heart-touching Hindi Story
THEORIES-PSYCH-3.pptx theory of Abraham Maslow

Chrome Extensions for Web Hackers

  • 1. Chrome Extensions for Web Hackers Scandinavian Web Developer Conference 2010, Stockholm, Sweden Mark Wubben A talk about Chrome Extensions, why they’re so great for web hackers and how to build them. Given at the Scandinavian Web Developer Conference on June 2nd, 2010 in Stockholm, Sweden. Licensed under Creative Commons Attribution-Share Alike 2.5 http://creativecommons.org/licenses/by-sa/2.5/dk/ Photo by Steve Peck, http://www.flickr.com/photos/stevepeck/4615314670/. CC-BY-2.0.
  • 2. I’m a Web Hacker I’m a Web Hacker. That might scare some people, but I don’t hack highway signs or break into computers. I (try to) build cool shit. I think you’re web hackers as well, otherwise, why would you be here? But if you’re a web hacker, why limit yourself to building websites? Why not hack other systems? Build, say, browser extensions? Photo by James Kim, http://www.flickr.com/photos/underbiteman/2638246638/. CC- BY-2.0.
  • 3. Add-ons, Plugins, Extensions My question to you is, have you ever build a browser extension? Did you try? Did you look into it and got scared? That’s been my story—Firefox extension have always looked too bewildering. You’d have to know about RDF, XUL, XPCOM. You had to restart your browser every time you wanted to try something. Bah! Now, this talk is about Google Chrome. And this time, it’s different. Photo by Jon Fife, http://www.flickr.com/photos/good-karma/652486713/. CC-BY-SA-2.0.
  • 4. Open Web Technology See, Chrome’s Extension platform is based on Open Web Technology. It’s based on JavaScript, mostly. But also HTML and CSS. And the cool new HTML5ish APIs like localStorage or geo-location. Let’s dive in. Photo by Kevin Dooley, http://www.flickr.com/photos/pagedooley/4126491780/. CC- BY-2.0.
  • 5. This is the Extensions page in Chrome. It shows you which extensions you have installed. You can disable or uninstall them, see their web page, allow them to run in Incognito mode. At the bottom is a link to the Google Chrome Extensions Gallery. At the top is an option to enable Developer mode.
  • 6. Developer mode lets you load a new extension from your local file system. You can also package extensions for release or force the installed extensions to be updated. Normally this is done automatically when the browser is restarted.
  • 7. So, what is an extension?! Now the obvious question is, what *is* an extension?!
  • 8. An extension is a folder with a manifest.json file In essence, an extension isn’t much more than a folder that contains a manifest.json file. Let’s try loading a few folders as an extension.
  • 9. { "name": "SWDC For The Win!", "version": "1.0" } manifest.json And there’s the manifest for our very simple extension. These are the only two required properties, a name for your extension and a version number. Admittedly, this extension doesn’t do much. For more about the manifest file, see http://code.google.com/chrome/extensions/ manifest.html.
  • 10. Extensions can have content scripts. One of the things a Chrome Extension can do is to run scripts on the pages you visit. These are content scripts and should be familiar, because its a concept from the Firefox-based Greasemonkey add-on.
  • 11. Aaron Boodman / Greasemonkey In fact, the guy who invented Greasemonkey, Aaron Boodman, has been at Google for a few years now and is one of the guys behind the new Extensions platform. To put it differently, Chrome Extensions is Greasemonkey on steroids. Photo by Mark Wubben, http://www.flickr.com/photos/novemberborn/230693761/. CC-BY- SA-2.0.
  • 12. Fixing Twitter opening links in new windows You might have noticed how external links on Twitter always open in a new window. I find this annoying, so I figured I’d write an extension to fix it.
  • 13. { "name": "Twitter Fixer", "version": "1.0", "description": "Fix the external links…", "content_scripts": [{ "matches": ["http://*.twitter.com/*", "https://*.twitter.com/*"], "js": ["dojo.js", "fixer.js"] }] } manifest.json The manifest for our new extension, dubbed Twitter Fixer.
  • 14. { "name": "Twitter Fixer", "version": "1.0", "description": "Fix the external links…", "content_scripts": [{ "matches": ["http://*.twitter.com/*", "https://*.twitter.com/*"], "js": ["dojo.js", "fixer.js"] }] } manifest.json Note how I’ve added a description.
  • 15. { "name": "Twitter Fixer", "version": "1.0", "description": "Fix the external links…", "content_scripts": [{ "matches": ["http://*.twitter.com/*", "https://*.twitter.com/*"], "js": ["dojo.js", "fixer.js"] }] } manifest.json You can specify multiple content scripts per extension.
  • 16. { "name": "Twitter Fixer", "version": "1.0", "description": "Fix the external links…", "content_scripts": [{ "matches": ["http://*.twitter.com/*", "https://*.twitter.com/*"], "js": ["dojo.js", "fixer.js"] }] } manifest.json A content scripts needs to match a page. This is done through match patterns. Here we specify our extension will run on any page or subdomain on twitter.com, over HTTP as well as HTTPS. Keep in mind that the user is warned about the sites you might match. The more restrictive your match pattern, the better. To learn more, see http://code.google.com/chrome/extensions/match_patterns.html.
  • 17. { "name": "Twitter Fixer", "version": "1.0", "description": "Fix the external links…", "content_scripts": [{ "matches": ["http://*.twitter.com/*", "https://*.twitter.com/*"], "js": ["dojo.js", "fixer.js"] }] } manifest.json A content script itself can exist of any number of JavaScript files. They’re loaded in the same order as you specify in the manifest. Here I load a version of the Dojo Toolkit and my own code. You can also specify CSS files that need to be added to the page your content script runs on. To learn more, see http://code.google.com/chrome/extensions/content_scripts.html.
  • 18. dojo.query("a[target=_blank]").attr("target", ""); fixer.js A content script itself can exist of any number of JavaScript files. They’re loaded in the same order as you specify in the manifest. Here I load a version of the Dojo Toolkit and my own code. You can also specify CSS files that need to be added to the page your content script runs on. To learn more, see http://code.google.com/chrome/extensions/content_scripts.html.
  • 20. Isolated Worlds Chrome has learned from the security problems that existed with Greasemonkey, and even with Firefox add-ons as a whole. Each extension lives in a so-called “isolated world”, meaning it’s isolated from other extensions save for a few tightly controlled communication bridges. Photo by F.H. Mira, http://www.flickr.com/photos/fhmira/3204656258/sizes/o/. CC-BY- SA-2.0.
  • 21. Content scripts run in separate contexts For example, the JavaScript inside your content scripts is evaluated in a separate context from the page JavaScript. This means your code won’t affect the page code, and vice versa. You can’t directly call page code, and it can’t directly call your code.
  • 22. Shared DOM Luckily the page document is shared between the various content scripts that might be running on it. That way, you can change it!
  • 23. Communicating with page JavaScript But with these isolated worlds, how can your content scripts talk to the page JavaScript? Well, you’ve got access to the DOM, so you can insert your own JavaScript into the page! And, you can use DOM events so the inserted JavaScript can talk back to you.
  • 24. document.documentElement.addEventListener( "SWDCNotify", function(){ alert("Notified!"); }, false ); var s = document.createElement("script"); s.textContent = 'function notifyContentScript(){ var evt = document.createEvent("Event"); evt.initEvent("SWDCNotify", false, false); document.documentElement.dispatchEvent(evt); }'; document.body.appendChild(s); communication.js This sets up a content script that insert the `notifyContentScript` method into the page. When this method is called, a custom DOM event is dispatched on the document element, which is used to notify the content script. While you can’t send data along with the event, you can store it in the DOM. The content script can then look it up.
  • 25. document.documentElement.addEventListener( "SWDCNotify", function(){ alert("Notified!"); }, false ); var s = document.createElement("script"); s.textContent = 'function notifyContentScript(){ var evt = document.createEvent("Event"); evt.initEvent("SWDCNotify", false, false); document.documentElement.dispatchEvent(evt); }'; document.body.appendChild(s); communication.js
  • 26. document.documentElement.addEventListener( "SWDCNotify", function(){ alert("Notified!"); }, false ); var s = document.createElement("script"); s.textContent = 'function notifyContentScript(){ var evt = document.createEvent("Event"); evt.initEvent("SWDCNotify", false, false); document.documentElement.dispatchEvent(evt); }'; document.body.appendChild(s); communication.js
  • 27. document.documentElement.addEventListener( "SWDCNotify", function(){ alert("Notified!"); }, false ); var s = document.createElement("script"); s.textContent = 'function notifyContentScript(){ var evt = document.createEvent("Event"); evt.initEvent("SWDCNotify", false, false); document.documentElement.dispatchEvent(evt); }'; document.body.appendChild(s); communication.js
  • 29. Content scripts are limited. Background pages! Content scripts are fairly limited though. They exist only as long as the page they run on exists. They don’t have access to any permanent storage, so you can’t configure them. Nor can they talk to other websites, so you can’t look up anything through an API. Luckily, Chrome Extensions let you build background pages. These are normal HTML pages, except that they’re not rendered. They’re loaded when the browser starts, and won’t be unloaded until it’s closed. Let’s build a more complicated extension.
  • 30. Expanding bit.ly URLs on Twitter Due to character constraints URLs in Tweets are often shortened. But, I’d like to see where I’m going! Let’s write Chrome Extension that can expand bit.ly URLs.
  • 31. { "name": "Twitter Fixer", "version": "1.0", "description": "Expands shortened URLs…", "permissions": ["http://api.bit.ly/*"], "background_page": "background.html", "content_scripts": [{ "run_at": "document_end", "matches": ["http://*.twitter.com/*", "https://*.twitter.com/*"], "js": ["dojo.js", "fixer.js"] }] } manifest.json
  • 32. { "name": "Twitter Fixer", "version": "1.0", "description": "Expands shortened URLs…", "permissions": ["http://api.bit.ly/*"], "background_page": "background.html", "content_scripts": [{ "run_at": "document_end", "matches": ["http://*.twitter.com/*", "https://*.twitter.com/*"], "js": ["dojo.js", "fixer.js"] }] } manifest.json I’ve made two major modifications to the manifest.json we used previously. First is loading the background page, this is done using the background_page property whose value is the relative path (from the manifest.json file) to the background page. By convention this is named background.html, but you can name it whatever you like. The other change is that I’m now requesting permission to talk to the Bit.ly API. Chrome forces the extension developer to request permission for almost anything. When the user installs your extension he’s made aware of what you’re extension will have permission to, therefore making it harder for nefarious Extension developers to sneak bad stuff into their extensions without the users knowing about it.
  • 33. { "name": "Twitter Fixer", "version": "1.0", "description": "Expands shortened URLs…", "permissions": ["http://api.bit.ly/*"], "background_page": "background.html", "content_scripts": [{ "run_at": "document_end", "matches": ["http://*.twitter.com/*", "https://*.twitter.com/*"], "js": ["dojo.js", "fixer.js"] }] } manifest.json Another change I made is to specify the `run_at` property for the content script. This way I can make sure it runs right after the page document has finished parsing, so we don’t have to wait too long before we can expand the bit.ly URLs.
  • 34. var parsed = parseUrls(); chrome.extension.sendRequest( parsed.hashes, function(mapping){ for(hash in mapping){ parsed.links[hash].forEach(function(link){ link.textContent = mapping[hash]; }); } } ); fixer.js The code to find the URLs in the page isn’t terribly important so I’ve not put it in this slide. Suffice to say, `parsed` contains a list of bit.ly hashes, and a mapping from a hash to one or more link elements.
  • 35. var parsed = parseUrls(); chrome.extension.sendRequest( parsed.hashes, function(mapping){ for(hash in mapping){ parsed.links[hash].forEach(function(link){ link.textContent = mapping[hash]; }); } } ); fixer.js The content script needs to talk to the background page to expand the hashes. This is done through the `chrome.extension.sendRequest` API.
  • 36. var parsed = parseUrls(); chrome.extension.sendRequest( parsed.hashes, function(mapping){ for(hash in mapping){ parsed.links[hash].forEach(function(link){ link.textContent = mapping[hash]; }); } } ); fixer.js Also note how I can use forEach on an array. Chrome has a fully up-to-date JavaScript engine so native forEach is available. Same for using textContent to set the link text value.
  • 37. <!DOCTYPE html> <script src="dojo.js"></script> <script> chrome.extension.onRequest.addListener( function(hashes, sender, sendResponse){ // … sendResponse(mapping); } ); </script> background.html I won’t go into the specifics of how to talk to bit.ly and get the expanded URLs.
  • 38. <!DOCTYPE html> <script src="dojo.js"></script> <script> chrome.extension.onRequest.addListener( function(hashes, sender, sendResponse){ // … sendResponse(mapping); } ); </script> background.html The important bit is how you register a handler for requests from the content script. You get the request object, a reference to the tab from which the request was sent, and a callback function to call once you have a response. This communication mechanism is completely asynchronous.
  • 40. Debugging Web Inspector You can easily debug your extension using the Web Inspector you would normally use to debug your web pages. You can set break points or use the debugger keyword. An inspector for the background page can be opened by clicking on the “background.html” link in the Extensions page (if you have Developer mode enabled). You may also notice how the background page is actually at “chrome-extension://some- unique-identifier/background.html”. This is the domain it runs in, so the extension can piggyback on the normal same-origin restrictions!
  • 41. Extension configuration, persistent storage When talking about the limitations of content scripts, I promised you permanent storage and extension configuration. Let’s have a look how that’s done.
  • 42. Combining the extensions, with options Let’s combine the two extensions we’ve made into a single extension. Since not everybody wants the external links on Twitter to be opened in a new window, we’ll add an options page so this can be customized.
  • 43. { "name": "Twitter Fixer", "version": "1.0", "description": "Fix the external links …", "permissions": ["http://api.bit.ly/*"], "background_page": "background.html", "options_page": "options.html", "content_scripts": [{ "run_at": "document_end", "matches": ["http://*.twitter.com/*", "https://*.twitter.com/*"], "js": ["dojo.js", "fixer.js"] }] } manifest.json Our new manifest.
  • 44. { "name": "Twitter Fixer", "version": "1.0", "description": "Fix the external links …", "permissions": ["http://api.bit.ly/*"], "background_page": "background.html", "options_page": "options.html", "content_scripts": [{ "run_at": "document_end", "matches": ["http://*.twitter.com/*", "https://*.twitter.com/*"], "js": ["dojo.js", "fixer.js"] }] } manifest.json Chrome has special support for an Options page. It’ll show up under the extension name when it’s listed in the Extension page, and simply is a HTML page you provide. I won’t show the changes made to combine the extensions, but in general, the content script now talks to the background page to see which feature is enabled. The background page looks it up in localStorage, which is where the options page has saved the configuration.
  • 46. Chrome APIs Chrome provides a ton of proprietary APIs for interacting with the user. A quick overview.
  • 47. Page actions Browser actions Popups You can add an action button to the browser Chrome. If the action button is specific to a page, you can use a Page action. This can be controlled to only show up when it’s necessary. Browser actions are always visible. An extension cannot specify both a page and a browser action. You can use an image as the action icon, or use output from the Canvas API. Browser actions can have badges that communicate some information, say an unread messages count. When the user clicks on a page/browser action, you can show a tooltip.
  • 50. This is the Extensions page in Chrome. It shows you which extensions you have installed. You can disable or uninstall them, see their web page, allow them to run in Incognito mode. At the bottom is a link to the Google Chrome Extensions Gallery. At the top is an option to enable Developer mode.
  • 51. This is the Extensions page in Chrome. It shows you which extensions you have installed. You can disable or uninstall them, see their web page, allow them to run in Incognito mode. At the bottom is a link to the Google Chrome Extensions Gallery. At the top is an option to enable Developer mode.
  • 52. Desktop Notifications You can show Desktop Notifications, provided you requested permission to do this.
  • 53. This is the Extensions page in Chrome. It shows you which extensions you have installed. You can disable or uninstall them, see their web page, allow them to run in Incognito mode. At the bottom is a link to the Google Chrome Extensions Gallery. At the top is an option to enable Developer mode.
  • 54. History Bookmarks You can also interact with the browser history and the user’s bookmarks. Plus, you can override the History page to provide a better interface.
  • 55. Tabs Windows Chrome also lets you manipulate open tabs and windows. You can override the new tab page. You can’t override the Extensions page though, for obvious reasons.
  • 56. Publishing But, aside from all these capabilities, perhaps the most important thing is having other people use your extension! So far we’ve loaded extensions from your local machine. Let’s see how we can package those local files so that anybody can install your extension.
  • 57. Demo time You can pack your extension using the “Pack extension…” option on the Extensions page (in Developer mode). This takes the path to your extension and a possible private key file. The end result is a `.crx` file, which in essence is a signed ZIP file. You’ll also get a `.pem` file which contains the private key for your extension. This is important, the private key is used to sign the ZIP file, and Chrome will refuse to update your extension if the new extension file was not signed with the same private key.
  • 58. Gallery Chrome also has a Gallery where you can distribute your extension. They manage packaging and updating your extension, and will also keep track of the private key for you. This of course is the best place for your extension, though you’re free to host it yourself. In the latter case, you’ll have to set up some extra files on your server to support auto- updating of your extension.
  • 59. Questions? Mark Wubben supercollider.dk & novemberborn.net twitter.com/novemberborn Slides: 11born.net/swdc Licensed under Creative Commons Attribution-Share Alike 2.5 http://creativecommons.org/licenses/by-sa/2.5/dk/ And that concludes this talk. Thank you for your attention.
  • 60. Steve Peck James Kim Jon Fife Kevin Dooley F H Mira Matt Jones Jeff Kubina Many, many thanks to the wonderful people on Flickr who licensed their photos under Creative Commons. Photo by Jeff Kubina, http://flickr.com/photos/kubina/903033693/. CC-BY-SA 2.0.
  • 61. Now, as Matt Jones would put it, GET EXCITED and MAKE THINGS! Illustration by Matt Jones, CC-BY-SA-NC, http://www.flickr.com/photos/blackbeltjones/ 3365682994/.