Last updated on

前端报错与 crossorigin

问题背景

用户传来报问题但日志平台查询不到错误

定位和结论

前端的 JavaScript 代码会被上传到 CDN,假设为 xxx-cdn.com/hash.js 用户访问的是 xxx.com/path xxx-cdn-hash 和 xxx.com 不同源 xxx-cdn.com/hash.js 这里的报错能力受限

报错能力具体来说,日志平台收集报错的方式有通过下面的方式来处理未捕获的全局错误

window.onerror = function (message, source, line, column, error) {
  // Handle the error here
  console.log("from handle-error |Error:", {
    message,
    source,
    line,
    column,
    error,
  })
}

而 跨域的 script 中抛出的 error,详细信息会被干掉「普通 throw 的 error」或者拿不到「Promise 的情况」

增加 crossorigin 可以解决这个问题

<script src="http://localhost:4000/index.js" crossorigin></script>

相关出处

  1. MDN

https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/crossorigin

By default (that is, when the attribute is not specified), CORS is not used at all. The user agent will not ask for permission for full access to the resource and in the case of a cross-origin request, certain limitations will be applied based on the type of element concerned:

script: Access to error logging via window.onerror will be limited.

这里直接说了 onerror 的错误收集会受限制

  1. whatwg

https://html.spec.whatwg.org/multipage/scripting.html#attr-script-type

The crossorigin attribute is a CORS settings attribute. For classic scripts, it controls whether error information will be exposed, when the script is obtained from other origins. For module scripts, it controls the credentials mode used for cross-origin requests.

对于 classic scripts,crossorigin 控制了错误信息是否会被暴露

那什么是 classic scripts 呢?

The type attribute allows customization of the type of script represented: Omitting the attribute, setting it to the empty string, or setting it to a JavaScript MIME type essence match, means that the script is a classic script, to be interpreted according to the JavaScript Script top-level production. Classic scripts are affected by the async and defer attributes, but only when the src attribute is set. Authors should omit the type attribute instead of redundantly setting it.

把 type 属性置为 空或者 为下列 则为 classic scripts

A JavaScript MIME type is any MIME type whose essence is one of the following:

  • application/ecmascript
  • application/javascript
  • application/x-ecmascript
  • application/x-javascript
  • text/ecmascript
  • text/javascript
  • text/javascript1.0
  • text/javascript1.1
  • text/javascript1.2
  • text/javascript1.3
  • text/javascript1.4
  • text/javascript1.5
  • text/jscript
  • text/livescript
  • text/x-ecmascript
  • text/x-javascript

最佳实践

上 CDN 的 script 都加一下 crossorigin

其他与参考

debug 实践的仓库可以看 这个