Accessing a text Input inside iFrame (Google Forms) - Javascript
Cutting to the chase:
I have a Google Forms survey, and basically I need to dynamically edit one of its text-inputs.
The Forms survey is actually 1 out of 6 possible surveys, so Javascript adds it:
'<iframe name="survey" id="ifrm" src="https://spreadsheets.google.com/spreadsheet/embeddedform?formkey=dHpYM1NvTF开发者_Go百科N4OElNWnBJWUtjdHhld2c6MQ" width="760" height="623" frameborder="0" marginheight="0" marginwidth="0">Loading...</iframe>'
The trouble is accessing that textbox - I used setTimeout()
to wait until the iFrame is loaded properly. And then I want to do this:
function writeEncoded() {
alert("now attempting to inject");
var iF = document.getElementById('ifrm');
alert( iF);
//works up to here
var form = iF.contentWindow.document; //does not run.
alert (form);
form.getElementById('entry_3').value = "Hi";
}
Any ideas what's going wrong? Thanks guys.
You’re seeing Same Origin Policy in action.
On the web, content on one website is mostly not allowed to interact with content on another.
Since the iframe
is loaded from https://spreadsheets.google.com
and (I’m guessing) your webpage is on another website (like http://example.com/
), your JavaScript can’t see anything inside the iframe
(and Google’s JavaScript can’t see anything on your webpage).
Why? Same Origin Policy is meant to protect you. Without it, I could load google.com
into an iframe
on my website and, with JavaScript, read your email address (if you’re logged in). Or, I could load facebook.com
and read your name and quite a bit of other personal information out of the page.
The iframe is unusual in that it "lives" in two place in the browser javascript heirarchy. It's part of the window.frames collection because it's a kind of frame AND it's also a part of the document tree because it's an element. You can use the following line to access the element iframe and then do what you want to with it.
window.frames[x].document.getelementById('')
with x being 0 if there are no other iframes in the document.
精彩评论