Open2

iframe sandboxのメモ

syumaisyumai

iframe sandboxのメモ

parent windowに対するDOM操作

parent windowのDOMを変更するscriptを含んだiframeを用意して、sandboxの設定項目を変更することで挙動がどう変わるか確認する

サンプルコード

https://github.com/syumai/til/tree/a2cde5ea7d848e7ce35907d790a88fe630941878/iframe/modify-parent

iframe内のHTML

window.parent のbodyに、alertを表示するコードを含んだscript要素を追加する
このHTMLをiframeとしてロードすると、alertが表示される

<script>
  const script = document.createElement("script");
  script.text = "alert('hello!');"
  window.parent.document.body.appendChild(script);
</script>

ノーガード

<iframe src="iframe.html"></iframe>

alertが表示された

sandbox を追加

<iframe src="iframe.html" sandbox></iframe>

Blocked script execution in '...' because the document's frame is sandboxed and the 'allow-scripts' permission is not set.

allow-scripts permissionでブロックされた

sandbox="allow-scripts" を追加

<iframe src="iframe.html" sandbox="allow-scripts"></iframe>

Uncaught DOMException: Blocked a frame with origin "null" from accessing a cross-origin frame.

allow-same-origin を設定しておらず、iframeのoriginが "null" になっているため失敗した

sandbox="allow-scripts allow-same-origin" を追加

<iframe src="iframe.html" sandbox="allow-scripts allow-same-origin"></iframe>

alertが表示された

参考記事