
A simple command example 175
The changeCase() function first tests the property
document.forms[0].elements[0].checked. The document.forms[0].elements[0]
property refers to the first element in the first form of the current document object, which is
the UI for the extension. The
checked property has the value true if the element is checked
(or enabled) and
false if it is not. In the interface, elements[0] refers to the first radio
button, which is the Uppercase button. Because one of the radio buttons is always checked
when the user clicks OK, the code assumes that if the choice is not uppercase, it must be
lowercase. The function sets the variable
uorl to "u" or "l" to store the user’s response.
The remaining code in the function retrieves the selected text, converts it to the specified case,
and copies it back in place in the document.
To retrieve the selected text for the user’s document, the function gets the DOM. It then gets
the root element of the document, which is the
html tag. Finally, it extracts the whole
document into the
theWholeDoc variable.
Next,
changeCase() calls getSelectedNode() to retrieve the node that contains the selected
text. It also retrieves any child nodes (
theSelNode.childNodes) in case the selection is a tag
that contains text, such as
<b>text</b>.
If there are child nodes (
hasChildNodes() returns the value true), the command loops
through the children looking for a text node. If one is found, the text
(
theChildren[i].data) is stored in selText, and the offsets of the text node are stored in
theSel.
If there are no child nodes, the command calls
getSelection() and stores the beginning and
ending offsets of the selection in
theSel. It then extracts the string between those two offsets
and stores it in
selText.
The function then checks the
uorl variable to determine whether the user selected uppercase.
If so, the function writes the HTML code back to the document in sections: first, the
beginning of the document to the beginning of the selection; then the selected text,
converting it to uppercase (
selText.toUppercase()); and last, the end of the selected text to
the end of the document.
If the user selects lowercase, the function performs the same operation, but calls
selText.toLowerCase() to convert the selected text to lowercase.
Finally, changeCase() resets the selection and calls window.close() to close the UI.
Kommentare zu diesen Handbüchern