Javascript 在 iframe 内触发按钮单击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27332339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Trigger a button click inside an iframe
提问by Venelin Vasilev
This is the iframe code:
这是 iframe 代码:
<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:
这是上面 iframe 调用的按钮的 HTMl 代码:
<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:
这是我用来在页面加载时触发按钮点击的 jQuery 函数:
$('#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.
但是,只有当我将 jQuery 代码放在按钮的源中并且 iframe 使用脚本调用按钮时,才会这样工作。
I want to make an event which is clicking the button from outside the iframe. Is it possible ?
我想创建一个从 iframe 外部单击按钮的事件。是否可以 ?
Thanks in advance!
提前致谢!
回答by Amit Garg
NOTE: .contents() does not work if iframe's src points to cross domain page. More: Cross domain iframe issueand Get DOM content of cross-domain iframe
注意:如果 iframe 的 src 指向跨域页面,则 .contents() 不起作用。更多:跨域 iframe 问题和获取跨域 iframe 的DOM 内容
//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 中操作另一个页面,请搜索官方 API 或 GET 参数。示例:Youtube Embed Video, Google Maps Embed Api

