简体   繁体   English

使用跨域侦听iframe中的keydown事件

[英]Listen for keydown events in iframe with cross-domain

I want to listen for keydown events in an iframe to stop backspace from being executed. 我想在iframe中监听keydown事件以阻止执行后退空间。 It works as long as the page in the iframe comes from same domain, but when it comes from another domain it fails when the contents() method is called. 只要iframe中的页面来自同一个域,它就可以工作,但是当它来自另一个域时,它会在调用contents()方法时失败。

The error is: 错误是:

IE: "0x80070005 - JavaScript runtime error: Access is denied." IE: “0x80070005 - JavaScript运行时错误:访问被拒绝。”

Chrome: "Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "domain_a" from accessing a frame with origin "domain_b". Protocols, domains, and ports must match." Chrome: “Uncaught SecurityError:无法从'HTMLIFrameElement'读取'contentDocument'属性:阻止具有原始域”domain_a“的帧访问源为”domain_b“的帧。协议,域和端口必须匹配。”

Is there any way to listen for keydown events on iframes from another domain? 有没有办法在另一个域上监听iframe上的keydown事件?

I use this angularJS code to setup a listener: 我使用此angularJS代码来设置一个监听器:

KeyDownService.preFilterKeyDown($(this).contents());
...
angular.module('portal.services.keyHandlers.keyDownService', [])
.service('KeyDownService', function () {
    //Prevents shortcut keys (for instance backspace) in being executed in an iframe or document.
    this.preFilterKeyDown = function ($document) {
        $document.keydown(function (e) {
            var preventKeyPress;
            switch (e.keyCode) {
                case 8: //Backspace
                    preventKeyPress = preventBackspace(e);
                    break;
...
                default:
                    preventKeyPress = false;
            }

            if (preventKeyPress)
                e.preventDefault();
        });
    }

No. You cannot do this and it has nothing to do with AngularJS. 不,你不能这样做,它与AngularJS无关。 It is a security violation specifically to prevent you from IFRAME-ing in Bank of America into your own site and stealing a user's credentials from that frame. 这是一种安全违规行为,专门用于防止您将美国银行的IFRAME带入您自己的网站并从该框架中窃取用户的凭据。

However, if you control both pages you can have the IFRAME voluntarily provide you data back. 但是,如果您控制两个页面,您可以让IFRAME自愿为您提供数据。 postMessage is a common technique: postMessage是一种常见的技术:

http://caniuse.com/#search=postMessage http://caniuse.com/#search=postMessage

Essentially you trap the keystrokes in the IFRAME and then send a message back to the parent with the details. 基本上,您可以在IFRAME中捕获击键,然后使用详细信息将消息发送回父级。 Browsers allow this because it's voluntary and cooperative - you have to control both the sender and the receiver, so it can't be used to steal something from the user without them knowing it. 浏览器允许这样做,因为它是自愿和合作的 - 你必须控制发送者和接收者,所以它不能用来在没有他们知道的情况下从用户那里偷东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM