0

如果我有一个像下面这样的内联脚本,其中函数 foo 未定义,我希望能够执行以下操作:

<script fileName='foo.js'>
  foo();
</script>

并控制在错误控制台中显示什么文件名和/或控制在处理错误时将什么文件名传递给 window.onerror。例如,我想控制发送到的 url 参数

window.onerror = function (errMsg, url, line) {
    console.log(url); //would like this to output 'foo.js'
    console.log(event.filename);  //would like this to also output 'foo.js'
}

默认情况下,除非脚本链接到外部文件,否则只会列出父 html 文件,但如果能够在不同的脚本标签中使用内联代码说明错误源自哪个脚本标签,那就太好了。

有没有办法做到这一点?

4

1 回答 1

1

据我所知,javascript 并没有注意到它在其中运行的 HTML 标记。像这样的东西对你有用吗?

<script>
  try {
    foo();
    // the rest of the code...
  } catch (err) {
    console.log('Caught error in foo.js');
    console.error(err);
  }
</script>

If you're adding these scripts dynamically to the page you should be able to wrap them with this try/catch code and get the desired effect.

于 2012-09-14T15:40:51.763 回答