iframe 编辑内部页面的输入框及事件监听
时间: 2023-12-14 07:37:58 浏览: 87
可以通过以下步骤实现:
1. 在父页面中添加一个 iframe 标签,设置其 src 属性为要嵌入的页面的 URL。
2. 在 iframe 中的页面中添加需要监听的事件。
3. 在父页面中获取 iframe 中的输入框元素,以及其他需要监听的元素。
4. 使用 JavaScript 中的 postMessage() 方法向 iframe 中发送消息,监听 iframe 中的事件并做出相应处理。
下面是一个示例代码:
父页面代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>父页面</title>
</head>
<body>
<iframe id="my-iframe" src="inner-page.html"></iframe>
<script>
// 获取 iframe 中的输入框元素
var iframe = document.getElementById("my-iframe");
var innerInput = iframe.contentWindow.document.getElementById("inner-input");
// 监听 iframe 中的事件
window.addEventListener("message", function(event) {
if (event.origin !== "http://localhost:8000") {
return;
}
// 处理事件
if (event.data.type === "input") {
console.log("输入框的值为:" + event.data.value);
} else if (event.data.type === "button") {
console.log("点击了按钮!");
}
});
// 向 iframe 发送消息
function sendMessage(type, value) {
iframe.contentWindow.postMessage({
type: type,
value: value
}, "*");
}
</script>
</body>
</html>
```
内部页面代码:
```html
<!DOCTYPE html>
<html>
<head>
<title>内部页面</title>
</head>
<body>
<input type="text" id="inner-input">
<button id="inner-button">点击我</button>
<script>
// 监听输入框的输入事件
var innerInput = document.getElementById("inner-input");
innerInput.addEventListener("input", function() {
// 向父页面发送消息
window.parent.postMessage({
type: "input",
value: innerInput.value
}, "*");
});
// 监听按钮的点击事件
var innerButton = document.getElementById("inner-button");
innerButton.addEventListener("click", function() {
// 向父页面发送消息
window.parent.postMessage({
type: "button"
}, "*");
});
</script>
</body>
</html>
```
在这个示例中,父页面和内部页面都是同一个域名下的页面,所以使用了通配符 "*" 来接受所有来源的消息。在实际应用中,应该根据需要设置特定的来源。
阅读全文
相关推荐


















