Skip to content

Instantly share code, notes, and snippets.

@apua
Last active April 14, 2023 08:29
Show Gist options
  • Save apua/2f66ee1fc29412dad215991f929eca46 to your computer and use it in GitHub Desktop.
Save apua/2f66ee1fc29412dad215991f929eca46 to your computer and use it in GitHub Desktop.
Cross origin front-end HTTP API proxy
<script type="module">
window.addEventListener('message', async(event) => {
if (event.origin.match(/jenkins.internal.sifive.com/)) return;
if (! event.origin.match(/^http:\/\/localhost:|internal.sifive.com/)) return;
const path = event.data;
const resp = await fetch(path);
const json_data = await resp.json();
window.parent.postMessage(json_data, event.origin);
});
</script>
<html><head></head><body>
<iframe hidden src="https://myjenkins/userContent/cross-origin-proxy.html"></iframe>
<script type="module">
const iframe = document.querySelector('iframe');
const source = new URL(iframe.src);
document.querySelector('iframe').addEventListener('load', (event) => {
window.addEventListener('message', receiver);
iframe.contentWindow.postMessage('/computer/api/json', source.origin);
});
function receiver(event) {
if (event.origin != source.origin) return;
const json_data = event.data;
console.log('=>', json_data);
}
</script>
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment