1 // Copyright 2014 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.
8 * Constructor for the Nacl bridge to the whispernet wrapper.
9 * @param {string} nmf The relative path to the nmf containing the location of
10 * the whispernet Nacl wrapper.
11 * @param {function()} readyCallback Callback to be called once we've loaded the
14 function NaclBridge(nmf, readyCallback) {
15 this.readyCallback_ = readyCallback;
17 this.isEnabled_ = false;
18 this.naclId_ = this.loadNacl_(nmf);
22 * Method to send generic byte data to the whispernet wrapper.
23 * @param {Object} data Raw data to send to the whispernet wrapper.
25 NaclBridge.prototype.send = function(data) {
26 if (this.isEnabled_) {
27 this.embed_.postMessage(data);
29 console.error('Whisper Nacl Bridge not initialized!');
34 * Method to add a listener to Nacl messages received by this bridge.
35 * @param {function(Event)} messageCallback Callback to receive the messsage.
37 NaclBridge.prototype.addListener = function(messageCallback) {
38 this.callbacks_.push(messageCallback);
42 * Method that receives Nacl messages and forwards them to registered
44 * @param {Event} e Event from the whispernet wrapper.
47 NaclBridge.prototype.onMessage_ = function(e) {
48 if (this.isEnabled_) {
49 this.callbacks_.forEach(function(callback) {
56 * Injects the <embed> for this nacl manifest URL, generating a unique ID.
57 * @param {string} manifestUrl Url to the nacl manifest to load.
58 * @return {number} generated ID.
61 NaclBridge.prototype.loadNacl_ = function(manifestUrl) {
62 var id = 'nacl-' + Math.floor(Math.random() * 10000);
63 this.embed_ = document.createElement('embed');
64 this.embed_.name = 'nacl_module';
65 this.embed_.width = 1;
66 this.embed_.height = 1;
67 this.embed_.src = manifestUrl;
69 this.embed_.type = 'application/x-pnacl';
71 // Wait for the element to load and callback.
72 this.embed_.addEventListener('load', this.onNaclReady_.bind(this));
73 this.embed_.addEventListener('error', this.onNaclError_.bind(this));
75 // Inject the embed string into the page.
76 document.body.appendChild(this.embed_);
78 // Listen for messages from the NaCl module.
79 window.addEventListener('message', this.onMessage_.bind(this), true);
84 * Called when the Whispernet wrapper is loaded.
87 NaclBridge.prototype.onNaclReady_ = function() {
88 this.isEnabled_ = true;
89 if (this.readyCallback_)
90 this.readyCallback_();
94 * Callback that handles Nacl errors.
95 * @param {string} msg Error string.
98 NaclBridge.prototype.onNaclError_ = function(msg) {
99 // TODO(rkc): Handle error from NaCl better.
100 console.error('NaCl error', msg);