Cross Domain Communication in VueJs
Cross domain communication b/w Vue component and iframe.
Cross domain communication (also called Cross-origin) can be difficult and security risks. “window.postmessage()” method gives a provision for sending cross-domain e.g.: between a page and iframe or pop-up.
Required methods and their syntax
- window.postMessage() — to send the message to window
- window.addEventListener(“message”, targetOrigin, [transfer]) — to receive and process the message
Example
If you are using vuejs for iframe and target window both.
- Lets pick a iframe first from where you want to transfer object or any message to target window
In this component where we going to send message to parent window. here we have button with “sendMessage” method. when we click on button “sendMessage” triggered and message sent to parent window by “window.parent.postMessage()”. we are using “window.parent” bcz we are sending event to parent window where iframe is embed.
window.parent.postMessage({"data": data}, 'https:://www.xyz.com');
2. In Parent component we attach “window.addEventListener()” to mounted hook and also embed “iframe”. we add Callback function in “addEventListener”.
“window.addEventListener(“message”, this.iframeEvent, false)”
Conclusion
To call methods and access the content of another window, we should first have a reference to it.
window.postMessage() is a safe way to send messages between windows in different domains or origins. One can also post to an IFrame.
The data being sent is serialized and will accept almost any type of simple or complex data
For iframes, we can access parent/children windows using:
“window.frames” — a collection of nested window object
“window.parent, window.top” — are the references to parent and top window
“iframe.contentWindow” — is the window inside an <iframe> tag