以下是一个 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();
}
}
示例 iframe
如下所示:
<iframe id="iframeId" type="html" src="__FILE_PATH__" width="100%" height="750px;"></iframe>
实现如下:
var content = getIframeSelectionText(document.getElementById("iframeId"));
我得到的是所选的文本。我需要 HTML
(因为我也想捕获图像)
我尝试将 .html()
添加到 getSelection()
但没有成功。
解决方案也可以涉及 jQuery
。
如何前进?
---编辑---
这里有一个关闭提示:window.getSelection() gives me the selected text, but I want the HTML
对相关Selection
对象的引用位于:https://developer.mozilla.org/en-US/docs/Web/API/Selection
---可能的解决方案---
这是我面临的类似(不相同)问题的解决方案:https://stackoverflow.com/a/124929/2284357 另一个是 Get Selected HTML in browser via Javascript
最佳答案
这将返回选定的文本节点
let node = iframe.contentWindow.getSelection().baseNode
之后可用于获取父节点 HTML
let html = node.parentElement.innerHTML
关于javascript - 使用 Javascript/jQuery 从 iframe 选择 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42298386/