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

This article needs a technical review. How you can help.

Warning: The content of this article may be out of date.

utils.js is accessible at the following URL:
    https://mxr.mozilla.org/mozilla-centr...ntent/utils.js
This file includes utility functions used by a lot of the bookmarking, tagging, and annotation services that are built into Firefox. By default its only included in browser.xul. Its not an interface, and as such it will never be frozen, but it provides some easy to use functions that can save you from reinventing the wheel and cluttering up your own classes/functions when you need it.

Global Objects

There are a few global objects and constants defined in utils.js. These are:

QI_node

QI_node(aNode, aIID) Runs a query interface on a bookmark node to expose the interface available to that type. If the interface isn't available to that node, null is returned.

  • aNode - The bookmark
  • aIID - The return interface wanted.

There are several predefined versions of this for common calls. These just take in the node, as the interface is already defined:

  • asVisit(aNode)
  • asFullVisit(aNode)
  • asContainer(aNode)
  • asQuery(aNode)

Annotations

A few annotation names are defined here.

  • LOAD_IN_SIDEBAR_ANNO - This annotation is associated with bookmarks or items that should load in the sidebar automatically.
  • DESCRIPTION_ANNO - This annotation stores description information about a bookmark.
  • POST_DATA_ANNO - I need to clarify here, but I think this is the name of the annotation that stores information for keyword searches from a bookmark.
  • LMANNO_FEEDURI - Need to clarify here too, but I think for each livemark, there is an bookmark which contains an annotation storing the associated feed uri.
  • LMANNO_SITEURI - Need to clarify here, but I think for each livemark, there is an bookmark which contains an annotation storing the associated site uri.
  • ORGANIZER_FOLDER_ANNO - This annotation is associated with a folder that should be shown in the Library's left pane.
  • ORGANIZER_QUERY_ANNO - This annotation is used by the places organizer to decide what nodes should be shown in the left pane.


Warning : PlacesUtils class since Firefox 3 beta 5 has been split into:

  • PlacesUtils: can be used in any toolkit application
  • PlacesUIUtils: only in Firefox

PlacesUtils

This is a gigantic object full of usefulness if you need to do any bookmark work from within browser.xul. As such, it gets its own special section.

PlacesUtils

Method overview

nsIURI createFixedURI(string aSpec);
string getFormattedString(string key, string params);
string getString(string key);
boolean nodeIsFolder(nsINavHistoryResultNode aNode);
boolean nodeIsBookmark(nsINavHistoryResultNode aNode);
boolean nodeIsSeparator(nsINavHistoryResultNode aNode);
boolean nodeIsVisit(nsINavHistoryResultNode aNode);
boolean nodeIsURI(nsINavHistoryResultNode aNode);
boolean nodeIsQuery(nsINavHistoryResultNode aNode);
boolean nodeIsReadOnly(nsINavHistoryResultNode aNode);
boolean nodeIsHost(nsINavHistoryResultNode aNode);
boolean nodeIsContainer(nsINavHistoryResultNode aNode);
boolean nodeIsDynamicContainer(nsINavHistoryResultNode aNode);

boolean nodeIsLivemarkContainer(nsINavHistoryResultNode aNode); Obsolete since Gecko 21

