【问题标题】:Is there a way to print a link to a javascript source file and line number in the devtools console with a console.print statement?有没有办法使用 console.print 语句在 devtools 控制台中打印指向 javascript 源文件和行号的链接?
【发布时间】:2016-06-27 02:48:09
【问题描述】:

我有一些在特定 javascript 文件中触发的 console.log 打印。该文件知道其他文件,并在 console.log 打印中引用这些文件名。我想知道是否有一种方法可以在同一个 console.log 打印输出中打印指向该源文件的某种链接,并希望单击该链接会在开发工具中打开该文件的源视图?

【问题讨论】:

    标签: javascript google-chrome-devtools


    【解决方案1】:

    通过尝试@miir 的解决方案发现你可以:

    1) 链接到文件,只要你输入完整路径

    console.log("http://localhost:8000/myapp/path/to/file.js")
    console.log(document.currentScript.src); // if executed from within a script
    

    2) 手动链接到文件+行+字符

    const line = "83";
    const character = "2";
    console.log(document.currentScript.src + ":" + line + ":" + character);
    

    3) 动态链接到文件+行+字符

    const level = 1; // 1 is last stack trace, you can go up the calling functions
    console.log(new Error().stack.split("\n")[level].match(/http[^\)]+/)[0]);
    

    没有什么不能从接受的答案中弄清楚,但也许它可以帮助新人。

    【讨论】:

      【解决方案2】:

      在给出这个答案的时候,没有直接的方法可以做到这一点。

      但是,@Emissary 在下面的评论中指出,访问文件链接的解决方法是利用 Error 对象的能力。

      console.log(new Error().stack)

      【讨论】:

      • 并非完全正确,您可以通过解析/打印来自 Error 对象的堆栈跟踪来解决它。 例如原始的,console.log(new Error().stack) - 或者通过查看更多的robust wrapper in this answer。
      • @Emissary 我明白了!谢谢!
      猜你喜欢
      • 2012-03-06
      • 2010-11-25
      • 1970-01-01
      • 2019-01-16
      • 1970-01-01
      • 2019-09-15
      • 2011-03-07
      • 2021-10-28
      • 2012-01-22
      相关资源
      最近更新 更多