Identifying and displaying hyperlinks in XUL

Shyamal Mehta

The other day I needed to identify URLs within a block of text and create hyperlinks out of them to be displayed in a XUL description element. First I looked for any XUL control that could do this for me. But there was none. So I turned to javascript to identify the URLs in the block of text while I decided to use the HTML namespace to add HTML tags in the XUL.

To identify URLs, I used a regular expression from the book Mastering Regular Expressions by Jeffrey Friedl. I split the block of text on spaces, parenthesis and hypens and used the regular expression to check if each token is a URL. While finalizing the regular expression, I also took help from this entry by Mark Szlazak. Co-incidentaly, it also refers to the book Mastering Regular Expressions. With this done, I was able to evaluate if each token was a URL.

Now I had to convert these URLs into hyperlinks and make them clickable in XUL. I was using a description element for showing the whole text. Since the text could be long and should wrap to multiple lines, I chose not to use the value attribute but rather add the text as value of the description tag. To do so dynamically, here’s what I did:

  • First I added the correct html namespace by including the following attribute to the window element:


  • Then I added the description element:

var descNode = document.createElement(“description”);

  • Subsequently add the block of text (remember I split it into tokens) one token at a time

var txtNode = document.createTextNode(token);

  • The above works for adding plain text. Now to add a hyper link, the following code snippet was used to add tokens that were identified as hyperlinks:

var linkNode = document.createElementNS(“”,”a”);
linkNode.setAttribute(“href”, token);
linkNode.setAttribute(“target”, “_blank”);
link.setAttribute(“style”, “color: rgb(0,0,255); text-decoration:underline”);
var txtNode = document.createTextNode(token);

And here is how it looks:


If we were to print the XUL DOM tree, it would look like:

<vbox id=”box_id_1″ flex=”1″ style=”overflow: auto”>
This is normal text, but this link: <html:a xhref=></html:a>
is a URL that would be converted to a hyper link.

about the author

Shyamal Mehta

Shyamal is an experienced technology professional having expertise on the web and mobile technologies. His strength lies in his ability to successfully and repeatedly deliver projects and products (large and small) for a variety of industries.