Fill input text forms on other website in iframe
By pressing submit button , input value copies from input textbox to iframe textbox (or opposit of it). you can implement it like:
test1.html
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var iframe = document.getElementById('myiframe');
var doc = iframe.contentDocument || iframe.contentWindow.document;
var elem = document.getElementById('username');
doc.getElementsByName('user')[0].value = elem.value;
});
});
</script>
</head>
<body>
<input type="text" id="username">
<input type="submit" id="submit">
<iframe id="myiframe" frameborder="1" src="test2.html"></iframe>
</body>
</html>
And test2.html :
<!DOCTYPE html>
<html>
<body>
<input type="text" name="user" id="user">
</body>
</html>
When you load a page from a different domain into an iframe
, you can't do anything to the iframe page from JavaScript in your page.
As far as the browser is concerned, the iframe is a separate window and you have no access to it. Imagine that the user had a banking page open in one window and your page open in another window. You know that the browser would not let your JavaScript code interfere with the banking page, right?
The same thing applies when the other page is in an iframe
. It's still a completely separate browser window, it's just positioned so it looks like it's inside your page.
In your working example, the code works because the username and password fields are not in an iframe
from a different domain. They are part of the same page that the JavaScript code is in.
If the iframe
is loaded from the same domain as your main page, then you can do anything you want to it, including filling in form fields. The code would be slightly different because you need to access the iframe
document instead of the main page document, but that's easy. But if the iframe
is from a different domain, you are out of luck.