1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 var Event = require('event_bindings').Event;
6 var messagingNatives = requireNative('messaging_natives');
7 var utils = require('utils');
9 // Port object. Represents a connection to another script context through
10 // which messages can be passed.
11 function Port(portId, opt_name) {
12 this.portId_ = portId;
15 var portSchema = {name: 'port', $ref: 'runtime.Port'};
16 var messageSchema = {name: 'message', type: 'any', optional: true};
17 var options = {unmanaged: true};
19 this.onDisconnect = new Event(null, [portSchema], options);
20 this.onMessage = new Event(null, [messageSchema, portSchema], options);
21 this.onDestroy_ = null;
24 // Sends a message asynchronously to the context on the other end of this
26 Port.prototype.postMessage = function(msg) {
27 // JSON.stringify doesn't support a root object which is undefined.
28 if (msg === undefined)
30 msg = $JSON.stringify(msg);
31 if (msg === undefined) {
32 // JSON.stringify can fail with unserializable objects. Log an error and
35 // TODO(kalman/mpcomplete): it would be better to do the same validation
36 // here that we do for runtime.sendMessage (and variants), i.e. throw an
37 // schema validation Error, but just maintain the old behaviour until
38 // there's a good reason not to (http://crbug.com/263077).
39 console.error('Illegal argument to Port.postMessage');
42 messagingNatives.PostMessage(this.portId_, msg);
45 // Disconnects the port from the other end.
46 Port.prototype.disconnect = function() {
47 messagingNatives.CloseChannel(this.portId_, true);
51 Port.prototype.destroy_ = function() {
52 // Note: it's not necessary to destroy the onDisconnect/onMessage events
53 // because they're unmanaged.
56 messagingNatives.PortRelease(this.portId_);
59 exports.Port = utils.expose('Port', Port, {
60 functions: ['disconnect', 'postMessage'],
61 properties: ['name', 'onDisconnect', 'onMessage']