1. Trang chủ
  2. » Kinh Doanh - Tiếp Thị

Hacking Firefox ™ More Than 150 Hacks, Mods, and Customizations phần 8 pps

45 197 0

Đ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 đề Hacking Firefox ™ More Than 150 Hacks, Mods, and Customizations Part 8
Chuyên ngành Web Hacking and Customization
Thể loại Chương
Định dạng
Số trang 45
Dung lượng 1,27 MB

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

Nội dung

JavaScript and XUL Hacking Tools JavaScript and XUL programming can be used in tandem to create great Firefox extensionsand applications.. Using this technique of selecting a window cre-

Trang 1

Table 15-1 Default User Agent Values

Option User Agent String Value

Default Firefox’s current User Agent String value (This varies based on operating

system and version of Firefox running.) Internet Explorer Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) Netscape 4.8 Mozilla/4.8 [en] (Windows NT 5.1; U)

Opera 7.54 Opera/7.54 (Windows NT 5.1; U) [en]

Additional values can be added and customized to your liking by using the extension’s Optionspanel window

To download and install User Agent Switcher, visit http://chrispederick.com/work/firefox/useragentswitcher/

Hacking with ViewSourceWith

ViewSourceWith is a simple, well-thought-out extension that allows you to add a list of ent editors via its Options window, shown in Figure 15-6, which will then be made availablevia the Source View option in Firefox’s View menu, as “View source with” in the right-clickcontext menu, or as an optional toolbar button The uses for this extension quickly materializewhen working with simple local HTML pages that require quick editing Additionally, pullingpage source code into my favorite editors is a nice added bonus when reviewing or skimmingthrough code

differ-F IGURE 15-6: ViewSourceWith configuration screen

Trang 2

To download and install ViewSourceWith, visit http://dafizilla.sourceforge.net/

viewsourcewith/

Navigation and Link Hacking Tools

Three tools that are used for handling or working with links and their HTML code are MouseGestures, ieview, and BBCode All have different tasks and are extremely useful when navigat-ing from page to page or when posting link information on web forums and sites

Hacking with Mouse Gestures

While this tool is not necessarily web programming–specific, once you review all the availableoptions and features you will see how it can save you tons of time when navigating through theInternet — for example, to look up reference code or code snippets By default, you can right-click and drag your mouse in several directions to execute a specific navigation command (Forexample, right-clicking and dragging from right to left anywhere on the page jumps you back

to the previous page; doing the reverse from left to right jumps you forward one page in yourbrowsing history.) This extension is highly configurable but comes with some very easy-to-learn basic gestures, which, coupled with the Gesture Exchange link on their site, will have you customizing things to your liking or just leaving things as they are and enjoying quick navigation

To visually enhance the benefits of this little puppy, activate the mouse trails in the extension’soptions window, and you will see your mouse gestures as you do them

For more information or to install Mouse Gestures, visit http://optimoz.mozdev.org/

gestures/

Hacking with ieview

As much as I hate to admit it, there are still sites, including both public and corporateintranets, that rely heavily on Internet Explorer technology So, whether for testing or pureoutright need, this extension allows a quick way to load a link from Firefox into InternetExplorer For most users this need revolves around Windows Updates, Office Updates,Microsoft Java VM, or other Microsoft media-rich sites — basically, sites that are MicrosoftActiveX–dependent and have been absorbed into the Microsoft collective If you want to helpwith the migration pain of using Firefox until sites wake up and smell the Mozilla coffee brew-ing, you can use this extension as a one-time option from the right-click context menu or topermanently add sites that will launch in Internet Explorer

The two options that are added to the right-click context menu include “Open Link Target inIE” and “Always Open Linked Site in IE.” The first is for one-time use or testing, and the sec-ond will add the link to a list that will automatically launch in Internet Explorer after selectingthis To make changes to the “Always Open” list, open the Extension Manager and choose theOptions for ieview to make configuration changes

