简体   繁体   English

侦听iframe内容的addEventListener

[英]addEventListener that listens to the contents of an iframe

Background: I have written a bookmarklet (JavaScript) that appends an iframe to the current page you are viewing. 背景:我已经编写了一个书签(JavaScript),可将iframe附加到您正在查看的当前页面上。 This iframe's src attribute is pointing to a form back on my application. 该iframe的src属性指向我的应用程序中的表单。

Problem: I am trying to utilize addEventListener to detect if that form has been submitted. 问题:我正在尝试利用addEventListener来检测该表单是否已提交。 However, I don't seem to be able to access the elements within the iframe. 但是,我似乎无法访问iframe中的元素。

For example: 例如:

document.getElementById(remote_form_id).addEventListener("submit",afterSubmit,true)

does not work because the getElementByID call is returning null. 不起作用,因为getElementByID调用返回null。

My current work-around is to add an event listener on the iframe to listen for a "load" action and then call an intermediary function that ups a counter because I know how many times the iframe will be loaded before I need to call afterSubmit(). 我目前的解决方法是在iframe上添加事件侦听器,以侦听“加载”操作,然后调用增加计数器的中介函数,因为我知道在需要调用afterSubmit(之前,iframe将会加载多少次。 )。

document.getElementById(marklet_iframe_id).addEventListener("load",listenForSubmit,true)

function listenForSubmit(){
    if (count==1){afterSubmit();}
    count++;
}

Basically, I'm looking for a best practice cause this is a crap approach. 基本上,我正在寻找最佳实践,因为这是一种废话。

You can do something like this: 您可以执行以下操作:

var doc = document.getElementById(marklet_iframe_id).contentDocument;
var form = doc.getElementById(formId)
form.addEventListener("submit", afterSubmit, true)

Although it doesn't work in IE, you may want to look at the postMessage method of the pages' window objects. 尽管它在IE中不起作用,但您可能需要查看页面窗口对象的postMessage方法。 It allows you to asynchronously send string data between windows, even when direct access would be forbidden by the same-origin policy. 它允许您在窗口之间异步发送字符串数据,即使同源策略禁止直接访问也是如此。

Try the EasyXDM library which uses the best-available techniques in a given user's browser to achieve this. 尝试使用EasyXDM库 ,该在给定的用户浏览器中使用最佳技术。 It also is "best practice-y" in that its goal is to send messages between windows, and it's up to those windows to handle the messages, which mimicks the postMessage functionality available in HTML5 browsers. 它也是“最佳实践”,它的目标是在窗口之间发送消息,并且由这些窗口来处理消息,这类似于HTML5浏览器中可用的postMessage功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM