使用Javascript / jQuery从iframe中选择HTML
以下是一个javaScript
函数,用于从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(); } }
Sample iframe
看起来像这样:
实现如下:
var content = getIframeSelectionText(document.getElementById("iframeId"));
我得到的是选中的文字。 我需要HTML
(因为我也想抓住图像)
我尝试将.html()
添加到getSelection()
但是没有用。 解决方案也可能涉及jQuery
。
怎么前进?
– -编辑 – –
这里有一个关闭提示: window.getSelection()为我提供了所选的文本,但我想要HTML
有关Selection
对象的引用如下: https : //developer.mozilla.org/en-US/docs/Web/API/Selection
—可能的解决方案—
这是我面临的类似(不一样)问题的解决方案: https : //stackoverflow.com/a/124929/2284357 ,另一个是通过Javascript在浏览器中获取选定的HTML
这将返回选定的文本节点
let node = iframe.contentWindow.getSelection().baseNode
之后可用于获取父节点HTML
let html = node.parentElement.innerHTML
这应该让你走上正确的道路……
$("body").on("click","#iframeId",function(){ $(this).contents().find("html").html();