Trang 3

For more information or to install ieview, visit http://ieview.mozdev.org/.

Hacking with BBCode and BBCodeXtra

Without getting into extreme detail on how to use either one of these extensions, I can tell youthat they can definitely help in filling out responses in forums or forms and with creating linksand image tags for HTML, BBCode, and XHMTL BBCode is the universally acceptedmarkup language for just about all major online user forums BBCode markup language has amuch smaller subset of available formatting tags than HTML, and tags are usually delimitedwith brackets instead of the normal HTML tags, which are delimited with less than (<) andgreater than (>) signs Options that make either of these extensions great are their ability tocreate links from selected text or clipboards into an input form and to add text-formatting syn-tax, as needed Either one of these extensions is a must-have if you intend on posting forumrequests with links or have your own online forum that you use to support your applications,and so on

For more information or to install BBCode, visit http://jedbrown.net/1.0/mozilla/.For more information or to install BBCodeXtra, visit http://www.extenzilla.it/

bbcodextra/index.php?lang=eng

JavaScript and XUL Hacking Tools

JavaScript and XUL programming can be used in tandem to create great Firefox extensionsand applications This section focuses on tools that will help with inspecting the Firefox inter-face, help debug JavaScript, and provide JavaScript tools and XUL packaging features Thesetools vary in level of difficulty and may have a steep learning curve, but all should be worth theeffort required

Hacking with the DOM Inspector

The DOM Inspector is easily the best tool to use when working with Firefox and trying to ate extension overlays by picking apart a window’s or dialog’s XUL elements Using the combi-nation of File ➪ Inspect a Window and Search ➪ Select Element by Click, you can easilyextract a window’s or an element’s id to use within your code This is how I originally extractedthe “throbber-box” and “search-container” ids that I later used and modified in my localuserChrome.css file, as described in Chapter 2 Using this technique of selecting a window

cre-or dialog to inspect and then walking through the document tree also gives you a better understanding of the different elements that are used or are available with XUL interface programming

Installing the DOM Inspector is covered in Chapter 1 in greater detail, but suffice it to say, youwill need to redownload the Firefox installer to get this little gem After that, you can just fol-low the Custom installation options to enable Developer Tools when prompted

Trang 4

Hacking with JavaScript Console and Debugger

The JavaScript Console and JavaScript Debugger are two different tools that are miles apartwith respect to features and ease of use The Console is a default install with Firefox and can beconfigured to show JavaScript errors and warnings from web pages, as well as errors fromextensions or XUL applications The entries that get added here are errors, warnings, and messages

While this native feature of Firefox is good, some crave more control over JavaScript coding,and that is where Venkman or JavaScript Debugger comes in handy Venkman is the projectcode name for the JavaScript Debugger extension, which includes an extremely rich and robustediting and debugging environment specifically geared toward JavaScript debugging, as shown

in Figure 15-7

F IGURE 15-7: JavaScript Debugger window

This extension may be overwhelming for the faint of heart at first, but once you have gottenover the initial shock, the utilitarian features become very evident

For more information or to install Venkman, visit http://www.hacksrus.com/~ginda/

venkman/

Trang 5

Hacking with Extension Developer’s Extension

This extension is a nice compilation of quick tools that can make creating extensions a smoothride The extension comes with the following features:

 Toggle Debugging Preferences

 Reload All Chrome

An Extension Developer menu is added to Firefox’s Tools menu, and all of these features areaccessible there

Some of these features are mini–XUL applications that you can also use directly from Firefoxwithout having to install them separately While some of the features are really diamonds in therough, the overall usefulness of this extension can quickly be reaped by novice or serious exten-sion developers

For more information or to install Extension Developer’s Extension, visit http://ted.mielczarek.org/code/mozilla/extensiondev/

Page Validation Hacking Tools

While the Web Developer extension includes a couple of online validation service features, Iwant to also recommend two other extensions that may be of use: HTML Validator andChecky These extensions offer different sets of features, but both can be tapped into to clean