boolean nodeIsLivemarkItem(nsINavHistoryResultNode aNode); Obsolete since Gecko 21
boolean isReadonlyFolder(nsINavHistoryResultNode aNode);
int getIndexOfNode(nsINavHistoryResultNode aNode);
string wrapNode(nsINavHistoryResultNode aNode, string aType, nsIURI aOverrideURI);
array unwrapNodes(string blob, string aType);
nsITransaction makeTransaction(string data, string type, nsINavHistoryResultNode container, int index, boolean copy);
nsINavHistoryResult getFolderContents(int aFolderId, boolean aExcludeItems, boolean aExpandQueries);
boolean showAddBookmarkUI(nsIURI aURI, string aTitle, string aDescription, int aDefaultInsertionPoint, boolean aShowPicker, boolean aLoadInSidebar, string aKeyword, string aPostData);
boolean showMinimalAddBookmarkUI(nsIURI aURI, string aTitle, string aDescription, int aDefaultInsertionPoint, boolean aShowPicker, boolean aLoadInSidebar, string aKeyword, string aPostData);
boolean showAddLivemarkUI(nsIURI aFeedURI, nsIURI aSiteURI, string aTitle, string aDescription, int aDefaultInsertionPoint, boolean aShowPicker);
boolean showMinimalAddLivemarkUI(nsIURI aFeedURI, nsIURI aSiteURI, string aTitle, string aDescription, int aDefaultInsertionPoint, boolean aShowPicker);
boolean showMinimalAddMultiBookmarkUI(array nsIURI aURIList);
boolean showBookmarkProperties(int aId);
boolean showFolderProperties(int aId);
boolean showAddFolderUI(string aTitle, int aDefaultInsertionPoint, boolean aShowPicker);
array object getAnnotationsForURI(nsIURI aURI);
array object getAnnotationsForItem(int aItemId);
void setAnnotationsForURI(nsIURI aURI, object aAnnos);
void setAnnotationsForURI(int aItemId, object aAnnos);
getViewForNode(nsIDOMNode aNode);
void markPageAsTyped(string aURL);
void markPageAsFollowedBookmark(string aURL);
boolean checkURLSecurity(nsINavHistoryResultNode aURINode);
string getQueryStringForFolder(int aFolderId);
string getDescriptionFromDocument(nsIDOMDocument doc);
string setPostDataForBookmark(int aBoomarkId, string aPostData);
string getPostDataForBookmark(int aBoomarkId);
array string getURLAndPostDataForKeyword(string aKeyword);
string getItemDescription(int aItemId);
nsINavHistoryResultNode getMostRecentBookmarkForURI(nsIURI aURI);
nsINavHistoryResultNode getMostRecentFolderForFeedURI(nsIURI aURI);
nsINavHistoryResultNode getURLsForContainerNode(nsINavHistoryResultNode aNode);
void openContainerNodeInTabs(nsINavHistoryResultNode aNode, nsIDOMEvent aEvent);
void openURINodesInTabs(array nsINavHistoryResultNode aNodes, nsIDOMEvent aEvent);
void createMenuItemForNode(nsINavHistoryResultNode aNode, aContainersMap);

Constants

Mimetypes

  • TYPE_X_MOZ_PLACE_CONTAINER
  • TYPE_X_MOZ_PLACE_SEPARATOR: "text/x-moz-place-separator",
  • TYPE_X_MOZ_PLACE: "text/x-moz-place",
  • TYPE_X_MOZ_URL: "text/x-moz-url",
  • TYPE_HTML: "text/html",
  • TYPE_UNICODE: "text/unicode",

Services

There's easy access to some of the common services used in bookmarks or history navigation here. For instance, normally in order to get access to the bookmarks service, you have to run something like:

 Components.classes["@mozilla.org/browser/nav-bookmarks-service;1"]
   .getService(Components.interfaces.nsINavBookmarksService);

With places utils all you need to write is:

 PlacesUtils.bookmarks

This should save on the number of references to the service that are needed, and can help clean up interfaces that are already fairly cluttered. There are currently 11 services defined in here.

bookmarks
nsINavBookmarksService
history
nsINavHistoryService
globalHistory
nsIBrowserHistory
livemarks
nsILivemarkService
annotations
nsIAnnotationService
favicons
nsIFaviconService
microsummaries
nsIMicrosummaryService
tagging
nsITaggingService
RDF
nsIRDFService
ptm
nsIPlacesTransactionsService
clipboard
nsIClipboard
URIFixup
nsIURIFixup

Special Places

These are essentially references to the id's of special folders within places. They can save you time calling the service and searching for a particular folder on your own.

placesRootId
 
bookmarksMenuFolderId
The bookmarks menu.
toolbarFolderId
The bookmarks toolbar.
tagsFolderId
The folder that tags are stored in.
unfiledBookmarksFolderId
 

