OLD | NEW |
(Empty) | |
| 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. |
| 4 |
| 5 import 'dart:convert'; |
| 6 import 'dart:html'; |
| 7 |
| 8 import 'package:stream_channel/stream_channel.dart'; |
| 9 |
| 10 /// Constructs a [StreamChannel] wrapping `postMessage` communication with the |
| 11 /// host page. |
| 12 StreamChannel postMessageChannel() { |
| 13 var controller = new StreamChannelController(sync: true); |
| 14 |
| 15 window.onMessage.listen((message) { |
| 16 // A message on the Window can theoretically come from any website. It's |
| 17 // very unlikely that a malicious site would care about hacking someone's |
| 18 // unit tests, let alone be able to find the test server while it's |
| 19 // running, but it's good practice to check the origin anyway. |
| 20 if (message.origin != window.location.origin) return; |
| 21 message.stopPropagation(); |
| 22 |
| 23 // See host.dart for why we have to explicitly decode here. |
| 24 controller.local.sink.add(JSON.decode(message.data)); |
| 25 }); |
| 26 |
| 27 controller.local.stream.listen((data) { |
| 28 // TODO(nweiz): Stop manually adding href here once issue 22554 is |
| 29 // fixed. |
| 30 window.parent.postMessage({ |
| 31 "href": window.location.href, |
| 32 "data": data |
| 33 }, window.location.origin); |
| 34 }); |
| 35 |
| 36 // Send a ready message once we're listening so the host knows it's safe to |
| 37 // start sending events. |
| 38 window.parent.postMessage({ |
| 39 "href": window.location.href, |
| 40 "ready": true |
| 41 }, window.location.origin); |
| 42 |
| 43 return controller.foreign; |
| 44 } |
OLD | NEW |