Capturing Cross-Origin iframe Events

2019-03-04 11:13发布

问题:

I have a website at domain A that contains an iframe used to show a video, which is hosted on YouTube. On the iframe load event, I am attempting to register for the keyup event in the iframe so I can close the video when a client presses the escape key. Here is an example of my code:

$(myIFrame).bind('load', function() {
    $(myIFrame.contentWindow.document).keyup(function(event) {
        console.log(event.keyCode);
    });
    alert('Event Registered');
});

I am getting the following exceptions:

Firefox: Error: Permission denied to access property "document"
Chrome: Uncaught SecurityError: Blocked a frame with origin "A" from accessing a frame with origin "https://www.youtube-nocookie.com". Protocols, domains, and ports must match.

Is there any way to register for events in a cross-origin iframe?

回答1:

The Same Origin Policy is preventing you from doing this.

An origin consists of a scheme, port, protocol and domain. If these match, then JavaScript can be used to register events or to manipulate the DOM.

If your site is http://example.com and the video is on http://example.org then cross domain scripting will not be possible because the domains do not match.

It is possible for different origins to communicate, however they both need to opt into this functionality. postMessage is one such JavaScript function. However as you have no control of the origin running the video it cannot help you here.

On solution for you may be to display the video inline on your page. This should enable you to capture events.