Other

Other attributes stored in PlacesUtils.

localStore
Warning: Local store provided access to the local-store rdf data source, which stores persisted information about the browser. Its functionality has been replaced by xulstore.
uriTypes
 
containerTypes
 
leftPaneQueries
Queries that appear in the Library's left pane.
leftPaneFolderId
A single folder shown in the Library's left pane.
allBookmarksFolderId
The id of the "All Bookmarks" folder shown in the Library's left pane.
placesFlavors
 
GENERIC_VIEW_DROP_TYPES
 

Methods

createFixedURI

 nsIURI createFixedURI(string aSpec)

Takes in a spec and returns a valid uri based on it using the nsIURIFixup service.

Parameters
aSpec
a url string that needs fixup
Return type

Returns a correct nsIURI.

getFormattedString()

 string getFormattedString(string key,
                           array string params)
Parameters
key
The string name to get from the string bundle
params
Strings to substitute into the bundle at designated points

See XUL:stringbundle for more information.

Return type

Returns a string from the default places stringbundle.

getString()

 string getString(string key)
Parameters
key
The name of the string to get.
Return type

Returns a string from the default places stringbundle.

nodeIs()

There are a ton of nodeIs(something) functions in here to check properties of a bookmark node. The all take in the same argument and return a boolean true or false, so I'm just going to list them all in one lump:

boolean nodeIsFolder(aNode)
Determines whether or not a ResultNode is a Bookmark folder or not.
boolean nodeIsBookmark(aNode)
Determines whether or not a ResultNode represents a bookmarked URI.
boolean nodeIsSeparator(aNode)
Determines whether or not a ResultNode is a Bookmark separator.
boolean nodeIsVisit(aNode)
Determines whether or not a ResultNode is a visit item or not
boolean nodeIsURI(aNode)
Determines whether or not a ResultNode is a URL item or not
boolean nodeIsQuery(aNode)
Determines whether or not a ResultNode is a Query item or not
boolean nodeIsReadOnly(aNode)
Determines if a node is read only (children cannot be inserted, sometimes they cannot be removed depending on the circumstance)
boolean nodeIsHost(aNode)
Determines whether or not a ResultNode is a host folder or not
boolean nodeIsContainer(aNode)
Determines whether or not a ResultNode is a container item or not
boolean nodeIsDynamicContainer(aNode)
Determines whether or not a result-node is a dynamic-container item. The dynamic container result node type is for dynamically created containers (e.g. for the file browser service where you get your folders in bookmark menus).
boolean nodeIsLivemarkContainer(aNode)
Determines whether a result node is a remote container registered by the livemark service.
boolean nodeIsLivemarkItem(aNode)
Determines whether a result node is a live-bookmark item
Parameters
aNode
The node to check.
Return type

Returns a boolean.

isReadonlyFolder()

Determines whether or not a node is a readonly folder.

 boolean isReadonlyFolder(aNode)
Parameters
aNode
The node to check.
Return type

Return true if the node is a folder, false otherwise.

getIndexOfNode()

Gets the index of a node within its parent container

 int getIndexOfNode(aNode)
Parameters
aNode
The node to look up
Return type

Returns the index of the node within its parent container, or -1 if the node was not found or the node specified has no parent.

wrapNode()

String-wraps a result node according to the rules of the specified content type.

 string wrapNode(aNode,
                 string aType,
                 nsIURI aOverrideURI)
Parameters
aNode
The Result node to wrap (serialize)
aType
The content type to serialize as
aOverrideURI
[optional] Used instead of the node's URI if provided. This is useful for wrapping a container as TYPE_X_MOZ_URL, TYPE_HTML or TYPE_UNICODE.
Return type

Returns A string serialization of the node

unwrapNodes()

Unwraps data from the Clipboard or the current Drag Session.

 array object unwrapNodes(blob,
                          type)
Parameters
blob
A blob (string) of data, in some format we potentially know how to parse.
type
The content type of the blob.
Return type

