从iframe到iframe获取值

Getting value from iframe to iframe

本文关键字:iframe 获取      更新时间:2023-09-26

我有两个iframe在文档movie.htm:

<iframe id='movies' class='top' frameborder='0'></iframe>

<iframe src="moviesearch.htm" class="bottom" frameborder="0">
moviesearch.htm中有一个输入标签
<input id="search_str" type="text">

我想知道如何在文档movie.htm中使用JavaScript访问此值(包含在moviesearch.htm中)。

由于用户连续键入字段,因此需要在movie.htm中实时更新值。

我如何在JavaScript中实现这一点?

如果两个页面都在同一域中,您将能够iframe.contentDocument。https://developer.mozilla.org/en/XUL/iframe p-contentDocument

postMessage。https://developer.mozilla.org/en/DOM/window.postMessage

movie.htm:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
Current value:<div id="updatedvalue"></div>
<iframe src="moviesearch.htm"></iframe>
</body>
<script>
window.addEventListener
    ("message", function(e) {
    document.getElementById("updatedvalue").innerHTML = e.data;
    }, true);

</script>
</html>

moviesearch.htm:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="text" onkeyup="sendMessage(this.value)">
</body>
<script>
function sendMessage(message) {
    window.parent.postMessage(message, "*");
}
</script>
</html>