user2489195
user2489195

Reputation: 11

getElementByID("") with online src iframe

I have this code working fine with local file:

<html> 
<body>
<iframe id="frame1" name="frame1" frameborder=0 src="form.html" width=100% height=70%></iframe>
</body> 
<script type='text/javascript'>
    window.onload= function(){
        var iframe = document.getElementById('frame1');
        var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
        var input = innerDoc.getElementsByName('input1')[0].value;
        alert(input);
    }
</script>
</html>

form.html:

<input name="input1" type="text" value="testing"/>

Everything ok, but when I change iframe's src:

<iframe id="frame1" name="frame1" frameborder=0 src="form.html" width=100% height=70%></iframe>

With:

<iframe id="frame1" name="frame1" frameborder=0 src="http://test.hklearningmap.com/form.html" width=100% height=70%></iframe>

It not working. How can I make it work without uploading local file to the same location with form.html? Thanks.

Upvotes: 1

Views: 285

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1073998

You're running into the Same Origin Policy that browsers impose. JavaScript code running in a window from Origin A cannot access the document in a window (frame) from Origin B.

There are some exceptions, such as when both documents assign the same value to document.domain. But there are restrictions on the values that can be set (loosely, you can only set a superdomain, e.g. you can set example.com from a page loaded from www.example.com), and of course both documents have to set it (because that cooperation is what tells the browser it's okay to allow cross-origin scripting).

Upvotes: 1

user796443
user796443

Reputation:

You cannot access remote html content with js just because you load it in iframe. Read about same origin policy.

Upvotes: 0

Related Questions