1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Creating Applications with Mozilla-Chapter 5. Scripting Mozilla- P4 docx

22 337 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Creating XPCOM objects in script
Thể loại Chapter
Định dạng
Số trang 22
Dung lượng 48,63 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Using JavaScript and XPConnect, you can create instances of these components and use their methods and properties as you do any regular JavaScript object, as described here.. The second

Trang 1

Chapter 5 Scripting Mozilla- P4

Figure 5-4 How XPConnect fits into the application model

In Mozilla, XPConnect is the bridge between JavaScript and XPCOM

components The XPConnect technology wraps natively compiled

components with JavaScript objects XPCOM, Mozilla's own cross-platform component technology, is the framework on top of which these scriptable components are built Using JavaScript and XPConnect, you can create instances of these components and use their methods and properties as you

do any regular JavaScript object, as described here You can access any or all of the functionality in Mozilla in this way

Trang 2

Chapter 8 describes more about the XPConnect technology and how it

connects components to the interface It also describes the components

themselves and their interfaces, the XPCOM technology, and how you can create your own XPCOM components

5.4.1.1 Creating XPCOM objects in script

Example 5-10 demonstrates the creation and use of an XPCOM component

in JavaScript In this example, the script instantiates the filepicker

object and then uses it to display a file picker dialog with all of the file filters

selected To run this example, add the function to your xfly.js file and call it

from an event handler on the "New" menu item you added in Example 3-5

Example 5-10 Scriptable component example

// chooseApp: Open file picker and prompt user for application

fp.init( this.mDialog,

this.getString( "chooseAppFilePickerTitle" ), nsIFilePicker.modeOpen );

fp.appendFilters( nsIFilePicker.filterAll );

Trang 3

if ( fp.show( ) == nsIFilePicker.returnOK &&

}

Note the first two lines in the function and the way they work together to create the fp filepicker object The first line in the function assigns the

name of the nsFilepicker interface to the nsIFilePicker variable in

JavaScript This variable is used in the second line, where the instance is created from the component to specify which interface on that component should be used Discovering and using library interfaces is an important aspect of XPCOM, where components always implement at least two

interfaces

In Example 5-11, an HTML file (stored locally, since it wouldn't have the required XPConnect access as a remote file because of security boundaries) loaded in Mozilla instantiates a Mozilla sound component and plays a sound with it Go ahead and try it

Example 5-11 Scripting components from HTML

<head>

<title>Sound Service Play Example</title>

Trang 4

sample =

sample.QueryInterface(Components.interfaces.nsISound);

const SND_NETWORK_STD_CID =

"@mozilla.org/network/standard-url;1";

const SND_I_URL = "nsIURL";

const SND_URL = new

Trang 5

<form name="form">

<input type="button" value="Play Sound"

onclick="play();">

</form>

As in Example 5-10, the classes[ ] array on the special Mozilla

Components object refers to a particular component in this case, the sound component by contract ID All XPCOM objects must have a

contract ID that uniquely identifies them with the domain, the component name, and a version number ["@mozilla.org/sound;1"],

respectively See the Section 8.1.5 section in Chapter 8 for more information about this

5.4.1.2 Finding components and interfaces

Most components are scripted in Mozilla In fact, the challenge is not to find cases when this scripting occurs (which you can learn by searching LXR for the Components), but to find Mozilla components that don't use scriptable components Finding components and interfaces in Mozilla and seeing how they are used can be useful when writing your own application

The Mozilla Component Viewer is a great tool for discovering components and provides a convenient UI for seeing components and looking at their interfaces from within Mozilla The Component Viewer can be built as an extension to Mozilla (see "cview" in the extensions directory of the Mozilla source), or it can be downloaded and installed as a separate XPI from

http://www.hacksrus.com/~ginda/cview/ Appendix B describes the

Component Viewer in more detail

Trang 6

Commonly used XPCOM objects in the browser and other Mozilla

applications include file objects, RDF services, URL objects, and category managers

5.4.1.3 Selecting the appropriate interface from the component

In all cases, the way to get the object into script is to instantiate it with the special classes object and use the createInstance( ) method on the class to select the interface you want to use These two steps are often done together, as in the following example, which gets the component with the contract ID ldap-connection;1, instantiates an object from the

nsILDAPConnection interface, and then calls a method on that object:

var connection = Components.classes

["@mozilla.org/network/ldap-connection;1"]

createInstance(Components.interfaces.nsILDAPConnection);

connection.init(queryURL.host, queryURL.port, null,

generateGetTargetsBoundCallback( ));

These two common processes getting a component and selecting one of its interfaces to assign to an object can also be separated into two different statements:

// get the ldap connection component

Trang 7

var connection = Components.classes

// call the init( ) method on that object

connection.init(queryURL.host, queryURL.port, null, generateGetTargetsBoundCallback( ));

Mozilla constantly uses these processes Wherever functionality is organized into XPCOM objects (and most of it is), these two statements bring that functionality into JavaScript as high-level and user-friendly JavaScript

objects

5.5 JavaScript Application Code

There are two ways to use JavaScript in the third, deepest level of

application programming The first is to organize your JavaScript into

libraries so your functions can be reused, distributed, and perhaps

collaborated upon

The second way is to write a JavaScript component, create a separate

interface for that component, and compile it as an XPCOM component

whose methods and data can be accessed from XPConnect (using

JavaScript) This kind of application programming is described in Chapter 8,

Trang 8

which includes examples of creating new interfaces, implementing them in JavaScript or C++, and compiling, testing, and using the resulting

component in the Mozilla interface

This section introduces the library organization method of JavaScript

application programming The JSLib code discussed here is a group of

JavaScript libraries currently being developed by Mozilla contributors and is especially useful for working with the XPFE and other aspects of the

Mozilla application/package programming model When you include the right source files at the top of your JavaScript and/or XUL file, you can use the functions defined in JSLib libraries as you would use any third-party library or built-in functions You may even want to contribute to the JSLib project yourself if you think functionality is missing and as your Mozilla programming skills grow

5.5.1 JavaScript Libraries

The open source JSLib project makes life easier for developers The JSLib package implements some of the key XPCOM components just discussed and wraps them in simpler, JavaScript interfaces, which means that you can use the services of common XPCOM components without having to do any

of the instantiation, interface selection, or glue code yourself Collectively, these interfaces are intended to provide a general-purpose library for Mozilla application developers To understand what JSLib does, consider the

following short snippet from the JSLib source file jslib/io/file.js, which implements a close( ) function for open file objects and provides

a handy way to clean up things when you finish editing a file in the

filesystem

Trang 10

if(this.mFileChannel) delete this.mFileChannel;

if(this.mInputStream) delete this.mInputStream;

if(this.mTransport) delete this.mTransport;

Trang 11

}