up any nonstandard coding that may be lingering in the HTML closet

Hacking with HTML Validator

When I first used this extension on some of my pages, I was truly shocked and ashamed that itfound so many errors and warnings The core is based on Tidy, which was originally created bythe W3C and has been updated and extended as an open-source project Tidy’s core function-ality focuses on analyzing specific strict standards and formatting for HTML code

The latest version of HTML Validator, which taps into Tidy’s core features, adds a color-codedicon to display the status of the current page that is loaded to the status bar The real function-ality comes with the information that it displays when you view a page’s source code from

Trang 6

View ➪ Page Source This is where HTML Validator adds a split panel, shown in Figure 15-8,

to the bottom of the view source screen The bottom-left panel provides a list of errors andwarnings, and the bottom-right panel contains generic details and possible resolutions for theselected error or warning A nice feature of this extension is that when in view source mode,clicking on an entry in the bottom-left panel jumps you to the offending code within thesource code in the main code window above it, making it easier to track bugs within the code

Another feature that I have not really tapped into, but definitely will, is the Cleanup feature,which is available as a button on the bottom of the Page Source window or from the right-clickcontext menu from the extension’s icon on the status bar This feature steps you through pro-posed fixes for the offending page with source and browser views for the original as well as thenewly cleaned HTML

F IGURE 15-8: HTML Validator list of errors and warnings in view source window

For more information or to install HTML Validator, visit http://users.skynet.be/

mgueury/mozilla/

Trang 7

Hacking with Checky

Another notable extension for page validation is Checky, which is more centered on usingonline web validation services but comes with tons of options This extension also has the abil-

ity to create an agent, which automates several validation checks and caches the results locally.

For more information or to install Checky, visit http://checky.sourceforge.net/extension.html

Summary

This chapter highlights how to quickly make local configuration changes, discusses usingScrapBook to organize notes and web pages, and finally recommends the mother of all webdeveloper extensions to get the boat rockin’ After that, the chapter dives into a few extensionsthat help with hacking HTML, links, JavaScript, XUL, and validating web pages The chap-ter’s main goal is to provide well-rooted and actively supported extensions that can really make

an impact on the day-to-day web programming drudgeries that usually pop up

Trang 8

Creating Extensions

and Themes

Chapter 16

Understanding MozillaProgramming

Trang 10

Mozilla

Programming

This chapter introduces you to the wonderful world of Mozilla

pro-gramming You get to know the main Mozilla technologies and seehow these technologies work together After getting acquainted withthe various concepts and terms, we take our first look at the exciting possi-

bilities found in creating new browser extensions

What makes Mozilla programming and especially Mozilla extension

pro-gramming so great? You can quickly achieve quite a lot with a simple text

editor and some imagination Moreover, Mozilla is truly cross-platform For

example, the vast majority of Firefox extensions can run on many different

operating systems with no modifications whatsoever Finally, Mozilla is

open source This means that you can see exactly what is happening behind

the curtains in each and every component you want to enhance or modify It

also means that there are more people in the community who know the

inner workings of the various Mozilla parts and can help you on your

devel-opment quest

Understanding Mozilla Technologies

This section provides an overview of the various Mozilla technologies,

beginning with XML User Interface Language (XUL), the language

Mozilla uses to describe user interfaces (UI) Then we’ll discuss JavaScript,

a programming language used to implement the logic behind the user

inter-face You’ll also see how to use Cascading Style Sheets (CSS) to define the

appearance of your HTML and XUL documents and how to

programmati-cally access these documents using the Document Object Model (DOM)

interfaces The section concludes with a short overview of the Cross

Platform Component Object Model (XPCOM)

˛ Understanding Mozilla

technologies

˛ Introducing Firefox extension

programming

chapter

in this chapter

by Alex Sirota

Trang 11

XUL: XML User Interface Language

