• Skip to main content
  • Select language
  • Skip to search
MDN Web Docs
  • Technologies
    • HTML
    • CSS
    • JavaScript
    • Graphics
    • HTTP
    • APIs / DOM
    • WebExtensions
    • MathML
  • References & Guides
    • Learn web development
    • Tutorials
    • References
    • Developer Guides
    • Accessibility
    • Game development
    • ...more docs
Add-ons
  1. MDN
  2. Mozilla
  3. Add-ons
  4. Browser extensions
  5. JavaScript APIs
  6. devtools.inspectedWindow
  7. devtools.inspectedWindow.eval()

devtools.inspectedWindow.eval()

In This Article
  1. Helpers
  2. Syntax
    1. Parameters
    2. Return value
  3. Browser compatibility
  4. Examples
    1. Helper examples

Executes JavaScript in the window that the devtools are attached to.

This is somewhat like using tabs.executeScript() to attach a content script, but with two main differences:

First, the JavaScript can use a set of special commands that browsers typically provide in their devtools console implementation: for example, using "$0" to refer to the element currently selected in the Inspector.

Second, the JavaScript you execute can see any changes made to the page by scripts that the page loaded. This is in contrast to content scripts, which see the page as it would exist if no page scripts were loaded. However, note that the isolation provided by content scripts is a deliberate security feature, intended to make it harder for malicious or simply uncooperative web pages to confuse or subvert WebExtensions APIs by redefining DOM functions and properties. This means you need to be very careful if you waive this protection by using eval(), and should use content scripts unless you need to use eval().

The script is evaluated by default in the main frame of the page. The script must evaluate to a value that can be represented as JSON (meaning that, for example, it may not evaluate to a function or an object that contains any functions). By default, the script does not see any content scripts attached to the page.

You can't call eval() on privileged browser windows such as "about:addons".

You can optionally provide an options parameter, which includes options to evaluate the script in a different frame or in the context of attached content scripts. Note that Firefox does not yet support the options parameter.

The eval() function returns a Promise that resolves to the evaluated result of the script or to an error.

Helpers

The script gets access to a number of objects that help the injected script interact with the developer tools. The following helpers are currently supported:

$0
Contains a reference to the element that's currently selected in the devtools Inspector.
inspect()
Given an element in the page, selects it in the devtools Inspector.

See some examples.

Syntax

var evaluating = browser.devtools.inspectedWindow.eval(
  expression,       // string
  options           // object
)

Parameters

expression
string. The JavaScript expression to evaluate. The string must evaluate to a object that can be represented as JSON, or an exception will be thrown. For example, expression must not evaluate to a function.
optionsOptional
object. Options for the function, as follows:
frameURLOptional
string. The URL of the frame in which to evaluate the expression. If this is omitted, the expression is evaluated in the main frame of the window.
useContentScriptContextOptional
boolean. If true, evaluate the expression in the context of any content scripts that this extension has attached to the page. If you set this option, then you must have actually attached some content scripts to the page, or a Devtools error will be thrown.
contextSecurityOrigin Optional
string. Evaluate the expression in the context of a content script attached by a different extension, whose origin matches the value given here. This overrides useContentScriptContext.

Return value

A Promise that will be fulfilled with an array containing two elements.

If no error occurred, element 0 will contain the result of evaluating the expression, and element 1 will be undefined.

