Cross-window communication
lastmod 2022-06-02created 2022-06-023 edits
An explanation of how to communicate between iframes.
Parent window -> child window
let passData = {member_id:'jjong2028', member_name:'쫑'};
let iframe = document.getElementById('qwer-iframe').contentWindow;
iframe.postMessage(passData, 'http://qwer.co.kr')
/* 넘길프레임.postMessage(넘겨줄 데이터, 허용되는 도메인) */
Child window -> parent window
window.onload = function() {
let passData = { returnValue : 200 };
window.parent.postMessage(passData, 'http://asdf.com');
}
Receiving data
The same for both the parent window and the child window.
window.addEventListener('message', function(e) {
//e.data ==> 수신 받은 데이터
//e.origin ==> 허용된 도메인
if(e.data.member_id == 'jjong2028') {
//받은 아이디값이 jjong2028 일때의 로직 처리
}
});
Troubleshooting
DOMException: Failed to execute '...' could not be cloned
vue.esm.js?4b29:1906 DOMException: Failed to execute 'postMessage' on 'Window': function onRefreshTokenError() {
clearSession();
moveTo(_router_names_root__WEBPACK_IMPORTED_MO...<omitted>... } could not be cloned.
at VueComponent.onFrameLoad (webpack-internal:///./node_modules/babel-loader/lib/index.js!./node_modules/ts-loader/index.js??clonedRuleSet-41[0].rules[0].use[1]!./node_modules/@vue/vue-loader-v15/lib/index.js??vue-loader-options!./src/pages/main/MainPlugin.vue?vue&type=script&lang=ts&:85:32)
at invokeWithErrorHandling (webpack-internal:///./node_modules/vue/dist/vue.esm.js:1871:26)
at HTMLIFrameElement.invoker (webpack-internal:///./node_modules/vue/dist/vue.esm.js:2196:14)
at original._wrapper (webpack-internal:///./node_modules/vue/dist/vue.esm.js:7599:25)
When passing messages between iframes, an error saying the data cannot be copied, like the one above, may occur. Data tied to another window, such as window or document, cannot be copied (cloned).
See also
Favorite site
- Cross-window communication
- Window.postMessage() - Web API | MDN
- EventTarget.addEventListener() - Web API | MDN
- iframe communication with other domains
Pages that link here