-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathindex.html
59 lines (53 loc) · 1.79 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<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" />
</head>
<body>
<h1>Channel messaging demo</h1>
<p id="message-output">Message not yet sent</p>
<form>
<label for="message-input">Send a message</label>
<input type="text" id="message-input" autofocus />
<button>Send Message</button>
</form>
<iframe src="page2.html" width="480" height="320"></iframe>
<script>
const input = document.getElementById("message-input");
const output = document.getElementById("message-output");
const button = document.querySelector("button");
const iframe = document.querySelector("iframe");
const channel = new MessageChannel();
const port1 = channel.port1;
// Wait for the iframe to load
iframe.addEventListener("load", onLoad);
function onLoad() {
// Listen for button clicks
button.addEventListener("click", onClick);
// Listen for messages on port1
port1.onmessage = onMessage;
// Transfer port2 to the iframe
iframe.contentWindow.postMessage("init", "*", [channel.port2]);
}
// Post a message on port1 when the button is clicked
function onClick(e) {
e.preventDefault();
port1.postMessage(input.value);
}
// Handle messages received on port1
function onMessage(e) {
output.innerHTML = e.data;
input.value = "";
}
</script>
</body>
</html>