Bug 1291737 - [webext] Implement devtools.inspectedWindow.tabId. draft
authorLuca Greco <lgreco@mozilla.com>
Fri, 09 Sep 2016 18:11:05 +0200
changeset 416971 28f0150156a4d01f5e4054acb51ff54b34ee34ab
parent 416970 e5fb07a289f433dc054caceb1b4cad80a230708f
child 416972 d75445ed26b5269bb23c6600e6d930036fe25218
child 417022 7ad3c5b3f7b286dd94d90a35124190fbac4482fd
push id30296
push userluca.greco@alcacoop.it
push dateFri, 23 Sep 2016 10:19:08 +0000
bugs1291737
milestone52.0a1
Bug 1291737 - [webext] Implement devtools.inspectedWindow.tabId. This patch import the devtools.inspectedWindow API JSON schema file, and implements the devtools.inspectedWindow.tabId getter. MozReview-Commit-ID: DXTI7UQY9TX
browser/components/extensions/ext-devtools-inspectedWindow.js
browser/components/extensions/extensions-browser.manifest
browser/components/extensions/jar.mn
browser/components/extensions/schemas/devtools_inspected_window.json
browser/components/extensions/schemas/jar.mn
browser/components/extensions/test/browser/browser_ext_devtools_page.js
new file mode 100644
--- /dev/null
+++ b/browser/components/extensions/ext-devtools-inspectedWindow.js
@@ -0,0 +1,32 @@
+/* -*- Mode: indent-tabs-mode: nil; js-indent-level: 2 -*- */
+/* vim: set sts=2 sw=2 et tw=80: */
+"use strict";
+
+/* global getDeveloperToolboxForContext */
+
+/**
+ * This module provides the implementation of the devtools.inspectedWindow namespace.
+ */
+
+extensions.registerSchemaAPI("devtools.inspectedWindow", "devtools_parent", (context) => {
+  return {
+    devtools: {
+      inspectedWindow: {
+        get tabId() {
+          const toolbox = getDeveloperToolboxForContext(context);
+          if (toolbox && toolbox.target.isLocalTab) {
+            let {target} = toolbox;
+            let browser = target.tab.linkedBrowser;
+            let parentWindow = browser.ownerDocument.defaultView;
+            let tab = parentWindow.gBrowser.getTabForBrowser(browser);
+
+            return TabManager.getId(tab);
+          }
+
+          throw new Error("unable to retrieve a tabId for the current inspectedWindow");
+        },
+        // TODO: implement `eval` and `reload` as part of the initial API subset
+      },
+    },
+  };
+});
--- a/browser/components/extensions/extensions-browser.manifest
+++ b/browser/components/extensions/extensions-browser.manifest
@@ -1,27 +1,29 @@
 # scripts
 category webextension-scripts bookmarks chrome://browser/content/ext-bookmarks.js
 category webextension-scripts browserAction chrome://browser/content/ext-browserAction.js
 category webextension-scripts commands chrome://browser/content/ext-commands.js
 category webextension-scripts contextMenus chrome://browser/content/ext-contextMenus.js
 category webextension-scripts desktop-runtime chrome://browser/content/ext-desktop-runtime.js
 category webextension-scripts devtools chrome://browser/content/ext-devtools.js
+category webextension-scripts devtools-inspectedWindow chrome://browser/content/ext-devtools-inspectedWindow.js
 category webextension-scripts history chrome://browser/content/ext-history.js
 category webextension-scripts pageAction chrome://browser/content/ext-pageAction.js
 category webextension-scripts tabs chrome://browser/content/ext-tabs.js
 category webextension-scripts utils chrome://browser/content/ext-utils.js
 category webextension-scripts windows chrome://browser/content/ext-windows.js
 
 # scripts that must run in the same process as addon code.
 category webextension-scripts-addon tabs chrome://browser/content/ext-c-tabs.js
 
 # schemas
 category webextension-schemas bookmarks chrome://browser/content/schemas/bookmarks.json
 category webextension-schemas browser_action chrome://browser/content/schemas/browser_action.json
 category webextension-schemas commands chrome://browser/content/schemas/commands.json
 category webextension-schemas context_menus chrome://browser/content/schemas/context_menus.json
 category webextension-schemas context_menus_internal chrome://browser/content/schemas/context_menus_internal.json
 category webextension-schemas devtools chrome://browser/content/schemas/devtools.json
+category webextension-schemas devtools_inspected_window chrome://browser/content/schemas/devtools_inspected_window.json
 category webextension-schemas history chrome://browser/content/schemas/history.json
 category webextension-schemas page_action chrome://browser/content/schemas/page_action.json
 category webextension-schemas tabs chrome://browser/content/schemas/tabs.json
 category webextension-schemas windows chrome://browser/content/schemas/windows.json
