|
<!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); |
|
|
|
|
|
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.onload = () => iframe.contentWindow.postMessage('start', '*'); |
|
</script> |
|
|
|
</body> |
|
</html> |
|
|