XML User Interface Language (XUL) is the language used in Mozilla to describe user faces Being an XML language, it has all the advantages of XML: it is simple, text based, cross-platform, and very flexible You can create an advanced user interface with XUL in minutesusing a simple text editor You don’t need to compile anything or to learn any platform-specificconcepts or tools This makes creating user interfaces with Mozilla as straightforward as creat-ing regular web pages, and similarly to a web page, your XUL user interface works on any plat-form supported by Mozilla

inter-XUL is pronounced “zool” (rhymes with “cool”)

XUL can be used to create both simple and complex user interfaces, starting with simpledialogs all the way to full-featured applications In fact, the Mozilla applications — Firefox,Thunderbird, and the Mozilla Suite — are all built using XUL There are several other XUL-based applications, including the Internet Relay Chat (IRC) client named ChatZilla

User interfaces created with XUL can be easily skinned, extended, and localized For example,you can change the visual theme of your UI or translate it to another language by simplychanging a few text files Another nice feature is that you can open XUL documents insideyour browser’s content area — exactly as you would open an HTML document You can evenrun your XUL-based application directly from the Internet This makes creating web applica-tions as easy as creating web pages

A XUL user interface definition is an XML file that contains the UI elements and their chal structure For instance, your interface may consist of a window that contains two boxes.Each box can in turn have any number of child widgets (entry boxes, buttons, labels, and so on)

hierar-In the following sections, we create and lay out some simple widgets, and finally create a plete XUL document

com-If you want to test the XUL code in the following examples, you can create a file with a xulextension and the following contents:

<?xml version=”1.0” encoding=”UTF-8”?>

<window align=”start”

xmlns=”http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul”>

[Your XUL widgets go here]

.

Trang 12

Once you create the file and insert some XUL elements, you can open it in Firefox using File ➪Open File The align=”start” part makes sure your XUL widgets are shown correctly whenopened inside the browser window.

XUL Widgets

The basic element of a XUL document is a widget Buttons, text boxes, menu items, and so on

are all widgets A widget is created by inserting an appropriate element into your XUL ment The attributes of this element determine the various properties of your widget Forexample, the following defines a simple button:

docu-<button label=”Go”/>

The labelattribute determines the text that appears on the button

A button by itself isn’t much of a user interface, so let’s add a text box:

<textbox value=”Enter you text here”/>

The optional valueattribute defines the default text that initially appears inside the text box

You shouldn’t put text labels directly in a XUL file If you do, you won’t be able to use Mozilla’slocalization mechanisms to translate this text into other languages If you use XML entitiesinstead of literal text strings, the translation will become virtually effortless You learn aboutMozilla localization in the next chapter

XUL elements can have many optional attributes For example, some of the attributes that atext box can have follow:

 maxlength: The maximal number of characters that can be entered into the text box

 readonly: Setting this attribute to truemakes the entry box read-only

 type: You can create special-purpose entry boxes with this attribute For example, ting the value of this attribute to passwordcreates a password entry box, one that doesn’t display what is being typed

set-XUL Layout

We have seen how individual widgets can be specified using XUL Now it is time to see howXUL handles layout

XUL uses a scheme called the box model to specify how the elements are oriented, aligned, and

positioned The user interface is divided into boxes A box can contain UI elements or otherboxes Each box specifies whether its child elements are horizontally or vertically aligned Bygrouping your elements into boxes, adding spacers, and specifying the flexibility of your ele-ments, you can achieve the wanted layout for you user interface

For example, the following specifies that we want three buttons to be arranged in a row:

<hbox>

<button label=”Red”/>

<button label=”Green”/>

<button label=”Blue”/>

Trang 13

Figure 16-1 shows the horizontally arranged buttons.

F IGURE 16-1: Horizontally arranged buttons

As you can see, to create a horizontal layout, we placed the three buttons inside an hboxment Similarly, to create a vertical layout, you place the elements inside a vbox:

