Search code examples
javascriptgetselection

JavaScript How to extract link from selected text


I looking-for solution how to extract url from selected text using window.getSelection and document.selection.

Text to select look that:

<p>Lorem Ipsum is <a href="http://example.com">simply <b>dummy</b> text</a> of the printing and typesetting industry.</p>

Selected text (selected by user) to extract link:

Option 1 (include text and text between a tags):

Ipsum is simply dummy text of

Option 2 (select text and fragment of link):

Ipsum is simply

The function should be return http://example.com


Solution

  • It's hard to write up for cross-browser function. See How to bind a handler to a selection change on window?.

    We should capture some events like mousedown, mouseup, touchstart, touchend. The combination of these event may be fine.

    function addEvent(elem, event, func) {
        if (elem.addEventListener) {
            elem.addEventListener(event, func, false);
        } else {
            elem.attachEvent('on' + event, func);
        }
    }
    

    Next is the getSelectedHTML() using window.getSelection or document.selection.

    function getSelectedHTML(event) {
        // http://www.w3.org/TR/2000/REC-DOM-Level-2-Traversal-Range-20001113/ranges.html
        var range = window.getSelection ? window.getSelection()  /* W3C */
        : document.getSelection ? document.getSelection() /* redundant? */
        : document.selection ? document.selection.createRange()   /* IE */
        : null;
    
        if (range) {
            if (range.getRangeAt) {
                range = range.getRangeAt(0);
            } else if (range.setStart) { // Safari 1.3
                // Create range by itself
                range.setStart(range.anchorNode, range.anchorOffset);
                range.setEnd(range.focusNode, range.focusOffset);
            } else {
                // IE is already reange
            }
    
            var html = null, link = null;
            if (range.cloneContents) {
                var dummy = document.createElement('div');
                dummy.appendChild(range.cloneContents());
                html = dummy.innerHTML;
            } else {
                html = range.htmlText; /* IE */
            }
    
            if (html) {
                link = html.match(/<a.*?href\s*?=['"](.*?)['"]/);
                return link ? link[1] : null;
            }
        }
    
        return null;
    }
    

    This code should be checked especially with old browsers.

    Here is the sample fiddle: http://jsfiddle.net/tokkonoPapa/CQ63a/