Background: I have written a bookmarklet (JavaScript) that appends an iframe to the current page you are viewing. This iframe's src attribute is pointing to a form back on my application.
Problem: I am trying to utilize addEventListener to detect if that form has been submitted. However, I don't seem to be able to access the elements within the iframe.
For example:
document.getElementById(remote_form_id).addEventListener("submit",afterSubmit,true)
does not work because the getElementByID call is returning 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().
document.getElementById(marklet_iframe_id).addEventListener("load",listenForSubmit,true)
function listenForSubmit(){
if (count==1){afterSubmit();}
count++;
}
Basically, I'm looking for a best pract开发者_开发知识库ice cause this is a crap approach.
Although it doesn't work in IE, you may want to look at the postMessage
method of the pages' window objects. It allows you to asynchronously send string data between windows, even when direct access would be forbidden by the same-origin policy.
You can do something like this:
var doc = document.getElementById(marklet_iframe_id).contentDocument;
var form = doc.getElementById(formId)
form.addEventListener("submit", afterSubmit, true)
Try the EasyXDM library which uses the best-available techniques in a given user's browser to achieve this. 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.
精彩评论