【转】window.onerror跨域问题
2021-04-11 16:28
YPE html>
If you’ve done any work with the JavaScript onerror
event before, you’ve probably come across the following:
"Script error."
“Script error” is what browsers send to the onerror callback when an error originates from a JavaScript file served from a different origin (different domain, port, or protocol). It’s painful because even though there’s an error occurring, you don’t know what the error is, nor from which code it’s originating. And that’s the whole purpose of window.onerror
– getting insight into uncaught errors in your application.
The cause: cross-origin scripts
To better understand what’s going on, consider the following example HTML document, hypothetically served from http://example.com/test:
example.com/test
Here’s the contents of http://another-domain.com/app.js. It declares a single function, foo
, whose invocation will always throw a ReferenceError.
// another-domain.com/app.js
function foo() {
bar(); // ReferenceError: bar is not a function
}
When this document is loaded in the browser and JavaScript is executed, the following is output to the console (logged via the window.onerror
callback):
"Script error.", "", 0, 0, undefined
This isn’t a JavaScript bug – browsers intentionally hide errors originating from script files from different origins for security reasons. It’s to avoid a script unintentionally leaking potentially sensitive information to an onerror callback that it doesn’t control. For this reason, browsers only give window.onerror insight into errors originating from the same domain. All we know is that an error occurred – nothing else!
I’m not a bad person, really!
Despite browsers’ good intentions, there are some really good reasons why you want insight into errors thrown from scripts served from different origins:
- Your application JavaScript files are served from a different hostname, e.g. static.sentry.io/app.js.
- You are using libraries s
上一篇:C#中return的两个作用
文章标题:【转】window.onerror跨域问题
文章链接:http://soscw.com/index.php/essay/74346.html