admin管理员组

文章数量:1201147

I'm trying to get access to a form and its elements. The form is within an iframe and the javascript code that is accessing the form is within the main document.

I'm not sure what else I should put into the question, so please let me know if I need to add something else.

(form and main page are in the same domain)

Thanks

I'm trying to get access to a form and its elements. The form is within an iframe and the javascript code that is accessing the form is within the main document.

I'm not sure what else I should put into the question, so please let me know if I need to add something else.

(form and main page are in the same domain)

Thanks

Share Improve this question edited Jan 25, 2009 at 19:57 cbrulak asked Jan 25, 2009 at 19:16 cbrulakcbrulak 15.6k20 gold badges63 silver badges101 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 15
var ifr = document.getElementById( yourIframeId );
var ifrDoc = ifr.contentDocument || ifr.contentWindow.document;
var theForm = ifrDoc.getElementById( yourFormId );

Or you could have some code in the frame that sets a variable in parent to the form, but I wouldn't trust that method.

If your iframe has a name attribute, that can be used as a window name. If the frame name is "myframe":

myframe.document.getElementById("myform") // gives you the form element

Just made bookmarklet based on my older post Is it possible to save form data to a data file on the local computer and then reload that text file back into a form to select those same items?

It is reads inside iframe and set result JSON to textarea and prints to console:

javascript:o=document.getElementById("wf_IFid").contentDocument;
f=o.getElementsByTagName("input"), longest=f.length;
frm=f;
values={};
p=0;
for(a=0;a<longest;a++){
  el=frm[a];
  switch(el.type){
    case "checkbox":
      values[el.name]=el.checked;
      break;
    case "radio":
      if(el.checked)values[el.name]=el.value;
      else if(values[el.name]===undefined)values[el.name]=false;
      break;
    case "select-one":
      values[el.name]=el.selectedIndex<0?-1:el.options[el.selectedIndex].value;
      break;
    case "select-multiple":
      values[el.name]=[];
      for(i=0;i<el.options.length;i++){
        if(el.options[i].selected)values[el.name].push(el.options[i].value)
      }
      break;
    case "fieldset":
      break;
    case "button":
      break;
    case "submit":
      break;
    case "reset":
      break;
    case "file":
      break;
    case undefined:
      break;
    default:
      {
        if(el.getAttribute("aria-label")&&el.value){
          key=p++ + "|" + el.getAttribute("aria-label");
          values[key]=el.value
        }
      }
  }
}
t=o.createElement("textarea");
t.value=JSON.stringify(values, null, 2);
o.body.prepend(t);
console.log(JSON.stringify(values, null, 2));

本文标签: javascriptaccessing a form that is in an iframeStack Overflow