访问IFrame内的按钮

我正在寻找一种方法来访问iFrame中的按钮,并在另一个域中的iFrame内单击该按钮时触发单击事件。 尝试更深入地了解iFrame中的元素已经certificate是困难的。 到目前为止有没有人取得成功?

使用对iframe的src的ajax调用来获取其内容,并将其作为站点的一部分呈现(然后您可以挂钩)。

您无法直接从其他域访问iframe中的内容,因为这会违反安全规则。

如果我正确理解你的要求

您可以添加$('#iframe').load(function(){} ,它会监视iframe加载到您的DOM中。

加载iframe后,您可以将事件侦听器附加到按钮单击

 var iframe = $('#iframe').contents(); iframe.find("#button").click(function(){ //write code to close the popup }); 

上述过程可总结如下

 $('#iframe').load(function(){ var iframe = $('#iframe').contents(); iframe.find("#button").click(function(){ $('#popup').close() //May depend on your popup implementation }); }); 

这里的问题是同源策略阻止脚本访问具有其他来源的站点内容。 实际上,起源由以下部分组成。

 origin:://:/path/to/page.html 

如果协议,主机名和端口号不相同,则认为原点不同。

在这种情况下,由于同源安全策略,您无法从其他网站访问某个网站的内容。

为了克服它,你必须使用window.postMessage()来使用父子通信。

仅供参考: https : //developer.mozilla.org/en-US/docs/Web/API/Window/postMessage 。

Window.postMessage()方法安全地启用跨源通信。

假设您的父网站是example-parent.com ,在Iframe中您的加载网站example-iframe.com并且两者都使用http协议。 以下是我解决问题的方法。 在父网站中,为要接收的消息添加事件侦听器,如下所示。

 window.addEventListener('message',receiveMessage,false); function receiveMessage(event){ var origin = event.origin || event.originalEvent.origin; if(origin.indexOf('http://example-iframe.com')>=0) // check if message received from intended sender { if(event.data=="intended message format") // check if data received is in correct format { // call functionality that closes popup containing iframe }else{ // data received is malacious return; } }else{ // message is not received from intended sender return; } } 

从Iframe发布消息到父网站如下。 发布消息语法: otherWindow.postMessage(message, targetOrigin, [transfer]);

 function sendMessage(){ parent.postMessage('intended message format','http://example-parent.com'); } 

正确使用postMessage() ,否则可能导致跨站点脚本攻击。

我很抱歉这样对你说,但你不能。 因为那将违反浏览器设置的CORS(跨源资源共享)规则,并且它不会让你破坏它们。 因为它的全能。

它会在您的控制台中出现错误“Access-Control-Allow-Origin”。

希望你觉得它有用。

如果你想在你的网站上做一些事情,你可以在下面问一下,我可能会给你一个替代方案。