Javascript - Fill input with iframe-in Value

2019-05-18 03:53发布

问题:

I wanna fill input with my iframe-in Value.
i have two html file. 1.html and 2.html
First one (1.html) is like that:

<html>
<head>
<title>IFRAME TEST</title>
</head>
<body>
<input type="text" value="" id="mylovelytextbox"><br />
<iframe src="2.html" id="mylovelyiframe">
</body>
</html>

And second one (2.html) is like that:

<html>
<head>
<form method="get" action="">
<input type="hidden" name="thisone" value="mylovelychangedvalue">
</form>
</body>
</html>

I wanna fill mylovelytextbox in 1.html with thisone's value. How can i do that? -Sorry for bad english :(

Edit:

I run the code with @stano's help :) Now, my code is like that:

<html> <head> <title>IFRAME TEST</title> </head> <body> <input type="text" value="" id="mylovelytextbox"><input type="button" onClick="var iframe = document.getElementById('mylovelyiframe');console.log(iframe,doc,el);var doc = iframe.contentDocument || iframe.contentWindow.document;var el = document.getElementById('mylovelytextbox');el.value = doc.getElementsByName('thisone')[0].value;" value="Click"><br /> <iframe sandbox="allow-same-origin allow-scripts" src="2.html" id="mylovelyiframe"></iframe> </body> </html>

Thanks a lot, Stano!

回答1:

At first fix those missing tags

<iframe src="2.html" id="mylovelyiframe"></iframe>
</head><body>

and add some doctype, then you can use

<script type="text/javascript">
var iframe = document.getElementById('mylovelyiframe');
var doc = iframe.contentDocument || iframe.contentWindow.document;
var elem = document.getElementById('mylovelytextbox');
elem.value = doc.getElementsByName('thisone')[0].value;
</script>