Created
July 24, 2013 21:49
-
-
Save kharmabum/6074896 to your computer and use it in GitHub Desktop.
Get selected text from the browswer window
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
selectedText: function() { | |
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; | |
} | |
} | |
// Strip out any .click elements from the HTML before converting it to text | |
var div = document.createElement('div'); | |
div.innerHTML = html; | |
$('.clicks', $(div)).remove(); | |
var text = div.textContent || div.innerText || ""; | |
return String(text).trim(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment