"Script Error." 错误 window.onerror 仅在 Safari 中

"Script Error." errors in window.onerror in Safari only

我在 window.onerror 中捕获错误时得到 "Script Error.",即使在 S3 上正确(我认为)配置了 CORS headers。

CORS 配置:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>HEAD</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

HTML:

<script crossorigin src="https://s3.amazonaws.com/safari-script-error/foo.js" />

其中包含:

window.addEventListener("keydown", function(event) {
  if (event.keyCode === 69) { // "e" button
    throw new Error("Oh shoot");
  }
});

JS:

window.onerror = function(event) {
  console.log(event);
}

代码笔:https://codepen.io/astashov/pen/yoEvRB

它在 Chrome、Firefox 和 IE11 中工作正常,仅在 Safari 中显示 "Script error."(我有版本 10.0.3 (12602.4.8))。

如何让它在 Safari 中也能正常工作?

问题似乎不是 CORS。似乎并非每个浏览器都支持全局 onerror 处理程序。

参见: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror

其实应该是和CORS有关。

When a syntax(?) error occurs in a script, loaded from a different origin, the details of the syntax error are not reported to prevent leaking information (see bug 363897). Instead the error reported is simply "Script error." This behavior can be overriden in some browsers using the crossorigin attribute on and having the server send the appropriate CORS HTTP response headers. A workaround is to isolate "Script error." and handle it knowing that the error detail is only viewable in the browser console and not accessible via JavaScript.

How to make it work in Safari too?

你不能。当前的 Safari 版本不支持在跨源情况下向 onerror 回调提供错误消息——即使在 script 元素上指定了 crossorigin 属性。

Safari 之前确实支持它,但后来在某些时候倒退了。

https://bugs.webkit.org/show_bug.cgi?id=132945

处有一个未解决的错误