Skip to content

Commit

Permalink
Exploring two messaging
Browse files Browse the repository at this point in the history
  • Loading branch information
pmalacho-mit committed Sep 23, 2024
1 parent 8fd5d84 commit cb0acbf
Showing 1 changed file with 20 additions and 11 deletions.
31 changes: 20 additions & 11 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,53 @@ import './style.css'
const setAppContent = (content: string) =>
document.querySelector<HTMLDivElement>('#app')!.innerHTML = content;

const makeListContainer = () => `<div><ul id="list"></ul></div>`;
const prependListElement = (content: string = "") => {
const list = document.getElementById('list')!;
list.innerHTML = `<li>${new Date().toLocaleTimeString()}: ${content}</li>` + list.innerHTML;
}

let state: "https" | "http" | "unknown" =
window.location.protocol === 'https:' ? "https"
: window.location.protocol === 'http:' ? "http"
: "unknown";

if (window.isSecureContext && state === 'http')
state = 'https'; // for localhost

const params = new URLSearchParams(window.location.search);

if (params.has('protocol')) {
state = params.get('protocol') === 'https' ? 'https' : 'http';
}


switch (state) {
case "https":
console.log('This page is served over HTTPS');
const inputID = 'input'
const buttonID = 'button'
setAppContent(`
<div>
<input type="text" placeholder="Enter URL" id=${inputID} />
<button id=${buttonID}>Open child page</button>
${makeListContainer()}
</div>
`);
let count = 0;
window.addEventListener('message', ({ data }) => prependListElement(data));
document.getElementById(buttonID)!.addEventListener('click', () => {
const url = (document.getElementById(inputID) as HTMLInputElement).value;
const otherWindow = window.open(url);
if (!otherWindow) {
alert('Please allow popups for this website');
return;
}
setInterval(() => otherWindow.postMessage('Hello from HTTPS site', url), 1000);
const popup = window.open(url);
if (!popup)
return alert('Please allow popups for this website');

setInterval(() => popup.postMessage(`HTTPS msg ${count++}`, url), 100);
});
break;
case "http":
console.log('This page is served over HTTP');
setAppContent(`<p>Open console to view messages being received.</p>`);
setAppContent(`<div>Messages: ${makeListContainer()}</div>`);
window.addEventListener('message', (event) => {
console.log('Received message:', event.data);
prependListElement(event.data);
event.source!.postMessage(`HTTP msg ${event.data}`, { targetOrigin: event.origin });
});
break;
case "unknown":
Expand Down

0 comments on commit cb0acbf

Please sign in to comment.