Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / extensions / renderer / resources / messaging_utils.js
blobd1b563de33d868cff17d6f15d0b8ef73f1517326
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.
5 // Routines used to normalize arguments to messaging functions.
7 function alignSendMessageArguments(args, hasOptionsArgument) {
8 // Align missing (optional) function arguments with the arguments that
9 // schema validation is expecting, e.g.
10 // extension.sendRequest(req) -> extension.sendRequest(null, req)
11 // extension.sendRequest(req, cb) -> extension.sendRequest(null, req, cb)
12 if (!args || !args.length)
13 return null;
14 var lastArg = args.length - 1;
16 // responseCallback (last argument) is optional.
17 var responseCallback = null;
18 if (typeof args[lastArg] == 'function')
19 responseCallback = args[lastArg--];
21 var options = null;
22 if (hasOptionsArgument && lastArg >= 1) {
23 // options (third argument) is optional. It can also be ambiguous which
24 // argument it should match. If there are more than two arguments remaining,
25 // options is definitely present:
26 if (lastArg > 1) {
27 options = args[lastArg--];
28 } else {
29 // Exactly two arguments remaining. If the first argument is a string,
30 // it should bind to targetId, and the second argument should bind to
31 // request, which is required. In other words, when two arguments remain,
32 // only bind options when the first argument cannot bind to targetId.
33 if (!(args[0] === null || typeof args[0] == 'string'))
34 options = args[lastArg--];
38 // request (second argument) is required.
39 var request = args[lastArg--];
41 // targetId (first argument, extensionId in the manifest) is optional.
42 var targetId = null;
43 if (lastArg >= 0)
44 targetId = args[lastArg--];
46 if (lastArg != -1)
47 return null;
48 if (hasOptionsArgument)
49 return [targetId, request, options, responseCallback];
50 return [targetId, request, responseCallback];
53 exports.alignSendMessageArguments = alignSendMessageArguments;