4

I'm building a JS bookmarklet which allows me to capture text that a user has selected in their browser and sends it off to a web app. I've currently checked out a couple of tutorials and have a script which looks like this:

javascript:var t;try {t=((window.getSelection&&window.getSelection())||(document.getSelection&&document.getSelection())||(document.selection&&document.selection.createRange&&document.selection.createRange().text));}catch(e){t="";}alert(t);

To make it a bit easier, here's the code in a more readable fashion:

javascript:
      var t;
      try {
        t=((window.getSelection&&window.getSelection()) || (document.getSelection&&document.getSelection()) || (document.selection&&document.selection.createRange&&document.selection.createRange().text));
      }catch(e)
      {
        t="";
      }
      alert(t);

The current code I have grabs the selected text and alerts out so I can see what's been captured. However, the formatting of the text is important to me so what I'd really like to do is grab any HTML in this text too. In fact, I think it might be better yet to work out where the user has selected in the page and look up from the start and back from the end of the selected content to find the nearest HTML tags and then grab what's within that. (as the user can't tell if they're selecting HTML or not easily)

I'm much more used to working with JQuery to do DOM selections so this is a bit over my head at the moment. (Unless you can use JQuery with a bookmarklet... can you?)

Can anyone help me with this? (Even just pointing me in the right direction would be great, I'm doing this as a hobby learning project so I'm happy to figure some stuff out myself.)

2
  • 1
    If you really want to use jQuery in it check out: smashingmagazine.com/2010/05/23/…
    – mVChr
    May 12, 2011 at 6:15
  • Well, JQuery is what I'm familiar with. But I wonder about bloating what would technically be a very small piece of JS with it... (If, and it's a big if, what I'm trying to do is actually quite straightforward across browsers). Thanks heaps though, I'll definitely try it out! May 12, 2011 at 6:20

2 Answers 2

10

The following function will return a string containing the HTML of the user's selection:

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}

Here's a cut down version for a bookmarklet:

javascript:(function(){var h="",s,g,c,i;if(window.getSelection){s=window.getSelection();if(s.rangeCount){c=document.createElement("div");for(i=0;i<s.rangeCount;++i){c.appendChild(s.getRangeAt(i).cloneContents());}h=c.innerHTML}}else if((s=document.selection)&&s.type=="Text"){h=s.createRange().htmlText;}alert(h);})()
1
  • Thanks! That's pretty much what I was trying to do :) May 12, 2011 at 9:24
2

Append the results of getSelection().getRangeAt(0).cloneContents() to a div and then get the innerHTML of the div.

javascript:(function()%7Bvar%20node%3Ddocument.createElement('div')%3Bnode.appendChild(getSelection().getRangeAt(0).cloneContents())%3Balert(node.innerHTML)%3B%7D)()%3B

If you pass the markup in a GET request, you'll need to use encodeURIComponent() on it first.

Also note that a GET request might only accept so much data.

1
  • Thanks for the tip on encoding the GET! May 12, 2011 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.