- Cho phép nhận thông tin giữa các frames (connection between frames)
(https://wiki.izihelp.com/vi/knowledgebase/cach-chu-dong-mo-cua-so-chat/)
- Lắng nghe sự kiện “message”, kiểm tra thuộc tính “topic” là “initialized”
if (window.addEventListener) {
window.addEventListener('message', handleEvents, false);
} else if (w.attachEvent) {
window.attachEvent('onmessage', handleEvents);
}
function handleEvents(event) {
try {
var msg = JSON.parse(event.data);
if (msg.topic == "initialized") { <--- kiểm tra topic
fillingInfo(event.source); // <--- thực thi
}
} catch (error) {
console.error(error);
}
}
- Post message với topic là ‘fill-info’ => để điền thông tin (sau khi nhận sự kiện với topic = “initialized”)
function fillingInfo(source) {
var info = {
// [topic] must be "fill-info"
topic: 'fill-info',
// [data] contains keys, which created when add form setting, and values to be filled
data: {
name: 'tutorial',
email: 'no-email@email.com'
}
};
source.postMessage(JSON.stringify(info), '*');
}
Ví dụ
<script>
if (window.addEventListener) {
window.addEventListener('message', handleEvents, false);
} else if (w.attachEvent) {
window.attachEvent('onmessage', handleEvents);
}
function handleEvents(event) {
try {
var msg = JSON.parse(event.data);
if (msg.topic == "initialized") {
fillingInfo(event.source);
}
} catch (error) {
console.error(error);
}
}
function fillingInfo(source) {
var info = {
// [topic] must be "fill-info"
topic: 'fill-info',
// [data] contains keys, which created when add form setting, and values to be filled
data: {
name: 'tutorial',
email: 'no-email@email.com'
}
};
source.postMessage(JSON.stringify(info), '*');
}
</script>