Returns an array of objects representing each item contained by the source.

makeTransaction()

Constructs a Transaction for the drop or paste of a blob of data into a container.

 makeTransaction(data,
                 type,
                 container,
                 index,
                 copy)
Parameters
data
The unwrapped data blob of dropped or pasted data.
type
The content type of the data
container
The container the data was dropped or pasted into
index
The index within the container the item was dropped or pasted at
copy
The drag action was copy, so don't move folders or links.
Return type

Returns an object implementing nsITransaction that can perform the move/insert.

getFolderContents()

 getFolderContents(aFolderId,
                   aExcludeItems,
                   aExpandQueries)

Generates a nsINavHistoryResult for the contents of a folder.

Parameters
folderId
The folder to open
[optional] excludeItems
True to hide all items (individual bookmarks). This is used on the left places pane so you just get a folder hierarchy.
[optional] expandQueries
True to make query items expand as new containers. For managing,you want this to be false, for menus and such, you want this to be true.
Return type

Returns a nsINavHistoryResult containing the contents of the folder. The result.root is guaranteed to be open.

Bookmark Dialog

Methods to show the bookmarkProperties dialog in its various modes.

The showMinimalAdd methods open the dialog by its alternative URI. Thus they persist the dialog dimensions separately from the showAdd methods. Note these variants also do not return the dialog "performed" state since they may not open the dialog modally.

showAddBookmarkUI()

Shows the "Add Bookmark" dialog.

 showAddBookmarkUI(aURI,
                   aTitle,
                   aDescription,
                   aDefaultInsertionPoint,
                   aShowPicker,
                   aLoadInSidebar,
                   aKeyword,
                   aPostData)
Parameters
[optional] aURI
An nsIURI object for which the "add bookmark" dialog is to be shown.
[optional] aTitle
The default title for the new bookmark.
[optional] aDescription
The default description for the new bookmark
[optional] aDefaultInsertionPoint
The default insertion point for the new item. If set, the folder picker would be hidden unless aShowPicker is set to true, in which case the dialog only uses the folder identifier from the insertion point as the initially selected item in the folder picker.
[optional] aShowPicker
see above
[optional] aLoadInSidebar
If true, the dialog will default to load the new item in the sidebar (as a web panel).
[optional] aKeyword
The default keyword for the new bookmark. The keyword field will be shown in the dialog if this is used.
[optional] aPostData
POST data for POST-style keywords.
Return type

Returns true if any transaction has been performed.

Note: The location, description and "load in sidebar" fields are visible only if there is no initial URI (aURI is null).
Note: When aDefaultInsertionPoint is not set, the dialog defaults to the bookmarks root folder.

showMinimalAddBookmarkUI()

 showMinimalAddBookmarkUI(aURI,
                        aTitle,
                        aDescription,
                        aDefaultInsertionPoint,
                        aShowPicker,
                        aLoadInSidebar,
                        aKeyword,
                        aPostData)

This opens the dialog with only the name and folder pickers visible by default. You can still pass in the various paramaters as the default properties for the new bookmark. The keyword field will be visible only if the aKeyword parameter was used.

See showAddBookmarkUI for a description of the params.

showAddLivemarkUI()

Shows the "Add Live Bookmark" dialog.

 boolean showAddLivemarkUI(aFeedURI,
                           aSiteURI,
                           aTitle,
                           aDescription,
                           aDefaultInsertionPoint,
                           aShowPicker)
Parameters
[optional] aFeedURI
The feed URI for which the dialog is to be shown (nsIURI).
[optional] aSiteURI
The site URI for the new live-bookmark (nsIURI).
[optional] aDefaultInsertionPoint
The default insertion point for the new item. If set, the folder picker would be hidden unless aShowPicker is set to true, in which case the dialog only uses the folder identifier from the insertion point as the initially selected item in the folder picker.
[optional] aShowPicker
see above
Return type

Return true if any transaction has been performed.

