0

HTML code copied from MS Word into any web browser (except IE) comes with some conditional comments that contains important data for me. Like the following snippet:

<p class="MsoToc1">
<!--[if supportFields]>
    ...
<![endif]-->A Section of my Document&nbsp;...&nbsp;
<!--[if supportFields]>
    ... PAGEREF _Toc360610812 ...
<![endif]-->3<!--[if gte mso 9]>
    ...
<![endif]-->
</p>

I can read and parse the content of the comments on Firefox and Chrome using JavaScript, but IE "removes" the conditional comments before I can actually parse them. Their documentation states that everything inside conditional comments is ignored "at the parsing level".

The current technique I'm using to capture the pasted HTML is widely used by WYSIWYG editors, and is well described in this answer. Basically I create a "contenteditable" element on my document and instruct the user to paste inside that element. The browser then inserts the pasted code into the document. Then I use some JavaScript to extract the inserted code and modify it.

But that is probably the main cause of the comment-stripping problem. Right after the paste event, the pasted code is inserted into the document. And at that point, IE simply strips out the content of conditional comments.

So, are there alternative ways to capture the clipboard content that would allow me to get the data with the comments preserved?

4

1 回答 1

0

如果您想复制评论,您需要从其中复制内容,.childNodes而不是查看.innerHTML属性或.children列表。该.childNodes列表包含所有 DOM 节点,包括文本和评论节点,因此您可以执行以下操作:

var div = createElementFrom(codeThatGetsPasted);
var target = document.querySelector(selectorForOnPageElement);
var childarray = Array.prototype.slice.call(div.childNodes);
childarray.forEach(function(child) {
 target.appendChild(child);
});

那应该将条件注释放入目标元素中。也就是说,我不知道 DOMContentLoaded 发生后 IE 是否会解析它们。

于 2013-09-13T16:55:10.277 回答