Bookmarklet which captures selected content including html tags

前端 未结 2 1857
梦如初夏
梦如初夏 2021-02-04 21:15

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 t

相关标签:
2条回答
  • 2021-02-04 22:01

    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.

    0 讨论(0)
  • 2021-02-04 22:08

    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);})()
    
    0 讨论(0)
提交回复
热议问题