Note: The feedURI and description fields are visible only if there is no initial feed URI (aFeedURI is null).
Note: When aDefaultInsertionPoint is not set, the dialog defaults to the bookmarks root folder.

showMinimalAddLivemarkUI()

This opens the dialog with only the name and folder pickers visible by default. You can still pass in the various paramaters as the default properties for the new live-bookmark.

 boolean showMinimalAddLivemarkUI(aFeedURI,
                                  aSiteURI,
                                  aTitle,
                                  aDescription,
                                  aDefaultInsertionPoint,
                                  aShowPicker)

See showAddLivemarkUI for a description of the params.

showMinimalAddMultiBookmarkUI()

Show an "Add Bookmarks" dialog to allow the adding of a folder full of bookmarks corresponding to the objects in the uriList. This will be called most often as the result of a "Bookmark All Tabs..." command.

 showAddMultiBookmarkUI(aURIList)
Parameters
aURIList
List of nsIURI objects representing the locations to be bookmarked.
Return type

Return true if any transaction has been performed.

showBookmarkProperties()

Opens the bookmark properties panel for a given bookmark identifier.

 showBookmarkProperties(aId)
Parameters
aId
bookmark identifier for which the properties are to be shown
Return type

Return true if any transaction has been performed.

showFolderProperties()

Opens the folder properties panel for a given folder ID.

 showFolderProperties(aId)
Parameters
aId
an integer representing the ID of the folder to edit
Return type

Return true if any transaction has been performed.

showAddFolderUI()

Shows the "New Folder" dialog.

 showAddFolderUI(aTitle,
                 aDefaultInsertionPoint, 
                 aShowPicker)
Parameters
[optional] aTitle
The default title for the new bookmark.
[optional] aDefaultInsertionPoint
The default insertion point for the new item. If set, the folder picker would be hidden unless aShowPicker is set to true, in which case the dialog only uses the folder identifier from the insertion point as the initially selected item in the folder picker.
[optional] aShowPicker
see above
Return type

Return true if any transaction has been performed.

Annotations

These are functions that simplify annotating pages. Information like keywords, descriptions, and POST data is already stored as annotations by Firefox, but you can create additional ones. Using the functions can save you some implementation work. For example, given a uri, the traditional code to get all its annotations would be:

 var annotationService = Components.classes["@mozilla.org/browser/annotation-service;1"]
   .getService(Components.interfaces.nsIAnnotationService);
 try {
   var names = annotationService.getPageAnnotationNames(uri);
 } catch(e) {
   // no annotations
 }
 var annotations = new Array();
 for(var i in names) {
   try {
     annotations.push(annotationService.getPageAnnotation(uri, names[i]));
   } catch(e) {
     // this shouldn't happen
   }
 }

The code using placesUtils collapses a bit to:

 var annotations = PlacesUtils.getAnnotationsForUri(uri);

saving you a bit of clumsy code and leaving Mozilla to make sure everything is written correctly. It also gives you more information that my hastily written (and probably incorrect) example up above. The annotation objects returned or send from/to all these functions all are arrays of objects which have the properties:

name
the annotation name
flags
annotation flags
expires
annotation expiration
mimeType
mimetype of the annotation, usually only used for binary annotations
type
the type used for non-binary annotations
value
the value of the annotation

getAnnotationsForURI()

Fetch all annotations for a URI, including all properties of each annotation which would be required to recreate it.

 array object getAnnotationsForURI(aURI)
Parameters
aURI
The URI for which annotations are to be retrieved.

Return array of objects, each containing the following properties: name, flags, expires, mimeType, type, value

getAnnotationsForItem()

Fetch all annotations for an item, including all properties of each annotation which would be required to recreate it.

 array object getAnnotationsForItem(aItemId)
Parameters
aItemId
The identifier of the itme for which annotations are to be retrieved.
Return type

Return Array of objects, each containing the following properties: name, flags, expires, mimeType, type, value

setAnnotationsForURI()

Annotate a URI with a batch of annotations.

 setAnnotationsForURI(nsIURI aURI,
                      array object aAnnos)