Figure 16-2 shows the vertically arranged buttons

F IGURE 16-2: Vertically arranged buttons

An example of a complete XUL document follows:

RDF in XUL Applications

Resource Description Framework (RDF) is a technology for describing Internet resources It istypically implemented as an XML file having a special syntax RDF is a complex topic outsidethe scope of this book In the following sections, you can see some Mozilla configuration fileswritten using this format, but understanding RDF is not required — all the examples includethe necessary explanations and clarifications

Trang 14

The RDF specification is maintained by the World Wide Web Consortium (W3C) For moreinformation about this technology in Mozilla visit the Mozilla RDF page: http://www.mozilla.org/rdf/doc/.

Additional XUL Resources

Following are two additional XUL resources that might come in handy:

 Mozilla XUL project page: This page contains the XUL specification and links to

addi-tional XUL resources:http://www.mozilla.org/projects/xul/

 XUL Planet: This site is dedicated to XUL programming It has several very helpful

tutorials and a lot of reference material:http://www.xulplanet.com/

We now know what XUL is and how we can use it to create user interfaces But XUL by itselfisn’t very useful; we have merely created a bunch of elements and placed them together Weneed a way to add some functionality to our user interface This is usually done with JavaScript,which leads us to the following section

JavaScript

JavaScript is a powerful scripting language most widely used for creating dynamic web pages

Mozilla also uses JavaScript to implement the logic behind XUL user interfaces Like manyother technologies used in Mozilla, JavaScript is very easy to master; you don’t have to be anexperienced programmer to start writing JavaScript programs

JavaScript and Java are two completely different languages They both have syntax somewhatsimilar to C, but other than that, they don’t really have much in common JavaScript is alightweight scripting language created by Netscape, while Java is a more complex, compiled lan-guage developed by Sun Microsystems

JavaScript is an interpreted language This means that the program is executed directly fromthe source code; there is no need to first compile it into binary form This also means that pro-grams written in JavaScript are usually open source by definition — they are just plain-textpieces of code, located either in separate files or embedded in HTML or XUL documents

The JavaScript language is standardized by the ECMA-262 standard under the nameECMAScript

Syntax

When it comes to syntax, JavaScript is similar to C, Perl, PHP, and many other programminglanguages

Trang 15

If you want to test the JavaScript examples that follow, you can create an HTML document withthe following contents:

.

} else {alert(“i is not 1”);

Trang 16

JavaScript has several different looping statements For example, the following loop will be cuted four times:

exe-for (i = 0; i < 4; i++) {alert(i);

}

In the preceding statement we want ito be initialized with 0and to be incremented by 1 oneach loop iteration The loop will be executed as long as the value of iis less than 4

Variables

Variables in JavaScript are created by either assigning a value to a new variable or by declaring

it using the varkeyword:

var i;

Variables declared inside a function have a local scope, meaning that they can be used onlyinside that function Variables that were defined outside any function are global and can beused anywhere in the script

Functions

You can define new functions using the functionkeyword:

function add(a, b) {return a + b;

}The preceding function receives two arguments,aand b, and returns their sum

Scripting the User Interface

As previously mentioned, we will be using JavaScript in Mozilla to implement the logic behindthe user interface Each user interface element can trigger several events For example, a buttoncan trigger an event when it is pressed If we attach a JavaScript function to such an event, itwill be executed each time the event is triggered A function attached to an event is called an

Trang 17

F IGURE 16-3: A primitive calculator

Each time the button is pressed, our calculateSumfunction is executed Let’s look at howthis function might be implemented:

function calculateSum() {var firstBox = document.getElementById(“first-box”);

var secondBox = document.getElementById(“second-box”);

var a = parseInt(firstBox.value);

var b = parseInt(secondBox.value);

alert(a + b);

} Step by step, the preceding function does the following:

1 Find the two entry boxes elements using getElementsById This function is a part ofthe DOM interface (See the DOM section later in this chapter for details.)

2 After finding our entry boxes, we get their value by examining their valueproperty

3 Convert the value to integer using the parseIntfunction

4 After we have a numerical representation of the contents of our textboxes, we can

calcu-late the sum and present it to the user in a popup box

To see the previous example in action, you can create the following XUL document and open it

var secondBox = document.getElementById(“second-box”);

var a = parseInt(firstBox.value);

var b = parseInt(secondBox.value);

alert(a + b);

} ]]>

