File size: 1,531 Bytes
23443f5
39eaa9c
610a87b
23443f5
39eaa9c
610a87b
 
1d96306
7ee2971
610a87b
 
 
39eaa9c
610a87b
 
 
 
 
 
 
 
 
 
 
 
 
5379ab8
610a87b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39eaa9c
23443f5
39eaa9c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html lang="ja">
<head><meta charset="UTF-8"><title>iframe通信監視</title></head>
<body>

<h1>親ページ</h1>
<div id="log"></div>
<img src="/sjid.png" />
<script>
  const iframe = document.createElement('iframe');
  iframe.style.display = 'none';
  document.body.appendChild(iframe);

  // iframe内部コード(Blobにする)
  const iframeCode = `
    window.addEventListener('message', e => {
      if(e.data === 'start') {
        fetch('https://jsonplaceholder.typicode.com/posts/1')
          .then(res => res.text())
          .then(text => {
            parent.postMessage({ type: 'fetch-success', url: 'https://jsonplaceholder.typicode.com/posts/1', body: text.slice(0, 100) }, '*');
          })
          .catch(err => {
            parent.postMessage({ type: 'fetch-error', error: err.toString() }, '*');
          });
      }
    });
  `;

  const blob = new Blob([iframeCode], { type: 'application/javascript' });
  iframe.src = URL.createObjectURL(blob);

  window.addEventListener('message', e => {
    const log = document.getElementById('log');
    if(e.data.type === 'fetch-success') {
      log.innerHTML += `<div style="color:green">成功: ${e.data.url}<pre>${e.data.body}</pre></div>`;
    } else if(e.data.type === 'fetch-error') {
      log.innerHTML += `<div style="color:red">エラー: ${e.data.error}</div>`;
    }
  });

  // iframeが読み込み終わったら開始指示
  iframe.onload = () => iframe.contentWindow.postMessage('start', '*');
</script>

</body>
</html>