Parameters
aURI
The URI for which annotations are to be set.
aAnnotations
Array of objects, each containing the following properties: name, flags, expires, type, mimeType (only used for binary annotations) value.

setAnnotationsForItem()

Annotate an item with a batch of annotations.

 setAnnotationsForItem(int aItemId,
                       array object aAnnos)
Parameters
aItemId
The identifier of the item for which annotations are to be set
aAnnotations
Array of objects, each containing the following properties: name, flags, expires, type, mimeType (only used for binary annotations) value.

Other

Other functions that I'm not sure how to file.

getViewForNode()

Returns the closet ancestor places view for the given DOM node

 getViewForNode(aNode)
Parameters
aNode
a DOM node
Return type

Return the closet ancestor places view if exists, null otherwsie.

markPageAsTyped()

By calling this before we visit a URL, we will use TRANSITION_TYPED as the transition for the visit to that URL (if we don't have a referrer). This is used when visiting pages from the history menu, history sidebar, url bar, url autocomplete results, and history searches from the places organizer. If we don't call this, we'll treat those visits as TRANSITION_LINK.

 markPageAsTyped(string aURL)

markPageAsFollowedBookmark()

By calling this before we visit a URL, we will use TRANSITION_BOOKMARK as the transition for the visit to that URL (if we don't have a referrer). This is used when visiting pages from the bookmarks menu, personal toolbar, and bookmarks from within the places organizer. If we don't call this, we'll treat those visits as TRANSITION_LINK.

 markPageAsFollowedBookmark(string aURL)

checkURLSecurity()

Allows opening of javascript/data URI only if the given node is bookmarked (see bug 224521).

 checkURLSecurity(aURINode)
Parameters
aURINode
a URI node
Return type

Return true if it's safe to open the node in the browser, false otherwise.

getQueryStringForFolder()

Helper for getting a serialized Places query for a particular folder.

 getQueryStringForFolder(int aFolderId)
Parameters
aFolderId
The folder id to get a query for.
Return type

Return string serialized place URI

getDescriptionFromDocument()

Get the description associated with a document, as specified in a <META> element.

 getDescriptionFromDocument(doc)
Parameters
doc
A DOM Document to get a description for
Return type

Returns a description string if a META element was discovered with a "description" or "httpequiv" attribute, empty string otherwise.

setPostDataForBookmark()

Set the POST data associated with a bookmark, if any. Used by POST keywords.

 setPostDataForBookmark(int aBookmarkId,
                        string aPostData)
aBookmarkId
 
Return type

Returns string of POST data

getPostDataForBookmark()

Get the POST data associated with a bookmark, if any.

 getPostDataForBookmark(int aBookmarkId)
Parameters
aBookmarkId
 
Return type

Returns string of POST data if set for aBookmarkId. null otherwise.

getURLAndPostDataForKeyword()

Get the URI (and any associated POST data) for a given keyword.

 getURLAndPostDataForKeyword(aKeyword)
Parameters
aKeyword
keyword
Return type

Returns an array containing a string URL and a string of POST data

getItemDescription()

Retrieve the description of an item

 getItemDescription(aItemId)
Parameters
aItemId
item identifier
Return type

Returns the description of the given item, or an empty string if it is not set.

getMostRecentBookmarkForURI()

Get the most recently added/modified bookmark for a URL, excluding items under tag or livemark containers. -1 is returned if no item is found.

 getMostRecentBookmarkForURI(aURI)

getMostRecentFolderForFeedURI()

 getMostRecentFolderForFeedURI(aURI)

getURLsForContainerNode()

 getURLsForContainerNode(aNode)

openContainerNodeInTabs()

 openContainerInTabs(aNode,
                     aEvent)

openURINodesInTabs()

 openURINodesInTabs(aNodes,
                    aEvent)

createMenuItemForNode()

Helper for the toolbar and menu views.

 createMenuItemForNode(aNode,
                       aContainersMap)

   

   

Document Tags and Contributors

 Last updated by: e-motiv,