Listen for keydown events in a cross-domain iframe

I want to listen for keydown events in an iframe to stop the backspace from executing. It works as long as the page in the iframe comes from one domain, but when it comes from a different domain, it fails when the content () method is called.


IE: "0x80070005 - JavaScript Runtime Error: Access Denied."

Chrome: "Uncaught SecurityError: Could not read contentDocument property from" HTMLIFrameElement ": Blocked the source frame" domain_a "from accessing the source frame" domain_b ". Protocols, domains, and ports must match."

Is there a way to listen for keydown events on iframes from a different domain?

I am using this angular code to set up a listener:

angular.module('', [])
.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);
                    preventKeyPress = false;

            if (preventKeyPress)



source to share

1 answer

Not. You cannot do this, and it has nothing to do with AngularJS. This is a security breach specifically designed to prevent an IFRAME-in at Bank of America from reaching your own site and stealing user credentials from that frame.

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

Basically, you catch the keystrokes in the IFRAME and then send a message to the parents with the details. Browsers allow this because it is voluntary and collaborative - you have to control both the sender and the recipient, so it cannot be used to steal something from the user without knowing it.



All Articles