OLD | NEW |
(Empty) | |
| 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. |
| 4 |
| 5 var Event = require('event_bindings').Event; |
| 6 var messagingNatives = requireNative('messaging_natives'); |
| 7 var utils = require('utils'); |
| 8 |
| 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; |
| 13 this.name = opt_name; |
| 14 |
| 15 var portSchema = {name: 'port', $ref: 'runtime.Port'}; |
| 16 var messageSchema = {name: 'message', type: 'any', optional: true}; |
| 17 var options = {unmanaged: true}; |
| 18 |
| 19 this.onDisconnect = new Event(null, [portSchema], options); |
| 20 this.onMessage = new Event(null, [messageSchema, portSchema], options); |
| 21 this.onDestroy_ = null; |
| 22 } |
| 23 |
| 24 // Sends a message asynchronously to the context on the other end of this |
| 25 // port. |
| 26 Port.prototype.postMessage = function(msg) { |
| 27 // JSON.stringify doesn't support a root object which is undefined. |
| 28 if (msg === undefined) |
| 29 msg = null; |
| 30 msg = $JSON.stringify(msg); |
| 31 if (msg === undefined) { |
| 32 // JSON.stringify can fail with unserializable objects. Log an error and |
| 33 // drop the message. |
| 34 // |
| 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'); |
| 40 return; |
| 41 } |
| 42 messagingNatives.PostMessage(this.portId_, msg); |
| 43 }; |
| 44 |
| 45 // Disconnects the port from the other end. |
| 46 Port.prototype.disconnect = function() { |
| 47 messagingNatives.CloseChannel(this.portId_, true); |
| 48 this.destroy_(); |
| 49 }; |
| 50 |
| 51 Port.prototype.destroy_ = function() { |
| 52 // Note: it's not necessary to destroy the onDisconnect/onMessage events |
| 53 // because they're unmanaged. |
| 54 if (this.onDestroy_) |
| 55 this.onDestroy_(); |
| 56 messagingNatives.PortRelease(this.portId_); |
| 57 }; |
| 58 |
| 59 exports.Port = utils.expose('Port', Port, { |
| 60 functions: ['disconnect', 'postMessage'], |
| 61 properties: ['name', 'onDisconnect', 'onMessage'] |
| 62 }); |
OLD | NEW |