Bookmarklet which captures selected content including html tags

前端 未结 2 1892
梦如初夏
梦如初夏 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: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

提交回复
热议问题