Download presentation
Presentation is loading. Please wait.
Published byRuth Clark Modified over 8 years ago
1
Mozilla Firefox Extension Development Course 1: Basic Littlebtc OSSF Workshop / MozTW Acitivity The text of the slide is under CC-BY-SA-3.0. Most photos are under CC-BY-SA compatible license, while screenshots / logos are under Fair Use. Code is under MIT license.
2
Note This slide is partialy based on Firefox addons developer guide (CC-BY-SA-2.1JP) https://developer.mozilla.org/En/Firefox_addons _developer_guide/ Original authors: https://developer.mozilla.org/En/Firefox_addons _developer_guide/ – Hideyuki Emura Hideyuki Emura – Hiroshi "Piro" Shimoda Hiroshi "Piro" Shimoda – Taiga Gomibuchi Taiga Gomibuchi – Taro Matsuzawa Taro Matsuzawa – Yutaka Kachi Yutaka Kachi
3
Suggested Reading Firefox addons developer guide (CC-BY-SA- 2.1JP) https://developer.mozilla.org/En/Firefox_add ons_developer_guide/ https://developer.mozilla.org/En/Firefox_add ons_developer_guide/ Firefox 3 ではじめる拡張機能開発 (Japanese) http://gihyo.jp/dev/feature/01/firefox-addons by Gomita http://gihyo.jp/dev/feature/01/firefox-addons
4
About Speaker A undergraduate, a web designer, etc.
5
NicoFox ~5000 Users
6
(PTT: ybite)
7
http://littlebtc.blogspot.com
8
Introduction to Extension Which makes Firefox better
9
Extensions One of the “Add-ons”: – Extensions, Themes, Plugin “Extend” your browser – Provide more features – Fix some problem – Integrate with sites or applications
10
Extensions with Single Feature… Locationbar 2 Hide Menubar (Made in Taiwan!) After Press Alt
11
Extensions with Feature Enhancements NoScript
12
Web Application Integration TwitterFox GmailManager Forestfox S3Fox (For Amazon S3)
13
Extensions with New Feature(s) Adblock Plus New Tong Wen Tang – Conversion between Chinese characters Greasemonkey
14
Extensions with New Feature(s) IE Tab (Made in Taiwan!) Stylish (Custom CSS for every site & user interface) FireGuestures Andmore!
15
Application Level Sage Scrapbook Firebug
16
One trick Together with Foxkeh Glasser – Apply Vista / 7 Aero Glass in toolbar
17
Ways to custom your Firefox? MethodWebsiteApplication (Firefox, …) User Style Sheets (CSS)UserContent.css, StylishUserChrome.css User Script (JavaScript)Bookmarklet, GreasemonkeyUserChrome.js ExtensionsEasy but powerful Themes(Not supported)Very flexible
18
DIVE INTO EXTENSIONS Next:
19
About Mozilla Technology Why we can extend Firefox easily Photo: http://www.flickr.com/photos/ews/2603070503/http://www.flickr.com/photos/ews/2603070503/ CC-BY-2.0 by JP Puerta
20
This is the Firefox…
21
… and this is part of the the “Main Browser Window”.
22
Wait? Wait! Is this HTML / JavaScript? => No, but something similar to this
23
XUL Rendered by Gecko Engine “Write” Interface in an XML text format – Just Like write web pages in HTML Cross-platform interface elements The idea may be similar to Adobe’s MXML (Flex) and Microsoft’s XAML (WPF) XML User Interface Language THERE IS NO DATA. THERE IS ONLY XUL.
24
XUL Periodic Table http://www.hevanet.com/acorbin/xul/top.xul
25
CSS It’s true! CSS can also modify user interface’s style For example: Toolbar icon
26
JavaScript It’s true… again! Handle the command in the interface Almost like what it is on AJAX websites – XMLHTTPRequest, DOM, … But able to access some core API... So it is more dangerous alert(‘Hello World!’);
27
XPCOM Cross Platform Component Object Model The core, or the “black box” of Firefox Very similar to Microsoft’s COM A cross-platform API that can be extended Some API may allow access from JavaScript
28
Above all… XPCOM is the “brain” XUL is the “skeleton” JavaScript is the “muscle” CSS is the “skin”
29
Break #1 Try to Install some extensions on your Firefox! And remember to install our tutorial extensions set
30
Break #1 Don't forget a little set up:
31
Go Writing XUL From the very beginning
32
Use a tool to help you
33
Real-time XUL Editor Beware!
34
Some common attribute Identifier: id Classes: class Style: style, width, height, flex – We will explain flex later disabled="true" – In.NET, it is Enabled=“False” ;p
35
– Attributes value control (explain later) accesskey: Used for Alt+…
36
– Attributes id value type: – number/password – timed/search rows/cols size multiline: true/false readonly: true/false – Events onchange <textbox value="Add texts here!“ multiline="true" rows="3" cols="12" />
37
, again controls element in : When clicking on the specific label, will focus on the control with specific id. <textbox id="txt" value="Add texts here!" multiline="true" rows="3" />
38
Attributes – label Beware: but ! – accesskey – Image Events – oncommand: beware! (though onclick can be OK, but oncommand is usually used in XUL)
39
Example With a little scripting <button label="Test" accesskey="S" oncommand="alert('hello!');" />
40
Layout controls: boxes & flex : Horizontal Box : Vertical Box : Group Box (can have a ) : Like flex (flexibility): An integer attribute in control elements, which indicates the element in the box should automatically change its width/height to fit box/window's size. – If there is multiple elements, elements with larger flex values will be larger than ones with lower flex values.
41
Boxes & flex: example http://gist.github.com/108776
42
Grid & Groupbox: Example http://gist.github.com/108802
43
Example, again http://gist.github.com/108791 <button label="OK" oncommand="alert('Hello, ' + document.getElementById('name').value + '!');" />
44
Script in XUL … Will be used widly later
45
Checkbox / Radio Common: label/accesskey – checked Radio: use a to contain them – onselect: Fire when selection changed selectedIndex, selectedItem – selected Note: oncommand will fire in a strange time! :
46
Checkbox / Radio
47
Menus In XUL, the following are similar!
48
Menu: Can be used by,, or Or anything with popup="id" Or anything with context="id"
49
(I) In a
50
(II) For :
51
(III) For popup="x" or context="x":
52
More complex For Popup / Menu mode: – can set oncommand to handle the command – It can be "checked" (like most menu) We will see a lot of these later ;)
53
A quiet different type of window Have default buttons! – – Buttons can be accept, cancel, help, disclosure, extra1, extra2 Events: ondialogxxx
54
example <dialog id="mydialog" title="Dialog Example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" buttons="accept,cancel" buttonlabelcancel="Cancel" buttonlabelaccept="Send" ondialogaccept="alert('Thank you, ' + document.getElementById('name').value + '!');" ondialogcancel="alert('canceled!');">
55
Result
56
Scripting: From the very beginning… alert('Hello Scripting in XUL!');
57
Load / unload – Good, but sometimes you won't have chance to modify onload window.addEventListener('load', onLoad, false); window.addEventListener('unload', onUnload, false); Why unload? ==> We usaually need to release unneeded things
58
So we can… <![CDATA[ window.addEventListener('load', function() { document.getElementById('Hello').value="Hello World!"; }, false); ]]>
59
LET'S HAVE A LUNCH! Thank you!
60
“Create Project” Setup the environment
61
Some recommended extensions Extension Developer: https://addons.mozilla.org/firefox/addon/743 4 which helps you set up the environment, doing extension packaging and find something useful https://addons.mozilla.org/firefox/addon/743 4
62
Some recommended extensions Console 2 Change Error Console, Speed Up Your Debug Speed
63
Some recommended extensions DOM Inspector Watch the structure of webpages or XUL pages
64
A very simple extension structure this-is-a-extension@moztw.org – install.rdf -- Your Addons info – chrome.manifest -- Your file paths to register into "Chrome" – content XULs and JSs… – defaults preferences – skin -- CSS
65
Check our testing extension Go %APPDATA%\Mozilla\Firefox\Profiles\xxxxxxxx.default\extensions\extension-tutorial- may09@moztw.org Check the install.rdf and chrome.manifest!
66
install.rdf <RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> extension-tutorial-may09@moztw.org MozTW 擴充套件課程用教學套件 0.1 5/9 和 5/23 的教學所使用! Littlebtc 2 {ec8030f7-c20a-464f-9b0e-13a3a9e97384} 3.0 3.6a1pre
67
Explain em:id – identical to the folder name – Unique ID to your extension – Can be in Email format or GUID format em:version em:type – 2: Extensions em:targetApplication – Set compatible application – Application can be identified with UUID, which can be also Email or GUID format. For example: Firefox is {ec8030f7-c20a-464f-9b0e-13a3a9e97384} Songbird is songbird@songbirdnest.com
68
How about !!@#$%^&? L10n? – Set Multiple Applications? – A lot of For details: https://developer.mozilla.org/en/Install_Manifests https://developer.mozilla.org/en/Install_Manifests See a complex example (My NicoFox install.rdf) http://code.google.com/p/nicofox/source/brows e/trunk/install.rdf http://code.google.com/p/nicofox/source/brows e/trunk/install.rdf
69
chrome.manifest contenttutorial content/ First is the "instructions": content/locale/skin/overlay/# (comment) deciding what to do content instructions: content packagename paths/to/files/ [flags] – Will Register paths/to/files in chrome://packagename/content !
70
chrome.manifest locale instruction: locale packagename localename paths/to/files/ [flags] – loacle is use to store l10n files, ex: locale tutorial zh-TW locale/zh-TW/ skin instruction: skin packagename skinname paths/to/files/ [flags] – skin is used to store skin files (CSS/pictures) skin tutorial classic/1.0 skin/
71
chrome.manifest overlay instruction: overlay chrome://to-be-overlaid chrome://overlay [flags] – Use for XUL overlays – "ADD SOMETHING" in the existing XUL – So we can do a lot of things in our browser window! overlay chrome://browser/content/browser.xul chrome://tutorial/content/overlay.xul For more, see: https://developer.mozilla.org/en/Chrome_Registrationhttps://developer.mozilla.org/en/Chrome_Registration
72
Go and see chrome://tutorial/content/test.xul – Do you see a "Hello World" ?
73
Create another profile (optional) start "" "%ProgramFiles%\Mozilla Firefox\firefox.exe" -no-remote -P dev – no-remote allows multiple profile at a time – -P dev means open a “dev” profile
74
Go overlay Change the browser window (http://www.flickr.com/photos/ybite/367039657/ CC-BY-SA-2.0 by ybite)http://www.flickr.com/photos/ybite/367039657/
75
At beginning, overlay.xul:
76
You need to know your enemy chrome://browser/content/browser.xul id="status-bar" id="main-menubar" id="menu_ToolsPopup" id="navigator- toolbox "
77
Add an item in Tools Menu
78
How to test? After disabling XUL cache, open a new window and overlay will work Or using Extension Developer to Reload All Chrome (Not suggested)
79
Add Item to the statusbar <statusbarpanel id="tutorial-custom-statusbar" class="statusbarpanel-iconic-text" label="Mybar" tooltiptext="It is my statusbar!" hidden="false" src="chrome://tutorial/skin/sport_basketball.png" oncommand="alert('Hello!');" /> Class: statusbarpanel-iconic-text: Icon & text statusbarpanel-iconic: Icon only statusbarpanel-menu-iconic: icon & popup menu
80
Custom Toolbar Button or a new Toolbar? Custom Toolbar Button: https://developer.mozilla.org/en/Creating_too lbar_buttons https://developer.mozilla.org/en/Creating_too lbar_buttons Create a Toolbar: http://www.borngeek.com/firefox/toolbar- tutorial/ http://www.borngeek.com/firefox/toolbar- tutorial/
81
Localization Preparation in XUL Before : Add a file zh-TW/tutorial.dtd: Add a file en-US/tutorial.dtd: Change the overlay.xul: label="&tutorial.hello;"
82
L10n normal tips Entities naming: – xxxxx.label – xxxxx.accesskey Remember to l10n as most as you can If your strings consists of variable value, try JavaScript way (explain later)
83
JavaScript time Basic JavaScript technique in Extension development (http://www.flickr.com/photos/nicksieger/280662871/ CC-BY-SA-2.0 by nicksieger)http://www.flickr.com/photos/nicksieger/280662871/
84
Review: DOM Tree parentNodepreviousSibling element firstChild lastChild nextSibling
85
Review: Some Simple DOM Find elements – id: document.getElementById(‘…’) – class: document.getElementsByClassName(‘…’) (Support Firefox3+ / Gecko 1.9+ only Workaround: XPath :D) Work with elements – element.style.xxx; – element.disabled = true; – element.setAttribute(‘disabled’, true); – var value = element.getAttribute(‘value’);
86
Add Script code in our overlay <script type="application/x-javascript" src="chrome://tutorial/content/overlay.js" /> Insert right after
87
overlay.js var moztw_tutorial = { onLoad: function() { // Fire when browser window loading }, onUnload: function() { // Fire when browser window unloading } }; window.addEventListener('load', moztw_tutorial.onLoad, false); window.addEventListener('unload', moztw_tutorial.onUnload, false);
88
Why use a object to wrap everything? The global object may be used by more than 50 extensions (so easy to conflict!) So wrap everything in an object is a safe way Some better implementations: – http://blogger.ziesemer.com/2007/10/respecting- javascript-global-namespace.html http://blogger.ziesemer.com/2007/10/respecting- javascript-global-namespace.html – http://www.softwareishard.com/blog/planet- mozilla/firefox-extensions-global-namespace- pollution/ http://www.softwareishard.com/blog/planet- mozilla/firefox-extensions-global-namespace- pollution/
89
Code snippets Open a XUL Dialog window.openDialog('chrome://tutorial/content/test.xul', 'chrome,centerscreen,dialog=no,resizable=yes '); – chrome: needed for chrome-level window – dialog=no: needed if it is not a – resizable=yes: can it be resize? – modal: will it lock the outer window? Window size? – Define it on your XUL window CSS
90
Sending data A very complex job! There exists some way like using the window.openDialog to send https://developer.mozilla.org/en/Working_wit h_windows_in_chrome_code https://developer.mozilla.org/en/Working_wit h_windows_in_chrome_code https://developer.mozilla.org/en/Code_snippe ts/Interaction_between_privileged_and_non- privileged_pages https://developer.mozilla.org/en/Code_snippe ts/Interaction_between_privileged_and_non- privileged_pages
91
Try JavaScript Shell This has the chrome privileges
92
Coping with the page Can we cope with the our viewing content in our browser? Yes, But Strictly Limited
93
Getting document of currently selected tab content.document or gBrowser.selectedBrowser.contentDocument So you can modify the content! The following code is a little dirty! fixIt: function() { if (content.document) { var h1 = content.document.getElementsByTagName('h1'); if (h1 && h1.length > 0) { h1[0].innerHTML = "Test"; } }
94
Get JavaScript variable in currently selected tab … Are You sure? – It can be very dangerous – And it is very hard Try Greasemonkey and understand unsafeWindow carefully – It has a compiler to make your userscript an independent xpi
95
Tab browser related? https://developer.mozilla.org/En/Code_snippe ts/Tabbed_browser https://developer.mozilla.org/En/Code_snippe ts/Tabbed_browser It has a lot of data, and very useful!
96
XPCOM You will be able to use some XPCOM in the following way: – Instance: var file = Components.classes["@mozilla.org/file/local;1"]. createInstance(Components.interfaces.nsILocalFile); file.initWithPath("D:\\doggy.txt"); – Usually, Cc = Components.classes, Ci = Components.interfaces – Service: var bookmarksSvc = Cc["@mozilla.org/browser/nav-bookmarks- service;1"]. getService(Ci.nsINavBookmarksService);
97
What can I do with XPCOM? File access: nsILocalFIle Cross-site XMLHTTPRequest: nsIXMLHTTPRequest Advanced window operations: nsIWindowMediator Access places database (Firefox3+ / Gecko 1.9+): nsINavBookmarksService, nsITaggingService, … Access password manager: nsILoginManager (Fx3+/Gecko1.9+) Save pages into files: nsIPersist Etc…
98
JS l10n ways (I) You need a.properties file put locale/en-US/tutorial.properties: hello=Hello World! And locale/zh-TW/tutorial.properties: hello= 哈囉世界!
99
JS l10n ways (II) In overlay.xul, add: Now you can access hello locale in document.getElementById('tutorial-bundle').getString('hello');
100
Full l10n examples I will add two new entities in.dtd (XUL-l10n) Then, modify the overlay.xul: And
101
Full l10n examples (II) Then, the overlay.js: hello: function() { alert( document.getElementById('tutorial- bundle').getString('hello')); }
102
Example: TagHelper++ Improve Gomita's TagHelper example Make it more easy and accurate A complete demo for JavaScript, XUL and XPCOM!
103
Our Target Select the text Right-click to add tag
104
First step Setup the developing environment
105
Overlay: popup menu <menuitem id="taghelper2-menuitem" label="&taghelper2.menuItem.label;" accesskey="&taghelper2.menuItem.accesskey;" oncommand="taghelper2.addTags();" />
106
Overlay: JavaScript onLoad: function() { // Fire when browser window loading var contextMenu = document.getElementById("contentAreaContextMenu"); if (contextMenu) { contextMenu.addEventListener("popupshowing", taghelper2.popupShowing, false); } }, popupShowing: function(e) { var item = document.getElementById("taghelper2-menuitem"); if (gContextMenu.isContentSelected) { // Popup will show when selected item.hidden = false; } else { item.hidden = true; } },
107
Overlay: JavaScript (II) addTags: function() { // Check selection var selection = window.content.getSelection(); var texts = []; for (var i = 0; i < selection.rangeCount; i++) { var text = selection.getRangeAt(i).toString(); // Trim text = text.replace(/^\s/,'').replace(/\s$/,''); texts.push(text); } var text = texts.join(","); selection.removeAllRanges(); // Open Dialog var params = {text: text, url: window.content.document.location.href, title: window.content.document.title}; window.openDialog("chrome://taghelper2/content/taghelper2.xul", "", "chrome,centerscreen,modal", params); }
108
The Dialog <dialog title="&taghelper2.dialog.title;" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" buttons="accept,cancel" onload="taghelper2Dialog.onLoad();" ondialogaccept="return taghelper2Dialog.addTags();" >
109
The Script var Cc = Components.classes; var Ci = Components.interfaces; var taghelper2Dialog = { url: null, title: null, onLoad: function() { // Receive Arguments if (window.arguments[0] && window.arguments[0].text) { document.getElementById('tags').value = window.arguments[0].text; this.url = window.arguments[0].url; this.title = window.arguments[0].title; } },
110
The Script (II) addTags: function() { try { var bookmarkServ = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].getService(Ci.nsINavBookmarksService); var uri = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService).newURI(this.url, null, null); /* Check if it was in bookmark */ var checkArray = bookmarkServ.getBookmarkIdsForURI(uri, {}); if (checkArray.length < 1) { var bookmarkId = bookmarkServ.insertBookmark(bookmarkServ.unfiledBookmarksFolder, uri, -1, ""); bookmarkServ.setItemTitle(bookmarkId, this.title); } /* Add tag to places */ var taggingServ = Cc["@mozilla.org/browser/tagging-service;1"].getService(Ci.nsITaggingService); taggingServ.tagURI(uri, [document.getElementById('tags').value], 1 ); return true; } catch (e) { alert(e); return true; } }, };
111
Result
112
XPI Package Spread your extension!
113
XPI packaging, the easiest way Zip your extensions Make sure install.rdf & chrome.manifest is in the first level of zip files Rename the file to xxx.xpi And you are done!
114
Advanced: pack a.jar for chrome files File structure: – chrome taghelper2.jar (a zip file) – content » … – locale » … – skin » … The correspoding chrome.manifest fix: before: locale/zh-TW/ after: chrome/taghelper2.jar!/locale/zh-TW/
115
Scripts available build.sh http://kb.mozillazine.org/Bash_build_script Create XPI with inner JAR attached http://kb.mozillazine.org/Bash_build_script
116
Send it to a public website Spread your.xpi file Or, use Mozilla Add-ons – A good add-ons hosting – Strict review process – Public extension will have automatically update
117
THANK YOU!
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.