Have you ever ended up coming across a URL in a webpage only to find out it was not clickable? It can be really annoying to have to copy and paste the URL from the webpage into the browser's address bar.

Bookmarklet: Make Links Clickable
Drag the above link to your bookmark bar

Example page: Demo
Javascript raw source: View

How was the bookmarklet made?

A bookmarklet is basically a normal bookmark that has a javascript function passed on to the browser through the 'javascript:' protocol instead of simply a URL.

To make an "installable" bookmarklet, create a link with the javascript function in the href attribute of the <a> tag and instruct your users to drag the link to the bookmark bar.

Example:

HTML Source <a href="javascript:alert('Document has ' + document.getElementsByTagName('a').length + ' links');">Count links in document</a> Output Count links in document

After writing my javascript function for the bookmarklet in a separate file (as so - snippet.js) I used a php function to create the one-line javascript function by striping out all new line characters ( , ) and all tabs ( ) with the help of str_replace.

The resulting javascript function can be called on click by surrounding it with () and calling the newly encapsulated function with another ().
Javascript Source ( function() { /* ... */ } )();

Final Code
PHP Source <a class="bookmarklet" href="javascript:(<?php echo str_replace(array(" ", " "), '', file_get_contents('javascript/snippet.js')); ?>)()">Make Links Clickable</a>

*Note be sure to end all javascript expressions with a semi colon (;) as the bookmarklet has to be one line of code. This includes function constructors.

How was the link finder made?

To find all links in a document (not counting all the ones that are already inside an <a> tag) you must first get all the raw text from the HTML. The browser holds this raw text in so called TextNodes.

In order to get all the text nodes from the DOM, we start from the top (document.body) and make our way down the DOM tree, saving all nodes that are text nodes (child.nodeType == 3) and walking down recursively to nodes that are not text. Be sure to not go down nodes that do not allow <a> tags in them such as <textarea>, <script>, etc.

Having all the nodes, you can now parse them, finding "http://", "https://" or "www." to create a clickable link. For more information please check out the raw javascript.

That is it! I hope you find the bookmarklet useful. If you have any problems or questions feel free to send me a message to bogdan@webstarsltd.com.