somewhere to talk about random ideas and projects like everyone else


XPath Bookmark Bookmarklet 01 November 2009

  //inspired by
  var s = document.createElement('script');
  if(typeof jQuery=='undefined') document.getElementsByTagName('head')[0].appendChild(s);
  (function() {
    if(typeof jQuery=='undefined') setTimeout(arguments.callee, 100)
        for(var path = '', elt = jQuery(this)[0]; elt && elt.nodeType==1; elt=elt.parentNode){
          var idx = jQuery(elt.parentNode).children(elt.tagName).index(elt)+1;
          idx>1 ? (idx='['+idx+']') : (idx='');
        window.location.hash = "#xpath:"+path

Sometimes you want to link to a certain part of a web page. That’s great and works well if its a nice site that clearly defines anchor tags to link to, but what if there isn’t?

Today I just remembered something and I thought that I saw something earlier with a xpath URL hash. I googled it and couldn’t find anything native to the browser (please correct me if I’m wrong) but found this script: which is basically what I was thinking about. But it was allegedly hard to make those URLs, so I thought why not make a bookmarklet to make linking to those URLs simple? So I quickly hacked this together

javascript:(function(){var a=document.createElement("script");a.setAttribute("src","");if(typeof jQuery=="undefined"){document.getElementsByTagName("head")[0].appendChild(a)}(function(){if(typeof jQuery=="undefined"){setTimeout(arguments.callee,100)}else{jQuery("*").one("click",function(d){jQuery(this)[0].scrollIntoView();for(var e="",c=jQuery(this)[0];c&&c.nodeType==1;c=c.parentNode){var b=jQuery(c.parentNode).children(c.tagName).index(c)+1;b>1?(b="["+b+"]"):(b="");e="/"+c.tagName.toLowerCase()+b+e}window.location.hash="#xpath:"+e;d.preventDefault();d.stopPropagation();jQuery("*").unbind("click",arguments.callee)})}})()})();

(Just drag it over to your bookmarks bar as with any other bookmarklet). To use, just click on the bookmark, and click on the element you want to link to. You should see the URL will update with a xpath hash showing you the copy-pastable link to that element. The code is quite simple and should work on Firefox, Chrome and all the other browsers (maybe even IE) but the ability to auto-scroll and actually use the links is only available to Firefox and potentially Opera and Chrome.

And I’m working on a Chrome Extension for the original userscript (which should work with Chrome’s userscript support, but I’m going to try packaging it as a chrome extension file) But sadly chromium for linux isnt up to speed especially with extension development.

The source can be found

Update: _Fixed the link for the path and added some stuff. Update 2_: Fixed bookmarklet, now scrolls to clicked, executes only once, prevents default