简体   繁体   中英

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. 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.

The error is:

IE: "0x80070005 - JavaScript runtime error: Access is denied."

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."

Is there any way to listen for keydown events on iframes from another domain?

I use this angularJS code to setup a listener:

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. 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.

However, if you control both pages you can have the IFRAME voluntarily provide you data back. postMessage is a common technique:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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