在 IE 中的不同窗口上执行 try/catch
考虑一个包含 iframe 的页面。 iframe 的内容可能如下所示
<script type="text/javascript">
window.foo = function () {
nonExisting();
};
window.bar = function () {
throw "An error!";
};
</script>
现在,我想执行如下所示的内容:
try {
iframe.contentWindow.foo();
} catch (e) { console.log('ok'); }
这
try {
iframe.contentWindow.bar();
} catch (e) { console.log('ok'); }
就是我得到的:
- Chrome/Firefox/Opera - 'ok', 'ok'
(预期行为) - IE8 - “预期对象”错误,未捕获
异常 这里发生了什么?当我使用 try/catch 块时,这怎么可能是未捕获的异常?这是一个错误吗?或者规范中是否有任何内容允许这种行为?
最重要的是:我能让它正常工作吗?
Consider a page containing an iframe. The iframe's content might look like this
<script type="text/javascript">
window.foo = function () {
nonExisting();
};
window.bar = function () {
throw "An error!";
};
</script>
Now, I wanna execute something like this:
try {
iframe.contentWindow.foo();
} catch (e) { console.log('ok'); }
and
try {
iframe.contentWindow.bar();
} catch (e) { console.log('ok'); }
This is what I get:
- Chrome/Firefox/Opera - 'ok', 'ok'
(expected behaviour) - IE8 - "Object expected" error, Uncaught Exception
WTF is going on here? How could that be an uncaught exception when I'm using a try/catch block? Is that a bug? Or does anything in the specs allow this behaviour?
And most importantly: Can I make it work as it should?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
那是因为您有一个拼写错误:
“An error”!
。如果我在模拟 IE8 的 IE9 上运行它而没有拼写错误,则它可以工作: http://jsfiddle.net/vsSgE/ 3/。
That's because you have a typo:
"An error"!
.If I run it without that typo on IE9 with IE8 emulated, it works: http://jsfiddle.net/vsSgE/3/.
我今天遇到了这个问题。我在父窗口中定义了几个“异常类”,并将其“导入”到子窗口(iframe)中,以便能够使用父窗口中的
instanceof
处理它们。像这样的东西:父窗口
子(iframe)窗口
使用此设置,我遇到了与您相同的问题 - 它在我测试的所有现代浏览器中都有效,但在IE8 出现“未捕获的异常”错误。
我的解决方法是向父窗口中的 MyExceptions 对象添加一个简单的实用程序函数,该函数执行实际的抛出操作,如下所示:
然后,每当我想从子窗口抛出异常以在父窗口中处理时,我都会执行
MyExceptions.Throw(new MyExceptions.RenderingException());
。不太优雅,但我需要让它工作。
I ran into this exact issue today. I had defined a couple of "exception classes" in the parent window, which I "imported" into the child window (iframe) to be able to handle them with
instanceof
in the parent. Something like this:Parent window
Child (iframe) window
Using this setup, I got the same problem as you did - it worked in all modern browsers I tested, but failed in IE8 with the "uncaught exception" error.
My workaround was to add a simple utility function to the MyExceptions object in the parent window that does the actual throwing, like this:
Then whenever I wanted to throw an exception from the child window to be handled in the parent, I would do
MyExceptions.Throw(new MyExceptions.RenderingException());
.Not exactly elegant, but I needed to get it working.