如何处理contenteditable中复制粘贴时URL相对/绝对路径的“错误”问题

3
contenteditable 区域中,如果你粘贴了一个带有 URL 属性的元素,在一些浏览器中,它会将 URL 从相对转换为绝对地址。

我看过一些 bug 报告称这在最新版本中已“修复”,但事实并非如此。

我编写了这个演示来展示问题:演示链接!

这很丑陋,我想知道最佳解决方法是什么。

  1. 第一个想法是使用 onpaste,在当前节点中找到所有的 anchor 并用正则表达式解析它。我认为这并不是理想的方法,但可能会有效。

  2. ???

  3. ???

我真希望他们能放手不管,不要通过 contenteditable 创建太多与浏览器相关的问题,但我猜这会使事情变得太容易了。

你对解决这个问题有什么想法吗?

2个回答

1
CKEditor在让浏览器打破数据之前,会将所有的srcnamehref属性复制到data-cke-saved-src|href属性中。不幸的是,由于数据是字符串,所以必须通过正则表达式来完成。您可以在此处找到代码:/core/htmldataprocessor.js#L772-L783
var protectElementRegex = /<(a|area|img|input|source)\b([^>]*)>/gi,
    // Be greedy while looking for protected attributes. This will let us avoid an unfortunate
    // situation when "nested attributes", which may appear valid, are also protected.
    // I.e. if we consider the following HTML:
    //
    //  <img data-x="&lt;a href=&quot;X&quot;" />
    //
    // then the "non-greedy match" returns:
    //
    //  'href' => '&quot;X&quot;' // It's wrong! Href is not an attribute of <img>.
    //
    // while greedy match returns:
    //
    //  'data-x' => '&lt;a href=&quot;X&quot;'
    //
    // which, can be easily filtered out (#11508).
    protectAttributeRegex = /([\w-]+)\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|(?:[^ "'>]+))/gi,
    protectAttributeNameRegex = /^(href|src|name)$/i;

function protectAttributes( html ) {
    return html.replace( protectElementRegex, function( element, tag, attributes ) {
        return '<' + tag + attributes.replace( protectAttributeRegex, function( fullAttr, attrName ) {
            // Avoid corrupting the inline event attributes (#7243).
            // We should not rewrite the existed protected attributes, e.g. clipboard content from editor. (#5218)
            if ( protectAttributeNameRegex.test( attrName ) && attributes.indexOf( 'data-cke-saved-' + attrName ) == -1 )
                return ' data-cke-saved-' + fullAttr + ' data-cke-' + CKEDITOR.rnd + '-' + fullAttr;

            return fullAttr;
        } ) + '>';
    } );
}

在处理来自可编辑元素的HTML时,data-cke-saved-*属性会覆盖原始属性。


哎呀,那是个相当费力的解决方法。不过这种方式很有趣。我构建了一个简单的函数,只找到基本网址并将其删除。我想我的方法还需要改进,因为像你说的,图像使用 src 而不是 href。感谢你的输入! - Casey Dwayne
有时候我会有这样的感觉,即 CKEditor 所做的一切都是在解决浏览器的 bug、怪癖和不一致性。;) - Reinmar
  • 而且这个列表还非常长。我也参考了你的编辑器和TinyMCE,但里面有太多“额外”的东西,让我不敢靠近(对于几乎所有第三方软件/插件都是如此)。从零开始开发... 至少可以说它很有教育意义 :)
- Casey Dwayne
Khem... :D 工作在 CKEditor 上已经两年了,我确实学到了很多东西。其中之一就是我永远不应该尝试使用 contenteditable 从头开始编写任何生产就绪的东西...但是,祝你好运! :) - Reinmar

0

这看起来像是一个与contenteditable无关的浏览器错误:https://bugzilla.mozilla.org/show_bug.cgi?id=805359

该问题在10年前被提出,最后一次更新是6年前。然而它仍然没有解决。

您可以在StackOverflow上看到这个错误。检查任何SO链接都会显示href值为相对URL。将其复制并粘贴为HTML时,相对链接将被重写为绝对URL。

例如:

enter image description here

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接