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 var GetAvailability = requireNative('v8_context').GetAvailability;
6 var GetGlobal = requireNative('sendRequest').GetGlobal;
8 // Utility for setting chrome.*.lastError.
10 // A utility here is useful for two reasons:
11 // 1. For backwards compatibility we need to set chrome.extension.lastError,
12 // but not all contexts actually have access to the extension namespace.
13 // 2. When calling across contexts, the global object that gets lastError set
14 // needs to be that of the caller. We force callers to explicitly specify
15 // the chrome object to try to prevent bugs here.
18 * Sets the last error for |name| on |targetChrome| to |message| with an
21 function set(name, message, stack, targetChrome) {
22 var errorMessage = name + ': ' + message;
23 if (stack != null && stack != '')
24 errorMessage += '\n' + stack;
27 throw new Error('No chrome object to set error: ' + errorMessage);
28 clear(targetChrome); // in case somebody has set a sneaky getter/setter
30 var errorObject = { message: message };
31 if (GetAvailability('extension.lastError').is_available)
32 targetChrome.extension.lastError = errorObject;
34 assertRuntimeIsAvailable();
35 targetChrome.runtime.lastError = errorObject;
39 * Clears the last error on |targetChrome|.
41 function clear(targetChrome) {
43 throw new Error('No target chrome to clear error');
45 if (GetAvailability('extension.lastError').is_available)
46 delete targetChrome.extension.lastError;
48 assertRuntimeIsAvailable();
49 delete targetChrome.runtime.lastError;
52 function assertRuntimeIsAvailable() {
53 // chrome.runtime should always be available, but maybe it's disappeared for
54 // some reason? Add debugging for http://crbug.com/258526.
55 var runtimeAvailability = GetAvailability('runtime.lastError');
56 if (!runtimeAvailability.is_available) {
57 throw new Error('runtime.lastError is not available: ' +
58 runtimeAvailability.message);
61 throw new Error('runtime namespace is null or undefined');
65 * Runs |callback(args)| with last error args as in set().
67 * The target chrome object is the global object's of the callback, so this
68 * method won't work if the real callback has been wrapped (etc).
70 function run(name, message, stack, callback, args) {
71 var targetChrome = GetGlobal(callback).chrome;
72 set(name, message, stack, targetChrome);
74 $Function.apply(callback, undefined, args);
80 exports.clear = clear;