5

I noticed the following new feature in Craft CMS 2.6.2973: Added the “HTML Purifier Config” setting to Rich Text fields.

I can't see any mention or any example of config files in the Craft CMS docs for Rich Text fields though, and the only thing I can see in the Rich Text Field settings in the control panel is this:

You can save custom HTML Purifier configs as .json files in craft/config/htmlpurifier/. View available settings

Can someone help me with a custom HTML Purifier config .json file that I can use with Craft that would allow me to start using YouTube video embed code like this in Rich Text fields?

<iframe width="560" height="315" src="https://www.youtube.com/embed/HdYfAmrzVlc" frameborder="0" allowfullscreen=""></iframe>

At the moment, the above code will disappear when saving an entry unless I disable the Purify HTML? option in the Rich Text field settings. Thanks in advance for any help with this.

8

Something like this in a .json file should work:

{
  "HTML.SafeIframe": true,
  "URI.SafeIframeRegexp": "%^(https?:)?//(www\.youtube(?:-nocookie)?\.com/embed/)%",
  "Attr.AllowedFrameTargets": ["_blank"],
  "HTML.AllowedComments": ["pagebreak"]
}

Note that the first two lines were adapted from https://stackoverflow.com/a/12784081/684 and the last two are the default options that Craft uses if no custom config is set.

Probably also worth giving this a read: http://htmlpurifier.org/docs/enduser-youtube.html

  • Just note that the HtmlPurifier link is pretty out of date since it talks about YouTube videos as being a Flash embed. I think they've been using iframes for a few years now which have a better security model. – Simon East May 2 '17 at 10:25
  • Sorry for the delay in replying Brad! Just a quick comment to say that this did the trick for me, thanks. – Stephen Aug 3 '17 at 23:48
  • What should the json file be named though? Cant find any info on that – Laurence Cope Dec 30 '18 at 16:46
3

Following from Brad's answer (I'm not able to comment) I had to escape the backslashes to avoid JSON decode error.

Version for Youtube and Vimeo

{
    "HTML.SafeIframe": true,
    "URI.SafeIframeRegexp": "%^(https?:)?//(www\\.youtube(?:-nocookie)?\\.com/embed/|player\\.vimeo\\.com/video/)%",
    "Attr.AllowedFrameTargets": ["_blank"],
    "HTML.AllowedComments": ["pagebreak"]
}

Or just YouTube

{
    "HTML.SafeIframe": true,
    "URI.SafeIframeRegexp": "%^(https?:)?//(www\\.youtube(?:-nocookie)?\\.com/embed/)%",
    "Attr.AllowedFrameTargets": ["_blank"],
    "HTML.AllowedComments": ["pagebreak"]
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.