xo-bus
Version:
Cross Origin Event Bus
87 lines (74 loc) • 2.69 kB
HTML
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>Channel messaging demo</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300|Lobster+Two' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="style.css">
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<h1>Cross origin Channel messaging demo</h1>
<p id="message-output">Message not yet sent</p>
<div onclick="clicked()">
<label for="message-input">Send a message</label>
<input type="text" id="message-input" autofocus>
<button>Send Message</button>
<button onclick='reload()'>reload</button>
<div id="debug"></div>
</div>
<div>
<div>
<iframe src="http://localhost:8001/example/page1.html" width='480' height='320'></iframe>
<iframe src="http://localhost:8002/example/page2.html" width='480' height='320'></iframe>
</div>
</div>
<script src="http://localhost:8000/lib/eventbus.js"></script>
<script>
var input = document.getElementById('message-input');
var output = document.getElementById('message-output');
var button = document.querySelector('button');
var iframe = document.querySelector('iframe');
const eb = new CrossOriginEventBus()
document.querySelectorAll('iframe').forEach((iframe) => {
iframe.addEventListener('load', () => {
eb.controller.addChild(iframe)
})
})
button.addEventListener('click', onClick);
function onClick(e) {
e.preventDefault();
eb.send({type: 'input', value: input.value})
}
eb.subscribe('added', (e) => {
output.innerHTML = e.data.value;
input.value = '';
})
eb.registerService('test', () => {
return new Promise(res => {
setTimeout(() => res('hahaha'))
})
})
function reload() {
document.querySelectorAll('iframe').forEach(iframe => iframe.remove())
var i = document.createElement('iframe')
i.src = 'http://localhost:8002/example/page2.html'
i.width = '480'
i.height = '320'
document.body.appendChild(i)
i.addEventListener('load', () => {
eb.controller.addChild(i)
})
}
function clicked() {
const debugEl = document.querySelector('#debug')
debugEl.textContent = eb.controller.outPorts.size
}
clicked()
</script>
</body>
</html>