</script>

Trang 18

After reading this section, you should have a basic idea about what JavaScript is and how youcan use it to add some logic to your user interface Chapter 17 continues exploring the possibil-ities while examining several additional examples.

Additional JavaScript Resources

Following are some additional JavaScript resources that might be useful:

 The WebReference JavaScript Section has many articles and tutorials on JavaScript programming:http://www.webreference.com/js/

 The JavaScript Guide, while a bit outdated, is still a good reference:http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/

 The official JavaScript (ECMAScript) specification can be found on the Ecma web site:http://www.ecma-international.org/publications/standards/

Ecma-262.htm

 Here is a good JavaScript tutorial:http://www.tizag.com/javascriptT/

 Here is a nice article about the history of JavaScript:http://www.howtocreate.co.uk/jshistory.html

Cascading Style Sheets

Cascading Style Sheets (CSS) is a mechanism for specifying the appearance of HTML, XUL,and other documents With CSS, you can specify colors, fonts, sizes, and other style elements

CSS is a World Wide Web Consortium (W3C) specification

CSS allows you to separate your document content from its presentation For example, yourXUL document can specify that your user interface contains an entry box and two buttons Astyle sheet can then be used to specify the size of the entry field, the color of the buttons, andthe font of their labels There are many advantages to separating the document style from itscontent The first and possibly the most important benefit is flexibility If you define all thepresentation-related information in a separate style sheet, you will be able to easily modify thestyle of your user interface without needing to adjust the document content Your HTML orXUL files will become much more readable and clean

Trang 19

Suppose that you have created a large project with dozens of XUL documents Then, afterworking with your program for a while, you notice that changing the font of all the labels willgreatly improve their readability In a world without style sheets, you would have to search allyour XUL documents for labelelements and add an appropriate attribute to each and everyone of them What would happen if you decided to experiment with several different fonts tosee which one looked the best? With style sheets, this task becomes trivial If all your docu-ments use the same style sheet (and if they are part of the same project, they probably should),you can just add a line to this style sheet specifying the new font of your label elements.

A typical CSS definition is a list of rules A rule has a selector that specifies the elements therule applies to and a list of style declarations For example, a rule for changing the appearance

of all the labelelements might look like this:

