首页 > 解决方案 > 无法从 Chrome 控制台看到变量,但可以在代码中访问

问题描述

为什么可以从方法内部访问变量,但不能从浏览器控制台访问?

我有以下打字稿代码,使用 angular6,ng serve在 Windows 10,当前 Chrome 上运行。

import * as d3 from "d3"; // from "npm i d3 --save" version 5.7
// picking a member of d3, nothing magical about "scaleLinear" here
console.log("see", d3.scaleLinear) // it prints ok, ƒ linear() {...

// angular component code fragment below

somefunction() {
    console.log("see again", d3.scaleLinear) // it prints ok, again
    // add a break here
}

我将代码驱动到某个功能。在休息时,当我尝试时在 Chrome 控制台中:

> console.log(d3.scaleLinear)

它抛出一个错误:

VM2012:1 Uncaught ReferenceError: d3 is not defined
    at eval (eval at push../src/app/user-sel/user-sel.component.ts.UserSelComponent._resyncYSel (user-sel.component.ts:58), <anonymous>:1:13)
    at UserSelComponent.push../src/app/user-sel/user-sel.component.ts.UserSelComponent._resyncYSel (user-sel.component.ts:58)
    at UserSelComponent.push../src/app/user-sel/user-sel.component.ts.UserSelComponent.selYSel (user-sel.component.ts:166)
    at Object.eval [as handleEvent] (UserSelComponent.html:75)
    at handleEvent (core.js:21673)
    at callWithDebugContext (core.js:22767)
    at Object.debugHandleEvent [as handleEvent] (core.js:22470)
    at dispatchEvent (core.js:19122)
    at core.js:19569
    at HTMLSpanElement.<anonymous> (platform-browser.js:993)

如何直接在控制台中访问 d3?我错过了什么?我查看了有关此主题的旧 SO 问题52332640,但找不到确凿的答案。

标签: javascripttypescriptgoogle-chrome-devtools

解决方案


如果您的页面有任何框架,则您的控制台可能在错误的上下文中运行。有一个下拉菜单可让您指定正确的上下文

例如,在此屏幕截图中,有两个IFrame元素。为了从“contentIframe2”中运行的脚本访问变量,我必须切换上下文

控制台上下文


推荐阅读