dev-tools / index.html
soiz1's picture
Update index.html
1d96306 verified
raw
history blame
1.53 kB
<!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>