Select HTML from iframe using Javascript / jQuery

戏子无情 提交于 2019-12-12 10:20:01

问题


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


回答1:


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



回答2:


This should get you on the right path...

$("body").on("click","#iframeId",function(){ 
    $(this).contents().find("html").html();


来源:https://stackoverflow.com/questions/42298386/select-html-from-iframe-using-javascript-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!