iframe containing external wesbite does not fire t

2019-09-15 03:50发布

问题:

I understand that in order to fire the onscroll event handler in an iframe normally, the iframe must contain a site with the same domain name as the page that contains the iframe. But is there anyway at all that this can be done for an iframe that contains an external site?

The onscroll event handler:

<script type="text/javascript">
    window.onload = function() {
       var frm = document.getElementById("test").contentWindow;
       frm.onscroll = function(){
          alert("iframe scrolled");
       }
    }
</script>

The above js code works just fine for this:

<iframe id="test" src="http://www.<myDomain>.com"></iframe>

but not for this:

<iframe id="test" src="http://www.<anExternalSite>.com"></iframe>

If I can't do this my entire application will be useless. is there any workaround for doing this? any hack?

回答1:

Arbitrary external sites? No.

Co-operative external sites? Have the scroll event listener be bound by the site itself (to its body element) and communicate the event data using postMessage.



回答2:

Take a look at Quentin's answer or do something more hacky, serve the external site from your own domain using a proxy (http://httpd.apache.org/docs/2.2/mod/mod_proxy.html), because the crossdomain policy won't let you do this.

Be aware that the proxy will increase the traffic on your server.



回答3:

Use this:

  <html>
    <head>
      <style>
        #iframeoverlay { position: absolute; width: same-as-iframe; height: sams-as-iframe; anything-else: sams-as-iframe; z-index: 1-or-higher-if-the-iframe-is-over-1; }
      </style>
      <script>
        function alert() {
          alert("iframe scrolled");
        }
      </script>
    </head>
    <body>
      <iframe ... ></iframe><div id="iframeoverlay" onscroll="alert"></div>
    </body>
  </html>

Not sure if it'll work but try it.