Zalem
Zalem

Reputation: 164

Create sandboxed iFrame via jQUery

I am trying to create an iFrame without any permissions using jQuery. I am able to add the iFrame attribute, but it expects a value. I am using a dirty solution by adding an empty value (' ') but is this the right way? Is there a better way to create an permission-less sandboxed iFrame?

$(function() {
  $('article').each(createIFrame);
});

function createIFrame() {
  setArticleContent($(this), 'hello sandbox');
}

function setArticleContent(article, content) {
  article.find('span>p').first().text('');
  $('<iframe>', {
    srcdoc: '<p>' + content + '</p>',
    frameborder: '0',
    sandbox: ' ',
    style: 'background:#00FF00',
  }).appendTo(article.find('span>p').first());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<article>
  <span>
        <p>helloworld</p>
      </span>
</article>

Upvotes: 1

Views: 446

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337530

I am using a dirty solution by adding an empty value (' ') but is this the right way?

It's not dirty at all, however you should note that according to the specs you should be using an empty string:

The value of the attribute can either be an empty string (all the restrictions are applied), or a space-separated list of tokens that lift particular restrictions

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox

$('<iframe>', {
  srcdoc: '<p>' + content + '</p>',
  frameborder: '0',
  sandbox: '', // note the space was removed
  style: 'background: #00FF00',
}).appendTo(article.find('span>p').first());

Ideally the style should be set through an external stylesheet too.

Upvotes: 1

Related Questions