Following is a javaScript
function to get selected content from an iframe
function getIframeSelectionText(iframe) {
var win = iframe.contentWindow;
var doc = win.document;
if (win.getSelection) {
return win.getSelection();
} else if (doc.selection && doc.selection.createRange) {
return doc.selection.createRange();
}
}
The Sample iframe
looks like this:
<iframe id="iframeId" type="html" src="__FILE_PATH__" width="100%" height="750px;"></iframe>
The implementation looks like:
var content = getIframeSelectionText(document.getElementById("iframeId"));
What I get is the text selected. I need HTML
(because I want to catch the images too)
I tried adding .html()
to getSelection()
but didn't work. Solution can involve jQuery
too.
How to go forward?
---EDIT---
A close hint is found here: window.getSelection() gives me the selected text, but I want the HTML
A reference to the Selection
object in question is here: https://developer.mozilla.org/en-US/docs/Web/API/Selection
---POSSIBLE SOLUTION---
Here is a solution to the similar(not the same) problem I'm facing: https://stackoverflow.com/a/124929/2284357 and another one is Get Selected HTML in browser via Javascript
This returns the selected text node
let node = iframe.contentWindow.getSelection().baseNode
which afterwards can be used to get the parent node HTML
let html = node.parentElement.innerHTML
This should get you on the right path...
$("body").on("click","#iframeId",function(){
$(this).contents().find("html").html();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.