【问题标题】:Triggering click across iframe触发跨 iframe 的点击
【发布时间】:2014-12-20 05:05:53
【问题描述】:

这是我的 iframe HTML 代码:

<ul id="titleee" >
<li><a href="http://adskpak.com/?type=2&id=jayvicious">CLick me</a></li>
</ul>

这是我的主页代码:

<iframe id="iframe" src="iframe1.php"></iframe>

<script>
$(document).ready( function(){
  $('#iframe').contents().find('#titleee').click();
});
</script>

好像没有触发点击事件。

【问题讨论】:

  • Jquery capture Click on Iframe 的可能重复项
  • 听起来您正试图触发点击 iframe 中的锚标记。为此,您需要在 iframe 文档中包含触发代码,并为来自父文档的消息添加侦听器。
  • 当你触发click()时,jQuery 不会导致&lt;a&gt; 加载href
  • @macguru2000 ,你运气好吗?
  • 您要确保您的 find() 查询找到锚标记而不是 #titleee 元素。

标签: javascript jquery iframe


【解决方案1】:

只需检查浏览器控制台是否有错误:-
您可能会收到此错误:-

SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://www.goibibo.com" from accessing a cross-origin frame.

如果您在同一域中同时拥有 父级和 iframe,这将起作用。将页面和 iframe 的 document.domain 设置为相同的值,即您的域,然后检查。

【讨论】:

    【解决方案2】:

    我认为这样的事情应该可以工作,虽然我不再使用 jQuery,只是使用普通的 Javascript。我相信你可以弄清楚如何在 jQuery 中做到这一点。

    这是您的 iframe 代码:

    <ul id="titleee" >
    <li><a href="http://adskpak.com/?type=2&id=jayvicious">Click me</a></li>
    </ul>
    <script>
      window.addEventListener("message", function() {
        if (event.origin === 'http://adskpak.com') {
          if (event.data === 'click the link') {
            document.querySelector('#titleee a').click();
          }
        }
      });
    </script>
    

    现在你的主页代码:

    <iframe id="iframe" src="iframe1.php"></iframe>
    <script>
      var iframeWindow = document.querySelector('#iframe').contentWindow;
    
      // this needs to happen after the load event,
      // but it is best if it happens on a user's action.
      window.onload = function() {
        iframeWindow.postMessage('click the link', '*');
      }
    </script>
    

    我已经测试了这段代码,它似乎可以工作,虽然当我做测试时我使用了 google.com,它实际上提醒了我一个跨域错误:

    Load denied by X-Frame-Options: https://www.google.com/ does not permit cross-origin framing.
    

    我不确定这是否与您相关,因为看起来您在自己的域上做所有事情,只是提醒一下。

    【讨论】:

      猜你喜欢
      • 2013-03-02
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多