使用Javascript / jQuery从iframe中选择HTML [英] Select HTML from iframe using Javascript / jQuery

查看:103
本文介绍了使用Javascript / jQuery从iframe中选择HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一个 javaScript 函数,用于从 iframe中获取所选内容

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();
    }
}

示例 iframe 看起来像这样:

<iframe id="iframeId" type="html" src="__FILE_PATH__" width="100%" height="750px;"></iframe>

实现如下:

var content = getIframeSelectionText(document.getElementById("iframeId"));

我得到的是所选文字。我需要 HTML (因为我也想抓住图片)

What I get is the text selected. I need HTML(because I want to catch the images too)

我尝试添加 .html() getSelection()但是没有用。
解决方案也可能涉及 jQuery

I tried adding .html() to getSelection() but didn't work. Solution can involve jQuery too.

如何前进?

---编辑---

此处有一个紧密的提示: window.getSelection()为我提供了所选文本,但我想要HTML

A close hint is found here: window.getSelection() gives me the selected text, but I want the HTML

此处对 Selection 对象的引用如下: https://developer.mozilla.org/en-US/docs/Web/API/Selection

A reference to the Selection object in question is here: https://developer.mozilla.org/en-US/docs/Web/API/Selection

---可能的解决方案---

这里是我面临的类似(不一样)问题的解决方案: https://stackoverflow.com/a/124929/2284357
和另一个获取选择通过Javascript在浏览器中编辑HTML

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

之后可用于获取父节点HTML

which afterwards can be used to get the parent node HTML

let html = node.parentElement.innerHTML

这篇关于使用Javascript / jQuery从iframe中选择HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