关于javascript:触发iframe内的按钮点击

Trigger a button click inside an iframe

本问题已经有最佳答案,请猛点这里访问。

这是iframe代码:

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

以下是上述iframe调用的按钮的HTMl代码:

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

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

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

但这仅在将jQuery代码放在按钮源中并且iframe使用脚本调用按钮时才如此。

我要创建一个事件,即从iframe外部单击按钮。
可能吗 ?

提前致谢!


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

1
2
3
4
5
6
7
8
9
10
11
12
13
//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");
 
});
1
2
<!--Add jQuery library-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">

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