--- a/browser/components/extensions/jar.mn
+++ b/browser/components/extensions/jar.mn
@@ -13,14 +13,15 @@ browser.jar:
 #endif
     content/browser/extension.svg
     content/browser/ext-bookmarks.js
     content/browser/ext-browserAction.js
     content/browser/ext-commands.js
     content/browser/ext-contextMenus.js
     content/browser/ext-desktop-runtime.js
     content/browser/ext-devtools.js
+    content/browser/ext-devtools-inspectedWindow.js
     content/browser/ext-history.js
     content/browser/ext-pageAction.js
     content/browser/ext-tabs.js
     content/browser/ext-utils.js
     content/browser/ext-windows.js
     content/browser/ext-c-tabs.js
new file mode 100644
--- /dev/null
+++ b/browser/components/extensions/schemas/devtools_inspected_window.json
@@ -0,0 +1,267 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+  {
+    "namespace": "devtools.inspectedWindow",
+    "allowedContexts": ["devtools", "devtools_only"],
+    "defaultContexts": ["devtools", "devtools_only"],
+    "description": "Use the <code>chrome.devtools.inspectedWindow</code> API to interact with the inspected window: obtain the tab ID for the inspected page, evaluate the code in the context of the inspected window, reload the page, or obtain the list of resources within the page.",
+    "nocompile": true,
+    "types": [
+      {
+        "id": "Resource",
+        "type": "object",
+        "description": "A resource within the inspected page, such as a document, a script, or an image.",
+        "properties": {
+          "url": {
+            "type": "string",
+            "description": "The URL of the resource."
+          }
+        },
+        "functions": [
+          {
+            "name": "getContent",
+            "unsupported": true,
+            "type": "function",
+            "description": "Gets the content of the resource.",
+            "parameters": [
+              {
+                "name": "callback",
+                "type": "function",
+                "description": "A function that receives resource content when the request completes.",
+                "parameters": [
+                  {
+                    "name": "content",
+                    "type": "string",
+                    "description": "Content of the resource (potentially encoded)."
+                  },
+                  {
+                    "name": "encoding",
+                    "type": "string",
+                    "description": "Empty if content is not encoded, encoding name otherwise. Currently, only base64 is supported."
+                  }
+                ]
+              }
+            ]
+          },
+          {
+            "name": "setContent",
+            "unsupported": true,
+            "type": "function",
+            "description": "Sets the content of the resource.",
+            "parameters": [
+              {
+                "name": "content",
+                "type": "string",
+                "description": "New content of the resource. Only resources with the text type are currently supported."
+              },
+              {
+                "name": "commit",
+                "type": "boolean",
+                "description": "True if the user has finished editing the resource, and the new content of the resource should be persisted; false if this is a minor change sent in progress of the user editing the resource."
+              },
+              {
+                "name": "callback",
+                "type": "function",
+                "description": "A function called upon request completion.",
+                "optional": true,
+                "parameters": [
+                  {
+                    "name": "error",
+                    "type": "object",
+                    "additionalProperties": {"type": "any"},
+                    "optional": true,
+                    "description": "Set to undefined if the resource content was set successfully; describes error otherwise."
+                  }
+                ]
+              }
+            ]
+          }
+        ]
+      }
+    ],
+    "properties": {
+      "tabId": {
+        "description": "The ID of the tab being inspected. This ID may be used with chrome.tabs.* API.",
+        "type": "integer"
+      }
+    },
+    "functions": [
+      {
+        "name": "eval",
+        "unsupported": true,
+        "type": "function",
+        "description": "Evaluates a JavaScript expression in the context of the main frame of the inspected page. The expression must evaluate to a JSON-compliant object, otherwise an exception is thrown. The eval function can report either a DevTools-side error or a JavaScript exception that occurs during evaluation. In either case, the <code>result</code> parameter of the callback is <code>undefined</code>. In the case of a DevTools-side error, the <code>isException</code> parameter is non-null and has <code>isError</code> set to true and <code>code</code> set to an error code. In the case of a JavaScript error, <code>isException</code> is set to true and <code>value</code> is set to the string value of thrown object.",
+        "async": "callback",
+        "parameters": [
+          {
+            "name": "expression",
+            "type": "string",
+            "description": "An expression to evaluate."
+          },
+          {
+            "name": "options",
+            "type": "object",
+            "optional": true,
+            "description": "The options parameter can contain one or more options.",
+            "properties": {
+              "frameURL": {
+                "type": "string",
+                "optional": true,
+                "description": "If specified, the expression is evaluated on the iframe whose URL matches the one specified. By default, the expression is evaluated in the top frame of the inspected page."
+              },
+              "useContentScriptContext": {
+                "type": "boolean",
+                "optional": true,
+                "description": "Evaluate the expression in the context of the content script of the calling extension, provided that the content script is already injected into the inspected page. If not, the expression is not evaluated and the callback is invoked with the exception parameter set to an object that has the <code>isError</code> field set to true and the <code>code</code> field set to <code>E_NOTFOUND</code>."
+              },
+              "contextSecurityOrigin": {
+                "type": "string",
+                "optional": true,
+                "description": "Evaluate the expression in the context of a content script of an extension that matches the specified origin. If given, contextSecurityOrigin overrides the 'true' setting on userContentScriptContext."
+              }
+            }
+          },
+          {
+            "name": "callback",
+            "type": "function",
+            "description": "A function called when evaluation completes.",
+            "optional": true,
+            "parameters": [
+              {
+                "name": "result",
+                "type": "object",
+                "additionalProperties": {"type": "any"},
+                "description": "The result of evaluation."
+              },
+              {
+                "name": "exceptionInfo",
+                "type": "object",
+                "description": "An object providing details if an exception occurred while evaluating the expression.",
+                "properties": {
+                  "isError": {
+                    "type": "boolean",
+                    "description": "Set if the error occurred on the DevTools side before the expression is evaluated."
+                  },
+                  "code": {
+                    "type": "string",
+                    "description": "Set if the error occurred on the DevTools side before the expression is evaluated."
+                  },
+                  "description": {
+                    "type": "string",
+                    "description": "Set if the error occurred on the DevTools side before the expression is evaluated."
+                  },
+                  "details": {
+                    "type": "array",
+                    "items": { "type": "any" },
+                    "description": "Set if the error occurred on the DevTools side before the expression is evaluated, contains the array of the values that may be substituted into the description string to provide more information about the cause of the error."
+                  },
+                  "isException": {
+                    "type": "boolean",
+                    "description": "Set if the evaluated code produces an unhandled exception."
+                  },
+                  "value": {
+                    "type": "string",
+                    "description": "Set if the evaluated code produces an unhandled exception."
+                  }
+                }
+              }
+            ]
+          }
+        ]
+      },
+      {
+        "name": "reload",
+        "unsupported": true,
+        "type": "function",
+        "description": "Reloads the inspected page.",
+        "parameters": [
+          {
+            "type": "object",
+            "name": "reloadOptions",
+            "optional": true,
+            "properties": {
+              "ignoreCache": {
+                "type": "boolean",
+                "optional": true,
+                "description": "When true, the loader will bypass the cache for all inspected page resources loaded before the <code>load</code> event is fired. The effect is similar to pressing Ctrl+Shift+R in the inspected window or within the Developer Tools window."
+              },
+              "userAgent": {
+                "type": "string",
+                "optional": true,
+                "description": "If specified, the string will override the value of the <code>User-Agent</code> HTTP header that's sent while loading the resources of the inspected page. The string will also override the value of the <code>navigator.userAgent</code> property that's returned to any scripts that are running within the inspected page."
+              },
+              "injectedScript": {
+                "type": "string",
+                "optional": true,
+                "description": "If specified, the script will be injected into every frame of the inspected page immediately upon load, before any of the frame's scripts. The script will not be injected after subsequent reloads&mdash;for example, if the user presses Ctrl+R."
+              },
+              "preprocessorScript": {
+                "type": "string",
+                "deprecated": "Please avoid using this parameter, it will be removed soon.",
+                "optional": true,
+                "description": "If specified, this script evaluates into a function that accepts three string arguments: the source to preprocess, the URL of the source, and a function name if the source is an DOM event handler. The preprocessorerScript function should return a string to be compiled by Chrome in place of the input source. In the case that the source is a DOM event handler, the returned source must compile to a single JS function."
+              }
+            }
+          }
+        ]
+      },
+      {
+        "name": "getResources",
+        "unsupported": true,
+        "type": "function",
+        "description": "Retrieves the list of resources from the inspected page.",
+        "unsupported": true,
+        "async": "callback",
+        "parameters": [
+          {
+            "name": "callback",
+            "type": "function",
+            "description": "A function that receives the list of resources when the request completes.",
+            "parameters": [
+              {
+                "name": "resources",
+                "type": "array",
+                "items": { "$ref": "Resource" },
+                "description": "The resources within the page."
+              }
+            ]
+          }
+        ]
+      }
+    ],
+    "events": [
+      {
+        "name": "onResourceAdded",
+        "unsupported": true,
+        "type": "function",
+        "description": "Fired when a new resource is added to the inspected page.",
+        "parameters": [
+          {
+            "name": "resource",
+            "$ref": "Resource"
+          }
+        ]
+      },
+      {
+        "name": "onResourceContentCommitted",
+        "unsupported": true,
+        "type": "function",
+        "description": "Fired when a new revision of the resource is committed (e.g. user saves an edited version of the resource in the Developer Tools).",
+        "parameters": [
+          {
+            "name": "resource",
+            "$ref": "Resource"
+          },
+          {
+            "name": "content",
+            "type": "string",
+            "description": "New content of the resource."
+          }
+        ]
+      }
+    ]
+  }
+]
--- a/browser/components/extensions/schemas/jar.mn
+++ b/browser/components/extensions/schemas/jar.mn
@@ -4,12 +4,13 @@
 
 browser.jar:
     content/browser/schemas/bookmarks.json
     content/browser/schemas/browser_action.json
     content/browser/schemas/commands.json
     content/browser/schemas/context_menus.json
     content/browser/schemas/context_menus_internal.json
     content/browser/schemas/devtools.json
