Text/plain Fragment Bookmarklet

The text/plain fragment documented in RFC 5147 and described on Erik Wilde's blog struck my interest and, like the XML fragment, I wanted to see if I could implement this in IE. In this case there's no XSLT for me to edit so I've implemented it as a bookmarklet. This is only a partial implementation as it doesn't implement the integrity checks.

Implementation

text/plain fragment bookmarklet.

Example URIs

Book store dedication from Cory Doctorow's Little Brother.
Chapter 1 of Cory Doctorow's Little Brother.

Source

There may be bugs ahead:

   javascript:
   function findLinePos(linesOfText, lineToFind) {
      var linePos = -1;
      while (lineToFind-- > 0)
         linePos = linesOfText.indexOf('\n', linePos + 1);
      return linePos;
   };
   function findFragment() {
      var text = document.body.innerText;
      var hash = document.location.hash.substring(1);
      
      var split = hash.split('=', 2);
      var scheme = split[0];
      var schemeData = split[1].split(';', 2)[0];
      var rangeDelim = schemeData.indexOf(',');
      
      var startChar = 0;
      var endChar = -1;
      
      var schemeDataFirst = schemeData;
      var schemeDataSecond = '';
      if (rangeDelim != -1) {
         schemeDataFirst = schemeData.substring(0, rangeDelim);
         schemeDataSecond = schemeData.substring(rangeDelim + 1);
      }
      
      if (scheme == 'line') {
         if (schemeDataFirst.length > 0)
            startChar = findLinePos(text, schemeDataFirst);
         if (schemeDataSecond.length > 0)
            endChar = findLinePos(text, schemeDataSecond);
      }
      else if (scheme == 'char') {
         if (schemeDataFirst.length > 0)
            startChar = schemeDataFirst;
         if (schemeDataSecond.length > 0)
            endChar = schemeDataSecond;
      }
      
      if (startChar != 0 || endChar != -1) {
         if (endChar == -1)
            endChar = rangeDelim == -1 ? startChar : text.length;
         
         document.body.innerHTML =
            '<pre>' +
            text.substring(0, startChar) +
            "<span id='target' style='background:yellow'>" +
            text.substring(startChar, endChar) +
            '</span>' +
            text.substring(endChar) +
            '</pre>';
         
         document.getElementById('target').scrollIntoView();
      }
   };
   findFragment();