Skip to content

Instantly share code, notes, and snippets.

@ybootin
Last active June 8, 2023 16:45
Show Gist options
  • Save ybootin/1222b5a989a3efc69383fb0b0264efea to your computer and use it in GitHub Desktop.
Save ybootin/1222b5a989a3efc69383fb0b0264efea to your computer and use it in GitHub Desktop.
Iframe content injection test
<!DOCTYPE html>
<html>
<head></head>
<body>
<script async defer>
function getHtmlContent(from) {
let htmlSample =
`
<h1>I'm injected from ${from}! </h1>
<scr` +
`ipt>
try {
window.top.console.log("log from ${from}")
} catch(e) {
console.error('${from} ==> error accessing top window', e)
}
</scr` +
`ipt>
`;
return htmlSample;
}
let createIframe = () => {
const iframe = document.createElement('iframe');
iframe.style = 'width:100%;height: 300px';
iframe.setAttribute('border', '0');
iframe.setAttribute('allow', '*');
return iframe;
};
// blob
const blob = new Blob([getHtmlContent('blob')]);
const blobUrl = URL.createObjectURL(blob);
const blobIframe = createIframe();
blobIframe.src = blobUrl;
// base64
const b64Content = btoa(getHtmlContent('b64'));
const b64Url = 'data:text/html;base64,' + b64Content;
const b64Iframe = createIframe();
b64Iframe.setAttribute('sandbox', 'allow-top-navigation allow-scripts allow-same-origin')
b64Iframe.src = b64Url;
// srcdoc
const srcdocIframe = createIframe();
srcdocIframe.srcdoc = getHtmlContent('srcdoc');
// document.write
const docwriteIframe = createIframe();
// inject content inside iframe body directly, let the browser create the boiler plate code
const innerHtmlBody = createIframe();
let iframes = [
['blob', blobIframe],
['base64', b64Iframe],
['srcdoc', srcdocIframe],
['document.write', docwriteIframe],
['innerHtmlBody', innerHtmlBody],
];
iframes.forEach(([name, iframe], index) => {
const container = document.createElement('div');
container.innerHTML = `
<h1>${name}<h1>
<div id="container-${index}"></div>`;
document.body.appendChild(container);
document.getElementById('container-' + index).appendChild(iframe);
});
docwriteIframe.contentWindow.document.write(
getHtmlContent('document.write')
);
docwriteIframe.contentWindow.document.close();
innerHtmlBody.contentWindow.document.body.innerHTML = getHtmlContent('innerHtmlBody')
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment