【转】window.onerror跨域问题
What the heck is "Script error"?
Ben Vinegar/ May 17, 2016

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:
<!doctype html>
<html>
<head>
<title>example.com/test</title>
</head>
<body>
<script src="http://another-domain.com/app.js"></script>
<script>
window.onerror = function (message, url, line, column, error) {
console.log(message, url, line, column, error);
}
foo(); // call function declared in app.js
</script>
</body>
</html>
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 served from a community CDN, like cdnjs or Google’s Hosted Libraries.
- You’re working with a commercial 3rd-party JavaScript library, that is only served from external servers.
But don’t worry – getting insight into a JavaScript error served by these files just needs a few simple tweaks.
The fix: CORS attributes and headers
In order to get visibility into a JavaScript exception thrown from scripts originating from different origins, you must do two things.
1) Add a crossorigin=”anonymous” script attribute
<script src="http://another-domain.com/app.js" crossorigin="anonymous"></script>
This tells the browser that the the target file should be fetched “anonymously”. This means that no potentially user-identifying information like cookies or HTTP credentials will be transmitted by the browser to the server when requesting this file.
2) Add a Cross Origin HTTP header
Access-Control-Allow-Origin: *
CORS is short for “Cross Origin Resource Sharing”, and it’s a set of APIs (mostly HTTP headers) that dictate how files ought to be downloaded and served across origins.
By setting Access-Control-Allow-Origin: *
, the server is indicating to browsers that any origin can fetch this file. Alternatively, you can restrict it to only a known origin you control, e.g.
Access-Control-Allow-Origin: https://www.example.com
Note: most community CDNs properly set an Access-Control-Allow-Origin header.
$ curl --head https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.js | \
grep -i "access-control-allow-origin"
Access-Control-Allow-Origin: *
Once both of these steps have been made, any errors triggered by this script will report to window.onerror
just like any regular same-domain script. So instead of “Script error”, the onerror example from the beginning will yield:
"ReferenceError: bar is not defined", "http://another-domain.com/app.js", 2, 1, [Object Error]
Boom! You’re done – ”Script error” will plague you and your team no more.
An alternative solution: try/catch
Sometimes, we’re not always in a position to be able to adjust the HTTP headers of scripts our web application is consuming. In those situations, there is an alternative approach: using try/catch.
Consider the original example again, this time with try/catch:
<!-- note: crossorigin="anonymous" intentionally absent -->
<script src="http://another-domain.com/app.js"></script>
<script>
window.onerror = function (message, url, line, column, error) {
console.log(message, url, line, column, error);
}
try {
foo(); // call function declared in app.js
} catch (e) {
console.log(e);
throw e; // intentionally re-throw (caught by window.onerror)
}
</script>
For posterity, some-domain.com/app.js once again looks like this:
// another-domain.com/app.js
function foo() {
bar(); // ReferenceError: bar is not a function
}
Running the example HTML will output the following 2 entries to the console:
=> ReferenceError: bar is not defined
at foo (http://another-domain.com/b.js:2:3)
at http://example.com/test/:15:3
=> "Script error.", "", 0, 0, undefined
The first console statement – from try/catch – managed to get an error object complete with type, message, and stack trace, including file names and line numbers. The second console statement from window.onerror
, once again, can only output “Script error.”
Now, does this mean you need to try/catch all of your code? Probably not – if you can easily change your HTML and specify CORS headers on your CDNs, it is preferable to do so and stick to window.onerror
.
But, if you don’t control those resources, using try/catch to wrap 3rd-party code is a surefire (albeit tedious) way to get insight into errors thrown by cross-origin scripts.
Note: by default, Raven.js – Sentry’s JavaScript SDK – carefully instruments built-in methods to try to automatically wrap your code in try/catch blocks. It does this to attempt to capture error messages and stack traces from all your scripts, regardless of which origin they’re served from. It’s still recommended to set CORS attributes and headers if possible.
If this blog post helped you out, and you’d like to learn more about window.onerror
, you should also check out our other blog post: Capture and report JavaScript errors with window.onerror.
【转】window.onerror跨域问题的更多相关文章
- window.name 跨域
跨域的由来 JavaScript出于安全方面的考虑,不允许跨域调用其他页面的对象.但是我们常常会遇到无法避免跨域的情况,如普通文章站点(article.xxx.com)需要评论,而评论站点却在chea ...
- JS window.name跨域封装
JS window.name 跨域封装 function CrossDomainName(target, agent, callback, security) { if (typeof target ...
- window.name跨域
window.name? 每一个页面都有一个自己的window,而window.name是window的名字. window.name跨域原理 window对象有个name属性,该属性有个特征:即在一 ...
- window.returnValue跨域传值问题[转]
主页面用window.showModalDialog的时候,如果直接打开其它系统的页面,这时候别人的页面在window.returnValue=1;这样返回值的时候,主页面是取不到返回值的,原因就是因 ...
- HTML5 window/iframe跨域传递消息 API
原文地址:HTML5′s window.postMessage API 在线示例:Using HTML5's window.postMessage(请打开控制台看日志) 原文日期: 2010年09月0 ...
- (二)文档请求不同源之window.name跨域
一.基本原理 window.name不是一个普通的全局变量,而是当前窗口的名字.这里要注意的是每个iframe都有包裹它的window,而这个window 是top window的子窗口,而它自然也有 ...
- (二)文档请求不同源之window.postMessage跨域
一.基本原理 HTML5为了解决跨域,引入了跨文档通信API(Cross-document messaging).这个API为window对象新增了一个window.postMessage方法,允许跨 ...
- window.name跨域实现
参考:window.name实现的跨域数据传输 有三个页面: a.com/app.html:应用页面. a.com/proxy.html:代理文件,一般是一个没有任何内容的html文件,需要和应用页面 ...
- window.name 跨域数据传输
通过window.name可以实现跨域数据传输. 要解决的功能: www.a.com/a.html 需要获取到 www.b.com/b.html页面内容的数据 需要3个页面 www.a.com/a. ...
随机推荐
- java基础 关于final修饰符
final作为一个修饰符,可以修饰类.变量.函数. 1.被final修饰的类不可以被继承(保护封装性),为了避免被继承,被子类复写: 2.被final修饰的函数不可以被复写 3.被final修饰的变量 ...
- ccf 201712-4 行车路线(30分超时)
问题描述 小明和小芳出去乡村玩,小明负责开车,小芳来导航. 小芳将可能的道路分为大道和小道.大道比较好走,每走1公里小明会增加1的疲劳度.小道不好走,如果连续走小道,小明的疲劳值会快速增加,连续走s公 ...
- python—异常
异常是在程序中不可避免的,当程序遇到一个异常时程序就会停止,可以使用try—except进行处理异常,即便在出现异常程序也可以继续运行. 语法: try: 代码 except 异常名: 处理异常的代码 ...
- Flask框架搭建一个日程表
目录 前言 项目介绍 技术栈 Flask Web开发流程 一.搭建环境 1.1: 创建虚拟环境 1.2: 安装依赖包 1.3: 创建依赖包列表文件 1.4: 测试hello word 二.应用程序开发 ...
- git 解决每次更新代码都要输入用户名密码的解决方案
使用git pull或者git push每次都需要输入用户名和密码很繁琐,耽误时间,现在教大家一条命令实现保存用户名和密码不用再输入 git config --global credential.he ...
- 论文笔记:Mask R-CNN
之前在一次组会上,师弟诉苦说他用 UNet 处理一个病灶分割的任务,但效果极差,我看了他的数据后发现,那些病灶区域比起整张图而言非常的小,而 UNet 采用的损失函数通常是逐像素的分类损失,如此一来, ...
- npm 如何安装npm包
1.每个插件或者组件都会在官方网站有教程. 以https://v4.bootcss.com 为例 2.vuetify的 3.moment 的库
- hyperledger fabric部署总结
之前在有道云笔记上分享过,但想想还是搬到这里来吧,以后统一方便整理自己的知识进入正题.... 之前在调研 hyperledger fabric,其实部署说明官网都有,只是东西都是国外的照着操作也会遇到 ...
- 深度探索C++对象模型
深度探索C++对象模型 什么是C++对象模型: 语言中直接支持面向对象程序设计的部分. 对于各个支持的底层实现机制. 抽象性与实际性之间找出平衡点, 需要知识, 经验以及许多思考. 导读 这本书是C+ ...
- 将mysql中的一张表中的一个字段数据根据条件导入另一张表中
添加字段:alter table matInformation add facid varchar(99) default ''; 导入数据:update matInformation m set ...