label {font-family: arial;

There are many places in which both the author of the document and its reader can specifytheir preferred style rules For example, styles can be defined in external style sheets, embedded

in the document, or specified inline by setting an element’s style attribute Users can furtherchange these styles by changing the browser settings or adding their own custom style sheets.This means that several, often-conflicting style definitions can be applicable to the same ele-ment The “cascading” in CSS allows these conflicts to be resolved by specifying the order inwhich the rules are evaluated For example, the author-specified rules have higher priority thanthe reader-specified ones, and the more specific rules will override ones that are more general.Each element in our HTML or XUL document can have a classattribute that can be used

to specify that several elements are related to one another in some way Elements can also have

an idattribute Unlike the classattribute, the element’s idshould be unique throughout thedocument — it will be used to identify the specific element Let’s look at a fragment of a XULdocument to clarify things a bit:

<button id=”play-button” class=”control” label=”play”/>

<button id=”stop-button” class=”control” label=”stop”/>

In the preceding example, both buttons belong to the controlclass This will be useful if youwant to apply some style to all the elements belonging to this class For example, you mightwant to make all your control buttons bigger than the others You can see that both buttons areuniquely identified by their respective idattributes You can use this to apply a specific styleonly to one element (the play button, for example) without affecting all the other elements.The idattribute will also become handy if you want to find a specific element usingJavaScript

Trang 20

Let’s see a few examples of the various style declarations we can apply to our documents andspecifically to the two buttons from the previous example.

To specify a style for all the button elements in your document, you can use the following rule:

button { border: 1px solid red; }This rule will draw a 1-pixel-wide red border around all the buttons in your document

You can style all the elements having a specific class:

button.control { color: blue; }This rule selects the buttons having a controlclass and makes their label text blue If youwant the rule to apply to all the elements that belong to the controlclass and not only but-tons, you can omit the buttonpart of the selector, as follows:

.control { color: blue; }Now let’s change the label font of the stop button to bold by selecting it using its id,stop-button:

#stop-button { font-weight: bold; }The preceding examples, while simple, demonstrate the power of CSS There is, of course,much more to style sheets; there are additional selector types, inheritance, and many usefulstyle properties The important principle you should have gotten from this section is that youshould always separate your document content from its presentation by using style sheets

Additional CSS Resources

Following are some additional CSS resources that might be helpful:

 The CSS specification can be found on the W3C site:http://www.w3.org/TR/

REC-CSS1(Level 1),http://www.w3.org/TR/REC-CSS2(Level 2)

 The Web Design Group (WDG) site has a nice guide to CSS:http://www.htmlhelp.com/reference/css/

The Document Object Model

The DOM is a collection of interfaces for working with HTML and XML documents Thedocument is represented as a tree of elements The DOM defines methods for navigating andsearching this tree, retrieving information about the various elements, modifying the tree struc-ture by removing and inserting elements, manipulating individual elements, and so on

The DOM isn’t a language or a software library It is a World Wide Web Consortium (W3C)specification for an interface So how does it actually work? Software vendors, in our caseMozilla, implement the DOM standard interfaces and allow them to be used from various pro-gramming languages When developing Mozilla extensions, we will typically be using JavaScript

to call the DOM methods

Trang 21

The following sections provide some examples of what you can do with the DOM interfaces.This isn’t intended as a complete DOM reference but is rather meant to give you a taste of thepossibilities.

Assume that you have an HTML document that contains the following table:

<table id=”my-table” border=”1”>

This table will typically be rendered by the browser, as shown in Figure 16-4

F IGURE 16-4: The sample table rendered by the browser

The DOM representation of this table is shown in Figure 16-5

F IGURE 16-5: The DOM representation of the sample table

You can use the DOM Inspector extension to see the exact tree structure You can inspect andmodify the elements, their attributes, styles, and much more See Chapter 15 for more details onthe DOM Inspector

Last Name

Trang 22

Navigating and Searching the Document Tree

The following JavaScript code searches the document tree for our table using the table’s idattribute my-table:

var myTable = document.getElementById(“my-table”);

The document object represents the root element of our document tree It can be used toaccess all the other elements

In all of the following examples, assume that we have already found our table using thegetElementByIdmethod and assigned it to the myTablevariable

After successfully locating the table, you can find all the table header (th) elements of thattable:

var headers = myTable.getElementsByTagName(“th”);

for (var i = 0; i < headers.length; i++) {alert(headers[i].innerHTML);

}The preceding code displays two popup dialogs, the first saying “First Name” and the secondsaying “Last Name.”

To see this example in action, create an HTML document with the following contents, open it

in the browser, and click the Test button You can later modify the body of the testfunctioninserting the code of the following examples

<html>

<head>

<script type=”text/javascript”>

function test() {var myTable = document.getElementById(“my-table”);

<! var headers = myTable.getElementsByTagName(“th”);

for (var i = 0; i < headers.length; i++) {alert(headers[i].innerHTML);

}}// >

Ngày đăng: 10/08/2014, 12:21

TỪ KHÓA LIÊN QUAN