web.html(外部網頁)
<!-- web.html(外部網頁) -->
<!DOCTYPE html>
<html>
<head>
<title>外部網頁</title>
</head>
<body>
<h1>外部網頁</h1>
<!-- 創建一個 <iframe> 元素 -->
<iframe src="iframe.html" id="myIframe"></iframe>
<script>
window.addEventListener("message", (e) => {
if (e.data.msg) {
console.log(e.data.msg);
}
});
</script>
</body>
</html>
iframe.html(在 <iframe> 內的網頁)
<!DOCTYPE html>
<html>
<head>
<title>嵌入的網頁</title>
</head>
<body>
<h1>嵌入的網頁</h1>
<!-- 添加一顆按鈕,用於觸發 JavaScript -->
<button id="sendMessageButton">點我發送訊息</button>
<script>
// 獲取當前網頁的網域
var currentDomain = window.location.origin + "/web.html";
// 獲取按鈕元素
var sendMessageButton = document.getElementById("sendMessageButton");
// 在按鈕點擊時,向外部腳本發送訊息
sendMessageButton.addEventListener("click", function () {
window.parent.postMessage(
{
msg: "我是來自 iframe 內傳遞的文字!",
},
currentDomain
);
});
</script>
</body>
</html>