views:

11

answers:

1

I am playing with bookmarklets. I add a frame to the document, and load some elements, like so:

var myframe=document.createElement("iframe");
myframe.setAttribute('id','a_frame');
myframe.src='http://localhost:81/nframe.html';
document.body.insertBefore(myframe,document.body.firstChild);

this is what nframe.html looks like:

<form id="sr_cart" name="sr_cart" action="localhost:81/dosomething.php">
Item Number: <input type="text" name="ItemNum" id="sr_item" value="" /> 
<input type="submit" value="Submit" /> 
</form>

Looks great so far: when I click on my bookmarklet, the document has been modified correctly

Then I try to look up the item number (or the form)

cart = document.getElementById('sr_cart');

I'm perplexed as to why this comes back a null. (looking up sr_item does the same thing. looking up something that is not in my frame works fine)

TIA

A: 

You're searching the wrong document. Start from the iframe's document, like so:

var docEl = myframe.contentDocument || myframe.contentWindow.document || myframe.document;

if (docEl) {
    var cart = docEl.getElementById('sr_cart'); // this is what you need
}

I'm pretty sure this is what you need to do - I've done it before but I found verification in Closure Tools' code (Google's JS Library) - http://code.google.com/p/doctype/wiki/ArticleFrameContentDocument

Dan Beam
Thanks for the suggestion - that sounded right, but it still shows up as null
Sid
pretty strange - I am looking at docEl in firebug, and it is a document, but has no children!
Sid
I revisited your code - it looks like you're switching port number in the URL of the `iframe`'s `src`, right? If the hostname, protocol, and port ALL don't match up, the browser will not allow communication between the two frames. Look up Same the Origin Policy.
Dan Beam
You're right , but I would expect javascript to then give me an 'access denied' error.
Sid