If an error occurred, element 0 will be undefined, and element 1 will contain an object giving details about the error. Two different sorts of errors are distinguished:

  • errors encountered evaluating the JavaScript (for example, syntax errors in the expression). In this case, element 1 will contain:
    • a boolean property isException, set to true
    • a string property value, giving more details.
  • other errors (for example, an expression that evaluates to an object that can't be represented as JSON). In this case, element 1 will contain:
    • a boolean property isError, set to true
    • a string property code containing an error code.

Browser compatibility

ChromeEdgeFirefoxFirefox for AndroidOpera
Basic supportYesNo54NoYes
$0YesNo55NoYes
inspect()YesNo55NoYes
optionsYesNoNoNoYes

The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Examples

This tests whether jQuery is defined in the inspected window, and logs the result. Note that this wouldn't work in a content script, because even if jQuery were defined, the content script would not see it.

function handleError(error) {
  if (error.isError) {
    console.log(`Devtools error: ${error.code}`);
  } else {
    console.log(`JavaScript error: ${error.value}`);
  }
}
function handleResult(result) {
  console.log(result);
  if (result[0] !== undefined) {
    console.log(`jQuery: ${result[0]}`);
  } else if (result[1]) {
    handleError(result[1]);
  }
}
const checkjQuery = "typeof jQuery != 'undefined'";
evalButton.addEventListener("click", () => {
  browser.devtools.inspectedWindow.eval(checkjQuery)
    .then(handleResult);
});

Helper examples

This uses the $0 helper to set the background color of the element that's currently selected in the Inspector:

const evalButton = document.querySelector("#reddinate");
const evalString = "$0.style.backgroundColor = 'red'";
function handleError(error) {
  if (error.isError) {
    console.log(`Devtools error: ${error.code}`);
  } else {
    console.log(`JavaScript error: ${error.value}`);
  }
}
function handleResult(result) {
  if (result[1]) {
    handleError(result[1]);
  }
}
evalButton.addEventListener("click", () => {
  browser.devtools.inspectedWindow.eval(evalString)
    .then(handleResult);
});

This uses the inspect() helper to select the first <h1> element in the page:

const inspectButton = document.querySelector("#inspect");
const inspectString = "inspect(document.querySelector('h1'))";
function handleError(error) {
  if (error.isError) {
    console.log(`Devtools error: ${error.code}`);
  } else {
    console.log(`JavaScript error: ${error.value}`);
  }
}
function handleResult(result) {
  if (result[1]) {
    handleError(result[1]);
  }
}
inspectButton.addEventListener("click", () => {
  browser.devtools.inspectedWindow.eval(inspectString)
    .then(handleResult);
});

Acknowledgements

This API is based on Chromium's chrome.devtools API.

Microsoft Edge compatibility data is supplied by Microsoft Corporation and is included here under the Creative Commons Attribution 3.0 United States License.

// Copyright 2015 The Chromium Authors. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//    * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//    * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Document Tags and Contributors

Tags: 
  • Add-ons
  • API
  • devtools.inspectedWindow
  • eval
  • Extensions
  • Reference
  • WebExtensions
 Contributors to this page: wbamberg, andrewtruongmoz
 Last updated by: wbamberg, Jul 18, 2017, 3:45:32 PM
See also
  1. Browser extensions
  2. Getting started
    1. What are extensions?
    2. Your first extension
    3. Your second extension
    4. Anatomy of an extension
    5. Example extensions
  3. How to
    1. Intercept HTTP requests
    2. Modify a web page
    3. Add a button to the toolbar
    4. Implement a settings page
  4. User interface
    1. Introduction
    2. Toolbar button
    3. Address bar button
    4. Sidebar
    5. Context menu items
    6. Options page
    7. Bundled web pages
    8. Notifications
    9. Address bar suggestions
    10. Developer tools panels
  5. Concepts
    1. Using the JavaScript APIs
    2. Content scripts
    3. Match patterns
    4. Internationalization
    5. Content Security Policy
    6. Native messaging
  6. Porting
    1. Porting a Google Chrome extension
    2. Porting a legacy Firefox extension
    3. Embedded WebExtensions
    4. Comparison with the Add-on SDK
    5. Comparison with XUL/XPCOM extensions
    6. Chrome incompatibilities
    7. Differences between desktop and Android
  7. Firefox workflow
    1. Temporary Installation in Firefox
    2. Debugging
    3. Developing for Firefox for Android
    4. Getting started with web-ext
    5. web-ext command reference
    6. Extensions and the Add-on ID
    7. Publishing your extension
  8. JavaScript APIs
    1. Browser support for JavaScript APIs
    2. alarms
    3. bookmarks
    4. browserAction
    5. browsingData
    6. commands
    7. contextMenus
    8. contextualIdentities
    9. cookies
    10. devtools.inspectedWindow
      1. devtools.network
      2. devtools.panels
      3. downloads
      4. events
      5. extension
      6. extensionTypes
      7. history
      8. i18n
      9. identity
      10. idle
      11. management
      12. notifications
      13. omnibox
      14. pageAction
      15. permissions
      16. privacy
      17. proxy
      18. runtime
      19. sessions
      20. sidebarAction
      21. storage
      22. tabs
      23. topSites
      24. types
      25. webNavigation
      26. webRequest
      27. windows
    11. Manifest keys
      1. applications
      2. author
      3. background
      4. browser_action
      5. chrome_settings_overrides
      6. chrome_url_overrides
      7. commands
      8. content_scripts
      9. content_security_policy
      10. default_locale
      11. description
      12. developer
      13. devtools_page
      14. homepage_url
      15. icons
      16. incognito
      17. manifest_version
      18. name
      19. omnibox
      20. optional_permissions
      21. options_ui
      22. page_action
      23. permissions
      24. protocol_handlers
      25. short_name
      26. sidebar_action
      27. version
      28. web_accessible_resources
    12. Themes
    13. Publishing add-ons
    14. Guides
      1. Signing and distribution overview
      2. Submit an add-on
      3. Creating an appealing listing
      4. Review policies
      5. Developer agreement
      6. Featured add-ons
      7. Contact addons.mozilla.org
    15. Community and support
    16. Channels
      1. Add-ons blog
      2. Add-on forums
      3. Stack Overflow
      4. Development newsgroup
      5. IRC Channel
    17. Legacy add-ons
    18. Legacy technologies
      1. Add-on SDK
      2. Legacy Firefox for Android
      3. Bootstrapped extensions
      4. Overlay extensions