1 // Copyright (c) 2012 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 // Set to true when the Document is loaded IFF "test=true" is in the query
9 // Set to true when loading a "Release" NaCl module, false when loading a
10 // "Debug" NaCl module.
13 // Javascript module pattern:
14 // see http://en.wikipedia.org/wiki/Unobtrusive_JavaScript#Namespaces
15 // In essence, we define an anonymous function which is immediately called and
16 // returns a new object. The new object contains only the exported definitions;
17 // all other definitions in the anonymous function are inaccessible to external
19 var common
= (function() {
21 function isHostToolchain(tool
) {
22 return tool
== 'win' || tool
== 'linux' || tool
== 'mac';
26 * Return the mime type for NaCl plugin.
28 * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
29 * @return {string} The mime-type for the kind of NaCl plugin matching
30 * the given toolchain.
32 function mimeTypeForTool(tool
) {
33 // For NaCl modules use application/x-nacl.
34 var mimetype
= 'application/x-nacl';
35 if (isHostToolchain(tool
)) {
36 // For non-NaCl PPAPI plugins use the x-ppapi-debug/release
39 mimetype
= 'application/x-ppapi-release';
41 mimetype
= 'application/x-ppapi-debug';
42 } else if (tool
== 'pnacl') {
43 mimetype
= 'application/x-pnacl';
49 * Check if the browser supports NaCl plugins.
51 * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
52 * @return {bool} True if the browser supports the type of NaCl plugin
53 * produced by the given toolchain.
55 function browserSupportsNaCl(tool
) {
56 // Assume host toolchains always work with the given browser.
57 // The below mime-type checking might not work with
58 // --register-pepper-plugins.
59 if (isHostToolchain(tool
)) {
62 var mimetype
= mimeTypeForTool(tool
);
63 return navigator
.mimeTypes
[mimetype
] !== undefined;
67 * Inject a script into the DOM, and call a callback when it is loaded.
69 * @param {string} url The url of the script to load.
70 * @param {Function} onload The callback to call when the script is loaded.
71 * @param {Function} onerror The callback to call if the script fails to load.
73 function injectScript(url
, onload
, onerror
) {
74 var scriptEl
= document
.createElement('script');
75 scriptEl
.type
= 'text/javascript';
77 scriptEl
.onload
= onload
;
79 scriptEl
.addEventListener('error', onerror
, false);
81 document
.head
.appendChild(scriptEl
);
85 * Run all tests for this example.
87 * @param {Object} moduleEl The module DOM element.
89 function runTests(moduleEl
) {
90 console
.log('runTests()');
91 common
.tester
= new Tester();
93 // All NaCl SDK examples are OK if the example exits cleanly; (i.e. the
94 // NaCl module returns 0 or calls exit(0)).
96 // Without this exception, the browser_tester thinks that the module
98 common
.tester
.exitCleanlyIsOK();
100 common
.tester
.addAsyncTest('loaded', function(test
) {
104 if (typeof window
.addTests
!== 'undefined') {
108 common
.tester
.waitFor(moduleEl
);
113 * Create the Native Client <embed> element as a child of the DOM element
116 * @param {string} name The name of the example.
117 * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
118 * @param {string} path Directory name where .nmf file can be found.
119 * @param {number} width The width to create the plugin.
120 * @param {number} height The height to create the plugin.
121 * @param {Object} attrs Dictionary of attributes to set on the module.
123 function createNaClModule(name
, tool
, path
, width
, height
, attrs
) {
124 var moduleEl
= document
.createElement('embed');
125 moduleEl
.setAttribute('name', 'nacl_module');
126 moduleEl
.setAttribute('id', 'nacl_module');
127 moduleEl
.setAttribute('width', width
);
128 moduleEl
.setAttribute('height', height
);
129 moduleEl
.setAttribute('path', path
);
130 moduleEl
.setAttribute('src', path
+ '/' + name
+ '.nmf');
132 // Add any optional arguments
134 for (var key
in attrs
) {
135 moduleEl
.setAttribute(key
, attrs
[key
]);
139 var mimetype
= mimeTypeForTool(tool
);
140 moduleEl
.setAttribute('type', mimetype
);
142 // The <EMBED> element is wrapped inside a <DIV>, which has both a 'load'
143 // and a 'message' event listener attached. This wrapping method is used
144 // instead of attaching the event listeners directly to the <EMBED> element
145 // to ensure that the listeners are active before the NaCl module 'load'
147 var listenerDiv
= document
.getElementById('listener');
148 listenerDiv
.appendChild(moduleEl
);
150 // Request the offsetTop property to force a relayout. As of Apr 10, 2014
151 // this is needed if the module is being loaded on a Chrome App's
152 // background page (see crbug.com/350445).
155 // Host plugins don't send a moduleDidLoad message. We'll fake it here.
156 var isHost
= isHostToolchain(tool
);
158 window
.setTimeout(function() {
159 moduleEl
.readyState
= 1;
160 moduleEl
.dispatchEvent(new CustomEvent('loadstart'));
161 moduleEl
.readyState
= 4;
162 moduleEl
.dispatchEvent(new CustomEvent('load'));
163 moduleEl
.dispatchEvent(new CustomEvent('loadend'));
167 // This is code that is only used to test the SDK.
169 var loadNaClTest = function() {
170 injectScript('nacltest.js', function() {
175 // Try to load test.js for the example. Whether or not it exists, load
177 injectScript('test.js', loadNaClTest
, loadNaClTest
);
182 * Add the default "load" and "message" event listeners to the element with
185 * The "load" event is sent when the module is successfully loaded. The
186 * "message" event is sent when the naclModule posts a message using
187 * PPB_Messaging.PostMessage() (in C) or pp::Instance().PostMessage() (in
190 function attachDefaultListeners() {
191 var listenerDiv
= document
.getElementById('listener');
192 listenerDiv
.addEventListener('load', moduleDidLoad
, true);
193 listenerDiv
.addEventListener('message', handleMessage
, true);
194 listenerDiv
.addEventListener('error', handleError
, true);
195 listenerDiv
.addEventListener('crash', handleCrash
, true);
196 if (typeof window
.attachListeners
!== 'undefined') {
197 window
.attachListeners();
202 * Called when the NaCl module fails to load.
204 * This event listener is registered in createNaClModule above.
206 function handleError(event
) {
207 // We can't use common.naclModule yet because the module has not been
209 var moduleEl
= document
.getElementById('nacl_module');
210 updateStatus('ERROR [' + moduleEl
.lastError
+ ']');
214 * Called when the Browser can not communicate with the Module
216 * This event listener is registered in attachDefaultListeners above.
218 function handleCrash(event
) {
219 if (common
.naclModule
.exitStatus
== -1) {
220 updateStatus('CRASHED');
222 updateStatus('EXITED [' + common
.naclModule
.exitStatus
+ ']');
224 if (typeof window
.handleCrash
!== 'undefined') {
225 window
.handleCrash(common
.naclModule
.lastError
);
230 * Called when the NaCl module is loaded.
232 * This event listener is registered in attachDefaultListeners above.
234 function moduleDidLoad() {
235 common
.naclModule
= document
.getElementById('nacl_module');
236 updateStatus('RUNNING');
238 if (typeof window
.moduleDidLoad
!== 'undefined') {
239 window
.moduleDidLoad();
244 * Hide the NaCl module's embed element.
246 * We don't want to hide by default; if we do, it is harder to determine that
247 * a plugin failed to load. Instead, call this function inside the example's
248 * "moduleDidLoad" function.
251 function hideModule() {
252 // Setting common.naclModule.style.display = "None" doesn't work; the
253 // module will no longer be able to receive postMessages.
254 common
.naclModule
.style
.height
= '0';
258 * Remove the NaCl module from the page.
260 function removeModule() {
261 common
.naclModule
.parentNode
.removeChild(common
.naclModule
);
262 common
.naclModule
= null;
266 * Return true when |s| starts with the string |prefix|.
268 * @param {string} s The string to search.
269 * @param {string} prefix The prefix to search for in |s|.
271 function startsWith(s
, prefix
) {
272 // indexOf would search the entire string, lastIndexOf(p, 0) only checks at
273 // the first index. See: http://stackoverflow.com/a/4579228
274 return s
.lastIndexOf(prefix
, 0) === 0;
277 /** Maximum length of logMessageArray. */
278 var kMaxLogMessageLength
= 20;
280 /** An array of messages to display in the element with id "log". */
281 var logMessageArray
= [];
284 * Add a message to an element with id "log".
286 * This function is used by the default "log:" message handler.
288 * @param {string} message The message to log.
290 function logMessage(message
) {
291 logMessageArray
.push(message
);
292 if (logMessageArray
.length
> kMaxLogMessageLength
)
293 logMessageArray
.shift();
295 document
.getElementById('log').textContent
= logMessageArray
.join('\n');
296 console
.log(message
);
301 var defaultMessageTypes
= {
307 * Called when the NaCl module sends a message to JavaScript (via
308 * PPB_Messaging.PostMessage())
310 * This event listener is registered in createNaClModule above.
312 * @param {Event} message_event A message event. message_event.data contains
313 * the data sent from the NaCl module.
315 function handleMessage(message_event
) {
316 if (typeof message_event
.data
=== 'string') {
317 for (var type
in defaultMessageTypes
) {
318 if (defaultMessageTypes
.hasOwnProperty(type
)) {
319 if (startsWith(message_event
.data
, type
+ ':')) {
320 func
= defaultMessageTypes
[type
];
321 func(message_event
.data
.slice(type
.length
+ 1));
328 if (typeof window
.handleMessage
!== 'undefined') {
329 window
.handleMessage(message_event
);
333 logMessage('Unhandled message: ' + message_event
.data
);
337 * Called when the DOM content has loaded; i.e. the page's document is fully
338 * parsed. At this point, we can safely query any elements in the document via
339 * document.querySelector, document.getElementById, etc.
341 * @param {string} name The name of the example.
342 * @param {string} tool The name of the toolchain, e.g. "glibc", "newlib" etc.
343 * @param {string} path Directory name where .nmf file can be found.
344 * @param {number} width The width to create the plugin.
345 * @param {number} height The height to create the plugin.
346 * @param {Object} attrs Optional dictionary of additional attributes.
348 function domContentLoaded(name
, tool
, path
, width
, height
, attrs
) {
349 // If the page loads before the Native Client module loads, then set the
350 // status message indicating that the module is still loading. Otherwise,
351 // do not change the status message.
352 updateStatus('Page loaded.');
353 if (!browserSupportsNaCl(tool
)) {
355 'Browser does not support NaCl (' + tool
+ '), or NaCl is disabled');
356 } else if (common
.naclModule
== null) {
357 updateStatus('Creating embed: ' + tool
);
359 // We use a non-zero sized embed to give Chrome space to place the bad
360 // plug-in graphic, if there is a problem.
361 width
= typeof width
!== 'undefined' ? width
: 200;
362 height
= typeof height
!== 'undefined' ? height
: 200;
363 attachDefaultListeners();
364 createNaClModule(name
, tool
, path
, width
, height
, attrs
);
366 // It's possible that the Native Client module onload event fired
367 // before the page's onload event. In this case, the status message
368 // will reflect 'SUCCESS', but won't be displayed. This call will
369 // display the current message.
370 updateStatus('Waiting.');
374 /** Saved text to display in the element with id 'statusField'. */
375 var statusText
= 'NO-STATUSES';
378 * Set the global status message. If the element with id 'statusField'
379 * exists, then set its HTML to the status message as well.
381 * @param {string} opt_message The message to set. If null or undefined, then
382 * set element 'statusField' to the message from the last call to
385 function updateStatus(opt_message
) {
387 statusText
= opt_message
;
389 var statusField
= document
.getElementById('statusField');
391 statusField
.innerHTML
= statusText
;
395 // The symbols to export.
397 /** A reference to the NaCl module, once it is loaded. */
400 attachDefaultListeners
: attachDefaultListeners
,
401 domContentLoaded
: domContentLoaded
,
402 createNaClModule
: createNaClModule
,
403 hideModule
: hideModule
,
404 removeModule
: removeModule
,
405 logMessage
: logMessage
,
406 updateStatus
: updateStatus
411 // Listen for the DOM content to be loaded. This event is fired when parsing of
412 // the page's document has finished.
413 document
.addEventListener('DOMContentLoaded', function() {
414 var body
= document
.body
;
416 // The data-* attributes on the body can be referenced via body.dataset.
419 if (!body
.dataset
.customLoad
) {
420 loadFunction
= common
.domContentLoaded
;
421 } else if (typeof window
.domContentLoaded
!== 'undefined') {
422 loadFunction
= window
.domContentLoaded
;
425 // From https://developer.mozilla.org/en-US/docs/DOM/window.location
427 if (window
.location
.search
.length
> 1) {
428 var pairs
= window
.location
.search
.substr(1).split('&');
429 for (var key_ix
= 0; key_ix
< pairs
.length
; key_ix
++) {
430 var keyValue
= pairs
[key_ix
].split('=');
431 searchVars
[unescape(keyValue
[0])] =
432 keyValue
.length
> 1 ? unescape(keyValue
[1]) : '';
437 var toolchains
= body
.dataset
.tools
.split(' ');
438 var configs
= body
.dataset
.configs
.split(' ');
441 if (body
.dataset
.attrs
) {
442 var attr_list
= body
.dataset
.attrs
.split(' ');
443 for (var key
in attr_list
) {
444 var attr
= attr_list
[key
].split('=');
451 var tc
= toolchains
.indexOf(searchVars
.tc
) !== -1 ?
452 searchVars
.tc
: toolchains
[0];
454 // If the config value is included in the search vars, use that.
455 // Otherwise default to Release if it is valid, or the first value if
456 // Release is not valid.
457 if (configs
.indexOf(searchVars
.config
) !== -1)
458 var config
= searchVars
.config
;
459 else if (configs
.indexOf('Release') !== -1)
460 var config
= 'Release';
462 var config
= configs
[0];
464 var pathFormat
= body
.dataset
.path
;
465 var path
= pathFormat
.replace('{tc}', tc
).replace('{config}', config
);
467 isTest
= searchVars
.test
=== 'true';
468 isRelease
= path
.toLowerCase().indexOf('release') != -1;
470 loadFunction(body
.dataset
.name
, tc
, path
, body
.dataset
.width
,
471 body
.dataset
.height
, attrs
);