我目前正在使用以下内容将网页中的选定文本转换为自定义的Firefox扩展程序:
getSelectedText: function(){
var textWindow = document.commandDispatcher.focusedWindow;
var text = textWindow.getSelection();
if (text == null) {text =' ';}
text = text.toString();
text = text.replace(/^\s*$/ , "");
text = text.replace(/\r/g, "\r");
text = text.replace(/\n/g, "\n");
text = text.replace(/^\s+|\s+$/g , " ");
text = text.replace(new RegExp(/\u2019/g), "'");
text = text.replace(new RegExp(/\u201A/g), ",");
text = text.replace(new RegExp(/\u201B/g), "'");
return {str:text};
}
这适用于纯文本。
我的问题是我想要复制网页的所有元素(有点像safari中的webclips功能)
用例 - 如果用户选择带有格式化文本和图片的网页,我也希望复制基础HTML,以便我可以准确地将其粘贴到另一个XUL窗口中 - 甚至如果我愿意,可以将内容作为丰富的HTML电子邮件发送。
任何指针?
答案 0 :(得分:9)
尝试使用此代码:
var range = window.getSelection().getRangeAt(0);
var content = range.cloneContents();
执行此代码后,content
将成为包含select DOM节点副本的文档片段。请注意,不会克隆事件侦听器。有关更多信息,请转至https://developer.mozilla.org/en/DOM/range.cloneContents