将页面的HTML片段复制到剪贴板



我正在开发web开发工具,我想使用Javascript将当前网页的HTML代码的一部分复制到剪贴板。

这可能涉及

  • 使用DOM获取问题中的HTML

  • 使用Javascript复制文本到剪贴板

有人知道这里有什么问题吗?例如,与剪贴板处理相关-当一个人不使用documentitable模式时,我是否需要创建一个隐藏的位置来放置用于复制的HTML有效载荷?

如果可能的话,我还想与所见即所得组件(如TinyMCE)进行交互,以便在可视编辑模式下粘贴HTML时,它会以格式化的HTML而不是纯文本的形式出现。

如果解决方案在Chrome和Firefox中工作就足够了。不需要支持ie浏览器

Javascript无法向剪贴板添加内容。好吧,至少没有一个是跨浏览器的。

然而,有一个flash解决方案可以很好地工作。http://code.google.com/p/zeroclipboard/

我们开发了一个小的Firefox-AddOn,用于在从编辑器复制/粘贴内容时删除特殊字符(连字符)。这是必要的,因为没有javascript方法来填充剪贴板中的任何内容。我想它应该是可以为Chrome写一个扩展太(谷歌是你的朋友在这里)。在我看来,这似乎是你得到你想要的东西的唯一方法。

例子:下面是firefox插件删除特殊字符onCopy

所需的代码片段
// get Clipboard Object
var clip  = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
// get Transferable Object
    var tr_unicode = new Transferable(); 
var tr_html    = new Transferable();
// read "text/unicode flavors" (the clipboard has several "flavours" (html, plain text, ...))
    tr_unicode.addDataFlavor("text/unicode");
tr_html.addDataFlavor("text/html");
    clip.getData(tr_unicode, clip.kGlobalClipboard); // Systemclipboard
    clip.getData(tr_html, clip.kGlobalClipboard); // Systemclipboard
// generate objects to write the contents into (used for the clipboard)         
    var unicode = { }, ulen = { }, html = { }, hlen = { };
tr_html.getTransferData("text/html", html, hlen);
tr_unicode.getTransferData("text/unicode", unicode, ulen);
var unicode_obj = unicode.value.QueryInterface(Components.interfaces.nsISupportsString);
var html_obj    = html.value.QueryInterface(Components.interfaces.nsISupportsString);
// we remove Softhyphen and another control character here
var re = new RegExp('[u200b' + String.fromCharCode(173)+ ']','g');
if (unicode_obj && html_obj)
{
    var unicode_str = unicode_obj.data.replace(re, '');
    var html_str    = html_obj.data.replace(re, '');
    // Neue Stringkomponenten für unicode und HTML-Content anlegen      
    var unicode_in = new StringComponent();
    unicode_in.data = unicode_str;
    var html_in = new StringComponent();
    html_in.data = html_str;
    // generate new transferable to write the data back to the clipboard
    // fill html + unicode flavors
    var tr_in = new Transferable();
    tr_in.setTransferData("text/html", html_in, html_in.data.length * 2);
    tr_in.setTransferData("text/unicode", unicode_in, unicode_in.data.length * 2);
    // copy content from transferable back to clipboard     
    clip.setData(tr_in, null, clip.kGlobalClipboard);
}

最新更新