Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Egy kiterjesztés elkészítése

 

Bevezető

Ez a tutoriál lépésröl lépésre elmagyarázza hogyan készíts egy alapvető kiterjesztést - ez a kiterjesztés egy "Hello, World!" feliratú státussávval bővíti a Firefox-ot.

Megjegyzés Ez a tutoriál a Firefox 1.5-ös vagy 2.0-ás verziójára vonatkozik. A korábbi verziókra más tutoriálok vonatkoznak.

A fejleszői környezet létesítése

Kibocsátásra kijelölt kiterjestéseket ZIP fájlokba, vagy xpi (ejtsd “zippy”) végződésü Köteg-ekbe csomagold. Az XPI fájl szerkezete a következő:

extension.xpi:
              /install.rdf                   
              /components/*  
              /components/cmdline.js                   
              /defaults/
              /defaults/preferences/*.js     
              /plugins/*                        
              /chrome.manifest                
              /chrome/icons/default/*       
              /chrome/
              /chrome/content/
     

Ezért az a legkönnyebb, ha ezen a módon tárolod a forráskódot, ha nem akarsz egy Makefájlt vagy egy shell skriptet írni ezek csomagolásához. Sőt, még akkor is, ha az utóbbi modszert választod, így könnyebbé válik a tesztelés, a Firefox 1.5-ösel kiszálított Add-on rendszer egyik tulajdonsága miatt.

Tehát, akkor kezdhetjünk is. Hozz létre egy mappát a lemezen, pl. C:\extensions\my_extension\ vagy ~/extensions/my_extension/ (Megjegyzés: használj kisbetüket) Ebben a mappában hozz létre egy chrome nevüt, amelyik egy content nevüt tartalmazzon. (Unix-féle rendszereken ezt könnyen el lehet érni a gyökérmappában végrehajtott mkdir -p chrome/content parancssal.)


angol szöveg So let's get started. Create a folder for your extension somewhere on your hard disk, e.g. <tt>C:\extensions\my_extension\</tt> or <tt>~/extensions/my_extension/</tt>. (note: use all lower case) Inside this folder create another folder called <tt>chrome</tt>, inside the <tt>chrome</tt> folder create a folder called <tt>content</tt>. (On Unix-like systems you can usually create both directories just by running <tt>mkdir -p chrome/content</tt> from within the extension's root directory.)

A kiterjesztés gyökérmappájában, a chrome mappa mellett, hozz létre két üres szövegfájlt. Az egyiket nevezd chrome.manifest-nek, a másikat install.rdf-nek.

angol szöveg Inside the '''root''' of your extension folder, alongside the <tt>chrome</tt> folder, create two new empty text files, one called <tt>chrome.manifest</tt> and the other called <tt>install.rdf</tt>.

Példa:

#!/bin/sh
h=$HOME/moExt
mkdir -p $h/my_extension/chrome/content
touch $h/my_extension/chrome.manifest $h/my_extension/install.rdf

További tancsokkal szolgál a Kiterjesztés fejlesztői környezet létesítése című cikk. angol szöveg More tips on setting up the development environment can be found in the article Setting up extension development environment.

A Manifest létrehozása és üzembe helyezése

Create the Install Manifest

Nyisd meg a gyökérmappában előzőleg létrehozott install.rdf fájlt és másold bele a következőt:

angol szöveg Open the file called <tt>install.rdf</tt> that you created at the top of your extension's folder hierarchy and put this inside:

<?xml version="1.0"?>

<RDF xmlns="https://www.w3.org/1999/02/22-rdf-syntax-ns#"
     xmlns:em="https://www.mozilla.org/2004/em-rdf#">

  <Description about="urn:mozilla:install-manifest">
    <em:id>[email protected]</em:id>
    <em:version>1.0</em:version>
    <em:type>2</em:type>
   
    <!-- Target Application this extension can install into, 
         with minimum and maximum supported versions. --> 
    <em:targetApplication>
      <Description>
        <em:id>{ec8030f7-c20a-464f-9b0e-13a3a9e97384}</em:id>
        <em:minVersion>1.5</em:minVersion>
        <em:maxVersion>2.0.0.*</em:maxVersion>
      </Description>
    </em:targetApplication>
   
    <!-- Front End MetaData -->
    <em:name>Sample!</em:name>
    <em:description>A test extension</em:description>
    <em:creator>Your Name Here</em:creator>
    <em:homepageURL>https://www.foo.com/</em:homepageURL>
  </Description>      
</RDF>
  • [email protected] - a kiterjesztés azonosítója. Ez egy érték, mely egyértelmüen azonosítja a kiterjesztést. Ennek az értéknek email formája van (ne a te email címed legyen). Egyértelmü legyen. Használhatsz egy GUID-et is. FIGYELEM: Ennek a paraméternek email formájúnak KELL lennie, de nem kell, hogy egy érvényes cím legyen. ([email protected])

This is some value you come up with to identify your extension in email address format (note that it should not be ''your'' email). Make it unique. You could also use a GUID. NOTE: This parameter MUST be in the format of an email address, although it does NOT have to be a valid email address. ([email protected])

  • <em:type>2</em:type> Az érték azt határozza meg, hogy ez (a 2.-es) egy kiterjesztést helyez üzembe. Ha egy témát szeretnél üzembe helyezni, ez az érték egy 4.-es. (lásd a Install Manifest#type-ot a többi kód gyanánt).

anglo szöveg declares that it is installing an extension. If you were to install a theme it would be 4 (see Install_Manifests#type for other type codes).

  • {ec8030f7-c20a-464f-9b0e-13a3a9e97384} - a Firefox alkalmazás azonosítója.
  • 1.5 - a Firefox legkisseb verziója, amelyel ez a kiterjesztés müködőképes. Ide a legkisseb verziót írd, amelyel teszeled és amelyhez javításokat írsz.

angol szöveg the minimum version of Firefox you're saying this extension will work with. Set this as the minimum version you're going to commit to testing and fixing bugs with.

  • 2.0.0.* - a legnagyobb Firefox verzió, amelyel a kiterjesztésed müködőképes. Ez maximum a legújabb verzió legyen! Ebben az esetben a "2.0.0.*" azt jelenti, hogy a kiterjesztés a Firefox 2.0.0.0-tól a 2.0.0.x-ig működőképes.

the maximum version of Firefox you're saying this extension will work with. Set this to be no newer than the newest currently available version! In this case, "2.0.0.*" indicates that the extension works with versions of Firefox 2.0.0.0 through 2.0.0.x. Azok a kiterjesztések, melyek a Firefox 1.5.0.x-es verziójára terveztettek, itt maximumként "1.5.0.*"-ot tartalmazzanak. <!-- Extensions designed to work with Firefox 1.5.0.x at the latest should set the maximum version to "1.5.0.*".

Lásd az Install Manifests címü cikket további tulajdonságok gyanánt. See Install Manifests for a complete listing of the required and optional properties.

Tárold a fájlt. Save the file.

A böngésző XUL-al való bövítése

A Firefox felhasználói felülete egy XUL és JavaScript-keverékben íródott. A XUL egy XML nyelvtan, amely a kezedbe adja a felhasználói felületet elemeit, azaz a gombokat, menüket, eszköztárakat, stb. Ezek müködőképességét pedig a JavaScript bisztosíja.

Ahoz, hogy a browser möködőképességét növeljed, a felhasználói felületet elemeit módosítanod kell. Tehát vagy hozzáadsz vagy megváltoztatsz egy elemet. Ahoz, hogy egy új elemet adj a felhasználói felületethez egy új XUL DOM elemet kell behelyettesítened a böngésző felületébe. A Scripttel pedig módosítod és event handler-ekkel (esemény kezelőkkel) bővíted ezeket.

A böngésző a browser.xul nevü XUL fajlba található (a $FIREFOX_INSTALL_DIR/chrome/browser.jar tartalmazza a content/browser/browser.xul-t) A browser.xul-ba megtalálhatjuk a státussávot, mely körülbelül igy néz ki:

<statusbar id="status-bar">
 ... <statusbarpanel>s ...
</statusbar>

A <statusbar id="status-bar"> egy "merge point" (azaz "egyesítő pont") a XUL Overlay számára.

angol szöveg === Extending the Browser with XUL === Firefox's user interface is written in XUL and JavaScript. XUL is an XML grammar that provides user interface widgets like buttons, menus, toolbars, trees etc. User actions are bound to functionality using JavaScript. To extend the browser, we modify parts of the browser UI by adding or modifying widgets. We add widgets by inserting new XUL DOM elements into the browser window, and modify them by using script and attaching event handlers. The browser is implemented in a XUL file called <tt>browser.xul</tt> (<tt>$FIREFOX_INSTALL_DIR/chrome/browser.jar</tt> contains <tt>content/browser/browser.xul</tt>). In browser.xul we can find the status bar, which looks something like this: &lt;statusbar id="status-bar"&gt; ... &lt;statusbarpanel&gt;s ... &lt;/statusbar&gt; <tt>&lt;statusbar id="status-bar"&gt;</tt> is a "merge point" for a XUL Overlay.

XUL Overlays

XUL Overlays are a way of attaching other UI widgets to a XUL document at run time. A XUL Overlay is a .xul file that specifies XUL fragments to insert at specific merge points within a "master" document. These fragments can specify widgets to be inserted, removed, or modified.

Example XUL Overlay Document

<?xml version="1.0"?>
<overlay id="sample" 
         xmlns="https://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
 <statusbar id="status-bar">
  <statusbarpanel id="my-panel" label="Hello, World"/>
 </statusbar>
</overlay>

The <statusbar> called status-bar specifies the "merge point" within the browser window that we want to attach to.

The <statusbarpanel> child is a new widget that we want to insert within the merge point.

Take this sample code above and save it into a new file called sample.xul inside the chrome/content folder you created.

For more information about merging widgets and modifying the user interface using Overlays, see below.

Chrome URIs

XUL files are part of "Chrome Packages" - bundles of user interface components which are loaded via chrome:// URIs. Rather than load the browser from disk using a file:// URI (since the location of Firefox on the system can change from platform to platform and system to system), Mozilla developers came up with a solution for creating URIs to XUL content that the installed application knows about.

The browser window is: chrome://browser/content/browser.xul Try typing this URL into the location bar in Firefox!

Chrome URIs consist of several components:

  • Firstly, the URI scheme (chrome) which tells Firefox's networking library that this is a Chrome URI. It indicates that the content of the URI should be handled as a (chrome). Compare (chrome) to (http) which tells Firefox to treat the URI as a web page.
  • Secondly, a package name (in the example above, browser) which identifies the bundle of user interface components. This should be as unique to your application as possible to avoid collisions between extensions.
  • Thirdly, the type of data being requested. There are three types: content (XUL, JavaScript, XBL bindings, etc. that form the structure and behavior of an application UI), locale (DTD, .properties files etc that contain strings for the UI's localization), and skin (CSS and images that form the theme of the UI)
  • Finally, the path of a file to load.

So, chrome://foo/skin/bar.png loads the file bar.png from the foo theme's skin section.

When you load content using a Chrome URI, Firefox uses the Chrome Registry to translate these URIs into the actual source files on disk (or in JAR packages).

Create a Chrome Manifest

For more information on Chrome Manifests and the properties they support, see the Chrome Manifest Reference.

Open the file called chrome.manifest that you created alongside the chrome directory at the root of your extension's source folder hierarchy.

Add in this code:

content     sample    chrome/content/

(Don't forget the trailing slash, "/"! Without it, the package won't be registered.)

This specifies the:

  1. type of material within a chrome package
  2. name of the chrome package (make sure you use all lowercase characters for the package name ("sample") as Firefox/Thunderbird doesn't support mixed/camel case in version 2 and earlier - bug 132183)
  3. location of the chrome packages' files

So, this line says that for a chrome package sample, we can find its content files at the location chrome/content which is a path relative to the location of chrome.manifest.

Note that content, locale and skin files must be kept inside folders called content, locale and skin within your chrome subdirectory.

Save the file. When you launch Firefox with your extension, (later in this tutorial), this will register the chrome package.

Register an Overlay

You need Firefox to merge your overlay with the browser window whenever it displays one. So add this line to your chrome.manifest file:

overlay chrome://browser/content/browser.xul chrome://sample/content/sample.xul

This tells Firefox to merge sample.xul into browser.xul when browser.xul loads.

Test

First, we need to tell Firefox about your extension. In the bad old days of Firefox 1.0 this meant packaging your extension as a XPI and installing it through the user interface, which was a real pain. Now, it's much simpler.

  1. Open your Profile Folder
  2. Open the extensions folder (create it if it doesn't exist)
  3. Create a new text file, and put the path to your extension folder inside, e.g. C:\extensions\my_extension\ or ~/extensions/my_extension/. Save the file with the id of your extension as its name, e.g. [email protected]

(Don't forget the trailing slash, "/"! Without it, the extension won't get registered.)

Now you're ready to test your extension!

Start Firefox. Firefox will detect the text link to your extension directory and install the Extension. When the browser window appears you should see the text "Hello, World!" on the right side of the status bar panel.

You can now go back and make changes to the .xul file, close and restart Firefox and they should appear.

These don't actually match the described extension and confuse people. -Nickolay CENTER> Image:Helloworld_tools_menu.PNG Image:Helloworld_extensions_wnd.PNG </CENTER

Important For those of you who are just just starting out with programming, please note that the files "chrome.manifest", "sample.xul" and "install.rdf" are usually default saved with ANSI encoding. THIS WILL NOT WORK, you have to change the encoding to Unicode because if you save it with ANSI encoding, it will save the file as, "install.rdf.txt".

Package

Now that your extension works, you can package it for deployment and installation.

Zip up the contents of your extension's folder (not the extension folder itself), and rename the zip file to have a .xpi extension. In Windows XP, you can do this easily by selecting all the files and subfolders in your extension folder, right click and choose "Send To -> Compressed (Zipped) Folder". A .zip file will be created for you. Just rename it and you're done!

On Mac OS X, you can right-click on the contents of the extension's folder and choose "Create Archive of..." to make the zip file. However, since Mac OS X adds hidden files to folders in order to track file metadata, you should instead use the Terminal, delete the hidden files (whose names begin with a period), and then use the zip command on the command line to create the zip file.

On Linux, you would likewise use the command-line Zip tool.

If you have the 'Extension Builder' extension installed it can compile the .xpi file for you (Tools -> Extension Developer -> Extension Builder). Merely navigate to the directory where your extension is (install.rdf etc.), and hit the Build Extension button. This extension has a slew of tools to make development easier.

Now upload the .xpi file to your server, making sure it's served as application/x-xpinstall. You can link to it and allow people to download and install it in Firefox. For the purposes of just testing our .xpi file we can just drag it into the extensions window via Tools -> Extensions, or Tools -> Add-ons in FireFox 2.

Installing from a web page

There are a variety of ways you can install extensions from web pages, including direct linking to the XPI files and using the InstallTrigger object. Extension and web authors are encouraged to use the InstallTrigger method to install XPIs, as it provides the best experience to users.

Using addons.mozilla.org

Mozilla Update is a distribution site where you can host your extension for free. Your extension will be hosted on Mozilla's mirror network to guarantee your download even though it might be very popular. Mozilla's site also provides users easier installation, and will automatically make your newer versions available to users of your existing versions when you upload them. In addition Mozilla Update allows users to comment and provide feedback on your extension. It is highly recommended that you use Mozilla Update to distribute your extensions!

Visit https://addons.mozilla.org/developers/ to create an account and begin distributing your extensions!

Note: Your Extension will be passed faster and downloaded more if you have a good description and some screenshots of the extension in action.

Registering Extensions in the Windows Registry

On Windows, information about extensions can be added to the registry, and the extensions will automatically be picked up the next time the applications starts. This allows application installers to easily add integration hooks as extensions. See Adding Extensions using the Windows Registry for more information.

More on XUL Overlays

In addition to appending UI widgets to the merge point, you can use XUL fragments within Overlays to:

  • Modify attributes on the merge point, e.g. <statusbar id="status-bar" hidden="true"/> (hides the status bar)
  • Remove the merge point from the master document, e.g. <statusbar id="status-bar" removeelement="true"/>
  • Control the position of the inserted widgets:
<statusbarpanel position="1" .../>

<statusbarpanel insertbefore="other-id" .../>

<statusbarpanel insertafter="other-id" .../>

Creating New User Interface Components

You can create your own windows and dialog boxes as separate .xul files, provide functionality by implementing user actions in .js files, using DOM methods to manipulate UI widgets. You can use style rules in .css files to attach images, set colors etc.

View the XUL documentation for more resources for XUL developers.

Defaults Files

Defaults files that you use to seed a user's profile with should be placed in defaults/ under the root of your extension's folder hierarchy. Default preferences .js files should be stored in defaults/preferences/ - when you place them here they will be automatically loaded by Firefox's preferences system when it starts so that you can access them using the Preferences API.

An example default preference file:

pref("extensions.sample.username", "Joe"); //a string pref
pref("extensions.sample.sort", 2); //an int pref
pref("extensions.sample.showAdvanced", true); //a boolean pref

XPCOM Components

Firefox supports XPCOM components in extensions. You can create your own components easily in JavaScript or in C++ (using the Gecko SDK).

Place all of your .js or .dll files in the components/ directory - they are automatically registered the first time Firefox runs after your extension is installed.

For more information see How to Build an XPCOM Component in Javascript, How to build a binary XPCOM component using Visual Studio and the Creating XPCOM Components book.

Application Command Line

One of the possible uses of custom XPCOM components is adding a command line handler to Firefox or Thunderbird. You can use this technique to run your extension as an application:

 firefox.exe -myapp

I should move the useful parts of this to the Command Line page. -Nickolay This is done by adding a component containing the function... function NSGetModule(comMgr, fileSpec) { return myAppHandlerModule; } This function is run by firefox each time firefox is started. Firefox registers the myAppHandlerModule's by calling its 'registerSelf()'. Then it obtains the myAppHandlerModule's handler factory via 'getClassObject()'. The handler factory is then used to create the handle using its 'createInstance(). Finally, the handle's 'handle(cmdline)' processes the command line cmdline's handleFlagWithParam() and handleFlag(). See Chrome: Command Line and a forum discussion for details.

Localization

To support more than one language, you should separate strings from your content using entities and string bundles. It is much easier to do this while you are developing your extension, rather than come back and do it later!

Localization information is stored in the locale directory for the extension. For example, to add a locale to our sample extension, create a directory named "locale" in chrome (where the "content" directory is located) and add the following line to the chrome.manifest file:

locale sample en-US chrome/locale/en-US/

To create localizable attribute values in XUL, you put the values in a .ent (or a .dtd) file, which should be placed in the locale directory and looks like this:

<!ENTITY  button.label     "Click Me!">
<!ENTITY  button.accesskey "C">

And then include it at the top of your XUL document (but underneath the "<?xml version"1.0"?>") like so:

<!DOCTYPE window SYSTEM "chrome://packagename/locale/filename.ent">

where window is the localName value of the root element of the XUL document, and the value of the SYSTEM property is the chrome URI to the entity file. For our sample extension, the root element is overlay.

To use the entities, modify your XUL to look like this:

<button label="&button.label;" accesskey="&button.accesskey;"/>

The Chrome Registry will make sure the entity file is loaded from the localization bundle corresponding to the selected locale.

For strings that you use in script, create a .properties file, a text file that has a string on each line in this format:

key=value

and then use nsIStringBundleService/nsIStringBundle or the <stringbundle> tag to load the values into script.

Understanding the Browser

Use the DOM Inspector (not part of the Standard Firefox installation, you must reinstall with the Custom install path and choose Developer Tools if there is not a "DOM Inspector" item in your browser's Tools menu) to inspect the browser window or any other XUL window you want to extend.

Use the point-and-click node finder button at the top left of the DOM Inspector's toolbar to click on a node in the XUL window visually to select it. When you do this the DOM inspector's DOM hierarchy tree view will jump to the node you clicked on.

Use the DOM Inspector's right side panel to discover merge points with ids that you can use to insert your elements from overlays. If you cannot discover an element with an id that you can merge into, you may need to attach a script in your overlay and insert your elements when the load event fires on the master XUL window.

Debugging Extensions

Analytical Tools for Debugging

  • The DOM Inspector - inspect attributes, DOM structure, CSS style rules that are in effect (e.g. find out why your style rules don't seem to be working for an element - an invaluable tool!)
  • Venkman - set breakpoints in JavaScript and inspect call stacks
  • arguments.callee.caller in JavaScript - access a function's call stack

printf debugging

  • Run Firefox with -console at the command line and use dump("string") (see the link for details)
  • Use nsIConsoleService to log to the JavaScript console

Advanced debugging

Quick Start

You can use the Extension Wizard online tool to generate a simple extension to work with.

A Hello World extension similar to what you can generate with the Extension Wizard is explained line-by-line in another tutorial from MozillaZine Knowledge Base.

Further information

Dokumentum címkék és a közreműködők

Címkék: 
 Ezen oldal közreműködői: teoli, fscholz, Solon
 Utoljára frissítve: teoli,