【问题标题】:How to inject HTML into a template with polymer如何将 HTML 注入到带有聚合物的模板中
【发布时间】:2014-03-05 13:49:00
【问题描述】:

我正在使用 polymer-jsonp 执行 JSONP 请求,但响应有时包含 html。

例如,假设 post.content 是 "<strong>Foo</strong> bar",我如何显示 {{post.content}} 以使 "Foo" 以粗体显示?

<polymer-element name="feed-element" attributes="">
  <template>
    <template repeat="{{post in posts.feed.entry}}">
      <p>{{post.content}}</p>
    </template>
    <polymer-jsonp url="url" response="{{posts}}"></polymer-jsonp>
  </template>
  <script>
    Polymer('feed-element', {
      created: function() { },
      attached: function() { },
      detached: function() { },
      attributeChanged: function(attrName, oldVal, newVal) { }
    });
  </script>
</polymer-element>

【问题讨论】:

标签: javascript json polymer


【解决方案1】:

Polymer 不会通过数据绑定标记未转义的 HTML,因为它会成为 XSS 攻击的漏洞。

目前正在讨论如何在有限的情况下标记 HTML,或者允许自定义过滤,但这还没有在数据层实现。

现在可以使用额外的自定义元素来做你想做的事,但再次提醒你,如果你将不受信任的 HTML 渲染到你的页面中,可能会发生坏事。

下面是一个展示这种技术的例子:

http://jsbin.com/durajiwo/1/edit

【讨论】:

  • Scott 使用 Flickr 的 jsonp API 和 &lt;polymer-jsonp&gt;: jsbin.com/zoduhoqu/1/edit 的技术示例
  • juicy-html 是否也容易受到 XSS 攻击?我想答案是肯定的,但只是检查
  • @Scott,您能否就需要额外的元素来实现这一点发表更多评论?
  • 你不需要 有一个额外的元素。你总是可以做this.innerHTML = ...。这个想法是,我们不能允许您直接将数据绑定到 HTML,除非您执行 something 以明确进入危险区域。有些人使用试图明确禁止innerHTML 的预处理器,其他团队需要输入消毒剂。有多种解决方案,我们可以在这方面进行改进。
【解决方案2】:

对于那些寻找聚合物 1.0

<dom-module id="html-echo">
  <style>
    :host {
      display: block;
    }
  </style>
  <template>
  </template>
</dom-module>

<script>
  (function () {
    Polymer({
      is: 'html-echo',
      properties: {
        html: {
          type: String,
          observer: '_htmlChanged'
        }
      },
      _htmlChanged: function (neo) {
        // WARNING: potential XSS vulnerability if `html` comes from an untrusted source
        this.innerHTML = neo;
      }
    });
  })();
</script>

【讨论】:

  • 请记住,由于绑定是在预渲染时静态计算的,因此您的命令式声明(如 [[foo]]{{bar}})将无法在您的新 html 中使用,因为它们是在渲染后添加的。
  • 如何在这个方法中调用 post render ?
  • this.innerHTML = postProcess(neo); 这适合你吗?@Ali.MD
  • 我认为在 Polymer 1.0 中,
【解决方案3】:

如果您确定这是您想要做的,只需使用innerHTML

_renderHtml: function(html) {
  this.$.dynamicHtmlContainer.innerHTML = html;
}

或者动态添加 shadow-dom 子节点:

_renderHtml: function(html) {
  var div = document.createElement('div');
  div.innerHTML = html;
  Polymer.dom(this).appendChild(div);
}

我认为 Polymer.dom 在 Polymer 2.0 中已被删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多