+    content/browser/schemas/devtools_inspected_window.json
     content/browser/schemas/history.json
     content/browser/schemas/page_action.json
     content/browser/schemas/tabs.json
     content/browser/schemas/windows.json
--- a/browser/components/extensions/test/browser/browser_ext_devtools_page.js
+++ b/browser/components/extensions/test/browser/browser_ext_devtools_page.js
@@ -8,32 +8,50 @@ XPCOMUtils.defineLazyModuleGetter(this, 
                                   "resource://devtools/shared/Loader.jsm");
 
 /**
  * This test file ensures that:
  *
  * - the devtools_page property creates a new WebExtensions context
  * - the devtools API object is not available in a background page
  * - the devtools page doesn't have access to all the APIs
+ * - the devtools page context has access to the devtools API object
+ * - the devtools.inspectedWindow.tabId value is the same value that we
+ *   can retrieve from another WebExtensions context using the tab API
  */
 
 add_task(function* test_devtools_page_api_namespaces() {
   let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser, "http://mochi.test:8888/");
 
   function background_page() {
     browser.test.sendMessage("is-devtools-in-backgroundpage", !!browser.devtools);
+
+    browser.tabs.query({active: true}).then(tabs => {
+      browser.test.sendMessage("current-tab-id", tabs[0].id);
+    });
   }
 
   function devtools_page() {
     // Test that the available APIs are correctly restricted in devtools pages.
     browser.test.assertEq(undefined, browser.runtime.getBackgroundPage,
       "The `runtime.getBackgroundPage` API method should be missing in a devtools_page context"
     );
 
-    browser.test.notifyPass("devtools_page.done");
+    if (browser.devtools) {
+      // If the devtools API object is defined, get the inspectedWindow tabId
+      // to check that it is the same of the tabId that we retrieve from the
+      // background page
+      let tabId = browser.devtools.inspectedWindow.tabId;
+      browser.test.sendMessage("inspectedWindow-tab-id", tabId);
+
+      browser.test.notifyPass("devtools_page.done");
+    } else {
+      // Just fail if the devtools API object is not defined
+      browser.test.notifyFail("devtools_page.done");
+    }
   }
 
   let extension = ExtensionTestUtils.loadExtension({
     background: background_page,
     manifest: {
       devtools_page: "devtools_page.html",
     },
     files: {
@@ -52,21 +70,27 @@ add_task(function* test_devtools_page_ap
 
   yield extension.startup();
 
   let isDevtoolsInBackground = yield extension.awaitMessage("is-devtools-in-backgroundpage");
 
   is(isDevtoolsInBackground, false,
      "The devtools API object should not be available in a background page");
 
+  let backgroundPageCurrentTabId = yield extension.awaitMessage("current-tab-id");
+
   let target = devtools.TargetFactory.forTab(tab);
 
   yield gDevTools.showToolbox(target, "webconsole");
   info("developer toolbox opened");
 
+  let devtoolsInspectedWindowTabId = yield extension.awaitMessage("inspectedWindow-tab-id");
+
+  is(devtoolsInspectedWindowTabId, backgroundPageCurrentTabId,
+     "Got the expected tabId from devtool.inspectedWindow.tabId");
 
   yield extension.awaitFinish("devtools_page.done");
 
   yield gDevTools.closeToolbox(target);
 
   yield extension.unload();
 
   yield BrowserTestUtils.removeTab(tab);