javascript to select text from web page

Posted by phil swenson on Stack Overflow See other posts from Stack Overflow or by phil swenson
Published on 2010-04-11T21:06:36Z Indexed on 2010/04/11 21:13 UTC
Read the original article Hit count: 243

Filed under:
|

I'm trying to write a bookmarklet that grabs any selected text on a web page and sends it to my website. It should (hopefully) work in Chrome, FFX, Safari, and IE. I did a search and found a function, but it doesn't appear to work. Here is the code:

<html>
<body>
<div onClick=getSelText()>Click</div>
<div>please select me</div>
</body>
<script language=javascript>
function getSelText(){
    var txt = 'nothing';
    if (window.getSelection){
        txt = "1" + window.getSelection();
    } else if (document.getSelection) {
        txt = "2" + document.getSelection();
    } else if (document.selection) {
        txt = "3" + document.selection.createRange().text;
    } else return;

    alert("selected text = " + txt);
}
</script>
</html>

when I select the text in the div "please select me" and hit the click div, I just get "selected text = 1"

thanks

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about bookmarklet