在 iframe 内触发按钮单击 [英] Trigger a button click inside an iframe

查看:143
本文介绍了在 iframe 内触发按钮单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 iframe 代码:

<iframe src="http://beta.sportsdirect.bg/checkout/onepage/" id="InnerIframe" class="FrameCSS" scrolling="no"></iframe>

这是上面的 iframe 调用的按钮的 HTMl 代码:

这是我用来在页面加载时触发按钮点击的 jQuery 函数:

 $('#SuperWebF1').trigger( "click" );

但是只有当我将 jQuery 代码放在按钮的源代码中并且 iframe 使用脚本调用按钮时,它才会这样工作.

我想创建一个从 iframe 外部单击按钮的事件.可能吗?

提前致谢!

解决方案

注意:如果 iframe 的 src 指向跨域页面,.contents() 将不起作用.更多:跨域 iframe 问题获取跨域 iframe 的 DOM 内容

//在DOM准备好后执行代码$(函数(){//找到iframe让 iframe = $('#main_iframe');//在iframe中找到按钮let button = iframe.contents().find('#main_button');//触发按钮点击button.trigger("点击");});

<!--添加jQuery库--><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

如果您需要在 iframe 中操作另一个页面,请搜索官方 API 或 GET 参数.示例:Youtube 嵌入视频Google Maps Embed Api

This is the iframe code:

<div id="OutDiv" class="outerdiv">
    <iframe src="http://beta.sportsdirect.bg/checkout/onepage/" id="InnerIframe" class="FrameCSS" scrolling="no"></iframe>
</div>

Here is the HTMl code of the button which the iframe above is calling:

<button type="button"  id="SuperWebF1" title="Continue" class="button">Continue</button>

Here is the jQuery function that i use to trigger the click of the button when page is loaded:

 $('#SuperWebF1').trigger( "click" );

But this is working like that only when i place the jQuery code inside the source of button and the iframe is calling the button with the script.

I want to make an event which is clicking the button from outside the iframe. Is it possible ?

Thanks in advance!

解决方案

NOTE: .contents() does not work if iframe's src points to cross domain page. More: Cross domain iframe issue and Get DOM content of cross-domain iframe

//execute code after DOM is ready
$(function() {

  //find iframe
  let iframe = $('#main_iframe');
  
  //find button inside iframe
  let button = iframe.contents().find('#main_button');
  
  //trigger button click
  button.trigger("click");
  
});

<!--Add jQuery library-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If you need to manipulate another page inside iframe, search for official API or GET parameters. Example: Youtube Embed Video, Google Maps Embed Api

这篇关于在 iframe 内触发按钮单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