获取文本选择的HTML

时间:2015-05-07 23:22:13

标签: javascript html google-chrome google-chrome-extension formatting

我无法理解代码(我是JS的新手)并且大多数代码对我不起作用。我正在构建Chrome扩展程序,以便在弹出窗口内的网页上显示文本选择。但文本选择不会显示在控制台中。 此外,我需要保留所选文本的格式并将其显示在popup.html中。

popup.html

<html>
  <head>
  </head>
  <body>
    <script src="jquery-1.11.3.min.js"></script>
    <script src="popup.js"></script>
    <div contenteditable="true" id="para">Some text</div>
  </body>
</html>

popup.js

window.onload=getSelectionHtml;
function getSelectionHtml() {
var html = "";
if (typeof window.getSelection != "undefined") {
    var sel = window.getSelection();
    if (sel.rangeCount) {
        var container = document.createElement("div");
        for (var i = 0, len = sel.rangeCount; i < len; ++i) {
            container.appendChild(sel.getRangeAt(i).cloneContents());
        }
        html = container.innerHTML;
    }
} else if (typeof document.selection != "undefined") {
    if (document.selection.type == "Text") {
        html = document.selection.createRange().htmlText;
    }
}

console.log(html);

return html;
}

我尝试在第二个if语句上设置断点,但即使在我选择文本后,值sel.rangeCount也没有改变(它保持为零)并且if子句没有执行。

Stackoverflow上的类似答案

Uncaught IndexSizeError: Failed to execute 'getRangeAt' on 'Selection': 0 is not a valid index

Chrome doesn't get the selected html string wrapping tags (contenteditable)

Get page selection including HTML?

Select text in javascript

Determine which DOM elements the current text selection contains

Get elements in text selection

How to copy formatting from the selected text?

此代码取自

Chrome doesn't get the selected html string wrapping tags (contenteditable)

我差点忘了!

直观地说,我认为我正在寻找的东西可能已在这里得到解答(上面引用)。我也尝试了这个,并下载了由Arne Roomann-Kurrik上传的chrome-extension,它没有帮助。

Get page selection including HTML?

0 个答案:

没有答案