Issue
I have two applications , one is angular js application and other is angular 10 application which are running in my local.I need to access a page from Angular 10 using iframe and need to post some message to the Angular 10 application using iframe from angular js application.
But i am unable to verify using below code weather postMessage is successful or not and also is there any issue connecting to new Angular application while sending the message. There are no errors in the console of the application.
Angular JS application code: This is running in local on port 8090. Added this below code in one file called index.js file.
var iframeUrl = "http://localhost:4200/indexing";
var htmlContent = "<iframe id='myframe' src="+iframeUrl+" "+"frameBorder='0'"+ "></iframe>";
newElement = angular.element(htmlContent);
$compile(newElement)($scope);
element.replaceWith(newElement);
var ifrmaeWindow= newElement.get(0).contentWindow; // Getting iframe window object
ifrmaeWindow.postMessage('Hello World!','http://localhost:4200/');
New Angular 10 application : This application is running in local on port 4200. below is the listener code added in index.html
<script>
window.addEventListener("message",function(message){
console.log("Received msg in angular="+message.origin);
console.log("Received msg in angular="+message.data);
},false);
</script>
Please let me know what is wrong in this code flow and why it is not sending messgages using postMessage. Also how do i verify whether the problem is in received end or sender end. Any help on this would be really appreciated. Thanks in advance.
Solution
Two applications running on different ports are actually considered different domains and iframes will be blocked via same origin policies: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
In order to get around this in your applications you should first try specifying document.domain = "localhost"
in both applications and then they should be able to communicate whilst on different ports
Also, within your angular application you may find it easier to add a HostListener
binding for the events, i.e.
@HostListener("window:message", ["$event"]) onPostMessage(event: any) {
if (event.origin === "http://localhost:8090") {
console.log("message from iframe", event);
}
Answered By - chrismclarke
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.