devtools.inspectedWindow.eval()

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 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 选项 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 选项 参数。

eval() 函数返回 Promise that resolves to the evaluated result of the script or to an error.

帮手

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 object, if it is an DOM element in the page, selects it in the devtools Inspector, otherwise it creates an object preview in the webconsole.

See some examples.

句法

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

					

参数

表达式

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, 表达式 must not evaluate to a function.

选项 可选

对象 . Options for the function (Note that Firefox does not yet support this options), as follows:

frameURL 可选

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.

useContentScriptContext 可选

boolean 。若 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 可选

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 .

返回值

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.

浏览器兼容性

BCD tables only load in the browser

范例

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);
});

						

注意: 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.

Found a problem with this page?

最后修改: , 由 MDN 贡献者

  1. 浏览器扩展名
  2. 快速入门
    1. What are extensions?
    2. Your first extension
    3. Your second extension
    4. Anatomy of an extension
    5. Example extensions
    6. What next?
  3. 概念
    1. Using the JavaScript APIs
    2. Content scripts
    3. Match patterns
    4. Working with files
    5. 国际化
    6. Content Security Policy
    7. Native messaging
    8. Differences between API implementations
    9. Chrome incompatibilities
  4. 用户界面
    1. 用户界面
    2. Toolbar button
    3. Address bar button
    4. Sidebars
    5. Context menu items
    6. Options page
    7. Extension pages
    8. Notifications
    9. Address bar suggestions
    10. Developer tools panels
  5. 如何
    1. Intercept HTTP requests
    2. Modify a web page
    3. Insert external content
    4. Share objects with page scripts
    5. Add a button to the toolbar
    6. Implement a settings page
    7. Work with the Tabs API
    8. Work with the Bookmarks API
    9. Work with the Cookies API
    10. Work with contextual identities
    11. Interact with the clipboard
    12. Build a cross-browser extension
  6. Firefox differentiators
  7. JavaScript API
    1. Browser support for JavaScript APIs
    2. alarms
    3. bookmarks
    4. browserAction
    5. browserSettings
    6. browsingData
    7. captivePortal
    8. clipboard
    9. 命令
    10. contentScripts
    11. contextualIdentities
    12. Cookie
    13. devtools
      1. dns
      2. downloads
      3. events
      4. extension
      5. extensionTypes
      6. find
      7. history
      8. i18n
      9. identity
      10. idle
      11. management
      12. menus
      13. notifications
      14. omnibox
      15. pageAction
      16. permissions
      17. pkcs11
      18. privacy
      19. proxy
      20. runtime
      21. search
      22. sessions
      23. sidebarAction
      24. storage
      25. tabs
      26. theme
      27. topSites
      28. 类型
      29. userScripts
      30. webNavigation
      31. webRequest
      32. windows
    14. Manifest keys
      1. 介绍
      1. 作者
      2. background
      3. browser_action
      4. browser_specific_settings
      5. chrome_settings_overrides
      6. chrome_url_overrides
      7. 命令
      8. content_scripts
      9. content_security_policy
      10. default_locale
      11. description
      12. developer
      13. devtools_page
      14. dictionaries
      15. externally_connectable
      16. homepage_url
      17. icons
      18. incognito
      19. manifest_version
      20. name
      21. offline_enabled
      22. omnibox
      23. optional_permissions
      24. options_page
      25. options_ui
      26. page_action
      27. permissions
      28. protocol_handlers
      29. short_name
      30. sidebar_action
      31. storage
      32. theme
      33. theme_experiment
      34. user_scripts
      35. version
      36. version_name
      37. web_accessible_resources
    15. Extension Workshop
      1. Develop
      2. Publish
      3. Manage
      4. Enterprise
    16. Contact us
    17. Channels
      1. Add-ons blog
      2. Add-ons forum
      3. Add-ons chat