To use the close method as it's defined here, import the file.js source file into your JavaScript, create a file object (as shown in the examples below), and call its close( ) method

xpcshell

Most examples in this section are in xpcshell, but using these libraries in your user interface JavaScript is just as easy You can access these libraries from a XUL file, as the section Section 5.5.1.6, later in this chapter,

demonstrates

xpcshell is the command-line interpreter to JavaScript and XPConnect This shell that uses XPConnect to call and instantiate scriptable XPCOM

interfaces It is used primarily for debugging and testing scripts

To run xpcshell, you need to go to the Mozilla bin directory or have that folder in your PATH For each platform, enter:

$ /run-mozilla.sh /xpcshell

Trang 12

To see the available options for xpcshell, type this:

$ /run-mozilla.sh /xpcshell help

objects), performing necessary error checking, and ensuring proper usage

To use a function like the one just shown, simply include the source file you need in your XUL:

technology, described in Chapter 6

Trang 13

Using your Mozilla browser, go to http://jslib.mozdev.org/installation.html and click the installation hyperlink The link uses XPInstall to install JSLIB and make it available to you in Mozilla To test whether it is installed

properly, type the following code in your shell:

./mozilla -chrome chrome://jslib/content/

You should see a simple window that says "welcome to jslib."

5.5.1.2 The JSLib libraries

Currently available JavaScript functions in the JSLib package are divided into different modules that, in turn, are divided into different classes defined

in source files such as file.js, dir.js, and fileUtils.js Table 5-1 describes

the basic classes in the JSLib package's I/O module and describes how they are used

Table 5-1 JSLib classes

Class / (filename) Description

File / (file.js)

Contains most routines associated with the File object (implementing nsIFile) The library is part of the jslib I/O module

FileUtils / (fileUtils.js) The chrome registry to local file path

conversion, file metadata, etc

Dir / (dir.js) Directory creation; variations of

directory listings

Trang 14

Class / (filename) Description

DirUtils / (dirUtils.js)

Paths to useful Mozilla directories

and files such as chrome, prefs,

bookmarks, localstore, etc

5.5.1.3 Using the File class

The JSLib File class exposes most local file routines from the nsIFile

interface The File class is part of the JSLib I/O module, and is defined in jslib/io/file.js Here is how you load the library from xpcshell:

Trang 15

true

js>

Note that file.js loads filesystem.js in turn The class

FileSystem in filesystem.js is the base class for the File object You can

also load file.js by using the top-level construct JS_LIB_PATH:

Trang 16

js> f.open( ); // open the file again and

js> f.read( ); // read back the data

// you can also use default flag 'r' for reading

this is line #1

js> f.close( );

You can also assign the contents of the file to a variable for later use,

iterative loops through the file contents, or updates to the data:

Trang 17

// rename the file

5.5.1.4 Using the FileUtils class

To create an instance of the FileUtils class, use the FileUtils

The difference between using the File and FileUtils interfaces is that

methods and properties on the latter are singleton and require a path

argument, while the FileUtils utilities are general purpose and not bound to any particular file The FileUtils interface has several handy I/O utilities for

converting, testing, and using URLs, of which this example shows a few:

Trang 18

js> fu.exists('/tmp');

true

// convert a chrome path to a url

js> fu.chromeToPath('chrome://jslib/content/'); /usr/src/mozilla/dist/bin/chrome/jslib/jslib.xul // convert a file URL path to a local file path js> fu.urlToPath('file:///tmp/foo.dat');

/tmp/foo.dat

Most methods on the FileUtils objects are identical to the methods found in file.js, except they require a path argument Another handy method in the FileUtils class is spawn, which spawns an external executable from the operating system It's used as follows:

js> var fu=new FileUtils( );

js> fu.exists('/tmp');

true

Trang 19

5.5.1.5 Using the Dir class

The Dir class is custom-made for working with directory structures on a local filesystem To create an instance of the Dir class, call its constructor and then its help method to see the class properties:

js> var d = new Dir('/tmp');

Trang 20

The methods all work like those in the File and FileUtils classes, so you can append a new directory name to the object, see if it exists, and

create it if (it does not) by entering:

5.5.1.6 Using the DirUtils class

Note that some methods in the DirUtils class cannot be called from

xpcshell and instead must be called from a XUL window into which the proper JSLib source file was imported The following XUL file provides two buttons that display information in textboxes about the system directories:

Trang 21

xmlns:html="http://www.w3.org/1999/xhtml" id="dir-utils-window"

}

function getMozDir( ) {

md = du.getMozHomeDir( );

textfield2 = document.getElementById("tf2"); textfield2.setAttribute("value", md);

Trang 22

<textbox id="tf1" value="chrome dir" />

Ngày đăng: 14/12/2013, 12:15

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN