Select HTML from iframe using Javascript / jQuery

2019-06-14 09:31发布

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

2条回答
够拽才男人
2楼-- · 2019-06-14 09:56

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
查看更多
虎瘦雄心在
3楼-- · 2019-06-14 10:08

This should get you on the right path...

$("body").on("click","#iframeId",function(){ 
    $(this).contents().find("html").html();
查看更多
登录 后发表回答