Dart Language: how to convert a String into a Transferable (ByteBuffer)

1.9k views Asked by At

I'll be using window.postMessage("", "*", [transferableData]) to send data between two browser windows. However, I didn't find any straight answer on how to convert types into Transferables.

So, in order for me to start learning this, it would be great to know how to convert a simple String into an Transferable (ByteBuffer) and read it on the other side (the side that is getting the message with the data). This would help me solving my problem and learning about this concept.

IMPORTANT UPDATE:

This question led me here: Dart Language: printing reports

Transferable Objects are not yet implemented on Dart VM (http://dartbug.com/4149). That means, if you're running your application via Dartium (Dart VM) the other window will be receiving and processing the first argument of postMessage, and not the Transferable Object. However, JavaScript does the job: the object gets transfered and the original array, emptied.

1

There are 1 answers

10
Günter Zöchbauer On BEST ANSWER
import 'dart:convert';

var list = Utf8.encode('xxx');
var data = list is Uint8List ? list.buffer : new Uint8List.fromList(list).buffer;

to send the data using window.PostMessage use

window.postMessage({'data': data}, '*', [data]);

and read it on the receiver side like

var string = Utf8.decode(message.data['data']);

See also http://dartbug.com/19968 for the status of transferrables.
The recent Dart dev channel release already ships with Dartium 38.xxx as far as I know.
Here is a small test case for transferrables https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/tests/html/transferables_test.dart