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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
<!DOCTYPE HTML>
<html>
<head>
<title>Test for content script</title>
<script type="text/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript" src="/tests/SimpleTest/SpawnTask.js"></script>
<script type="text/javascript" src="/tests/SimpleTest/ExtensionTestUtils.js"></script>
<script type="text/javascript" src="head.js"></script>
<link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
</head>
<body>
<script type="text/javascript">
"use strict";
/* eslint-disable mozilla/balanced-listeners */
add_task(function* test_postMessage() {
let extensionData = {
manifest: {
content_scripts: [
{
"matches": ["http://mochi.test/*/file_sample.html"],
"js": ["content_script.js"],
"run_at": "document_start",
"all_frames": true,
},
],
web_accessible_resources: ["iframe.html"],
},
background() {
browser.test.sendMessage("iframe-url", browser.runtime.getURL("iframe.html"));
},
files: {
"content_script.js": function() {
window.addEventListener("message", event => {
if (event.data == "ping") {
event.source.postMessage({pong: location.href},
event.origin);
}
});
},
"iframe.html": `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="content_script.js"><\/script>
</head>
</html>`,
},
};
let createIframe = url => {
let iframe = document.createElement("iframe");
return new Promise(resolve => {
iframe.src = url;
iframe.onload = resolve;
document.body.appendChild(iframe);
}).then(() => {
return iframe;
});
};
let awaitMessage = () => {
return new Promise(resolve => {
let listener = event => {
if (event.data.pong) {
window.removeEventListener("message", listener);
resolve(event.data);
}
};
window.addEventListener("message", listener);
});
};
let extension = ExtensionTestUtils.loadExtension(extensionData);
yield extension.startup();
let iframeURL = yield extension.awaitMessage("iframe-url");
let testURL = SimpleTest.getTestFileURL("file_sample.html");
for (let url of [iframeURL, testURL]) {
info(`Testing URL ${url}`);
let iframe = yield createIframe(url);
iframe.contentWindow.postMessage(
"ping", url);
let pong = yield awaitMessage();
is(pong.pong, url, "Got expected pong");
iframe.remove();
}
yield extension.unload();
});
</script>
</body>
</html>
|